Skip to content

Commit fa59b0a

Browse files
committed
v0.8.5: centralize application version
Add repository-root VERSION as the single source of truth for the ChatKeke release version. Runtime startup output, /about, and the DuckDuckGo User-Agent now load the application version from VERSION instead of duplicating it in source files. Add regression coverage and document the release-version convention.
1 parent dc408c8 commit fa59b0a

7 files changed

Lines changed: 165 additions & 30 deletions

File tree

‎.catgitinclude‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,5 @@ src/utils.py
1010
config/config.ini
1111
src/reminder_poller.py
1212
src/reminder_handler.py
13+
VERSION
14+
src/app_version.py

‎README.md‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## 🤖 _Powered by ChatKeke_ 🚀
44

5+
> **Required OpenAI key migration:** OpenAI scheduled legacy user API keys for deactivation on **October 22, 2026**. Affected installations must create a key inside the intended OpenAI project, replace every deployed secret, verify the replacement, and then revoke the legacy key. See [the migration guide](./docs/API_KEY_MIGRATION.md).
6+
57
- **A simple-to-use, quick-to-deploy Python-based Telegram bot for OpenAI API & Perplexity API**
68
- **🎙 Transcribed Telegram voice messages via OpenAI speech-to-text models (Whisper and others)**
79
- Supports configurable STT models such as `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and legacy `whisper-1`
@@ -38,8 +40,35 @@
3840

3941
- **Telegram API bot token**
4042
- use the [`@BotFather`](https://t.me/BotFather) bot on Telegram to set up your bot and get a Telegram Bot API token for it
41-
- **OpenAI API token**
42-
- Get one from from: https://platform.openai.com/
43+
- **OpenAI project API key**
44+
- Create it while the intended organization and project are selected: https://platform.openai.com/api-keys
45+
- Store it as `OPENAI_API_KEY`; never commit it to Git
46+
47+
---
48+
49+
## Existing installations: do I need a new key?
50+
51+
**Yes**, when OpenAI has notified your organization that a key is a legacy user API key or it appears in the legacy **User API Keys** list. A key already created inside the intended project does not need replacement solely because of this deadline.
52+
53+
The request format remains:
54+
55+
```text
56+
OPENAI_API_KEY=<project key>
57+
Authorization: Bearer <project key>
58+
```
59+
60+
ChatKeke v0.8.5 removes the mutable global `openai.api_key`. The credential is now resolved once at startup and passed explicitly into every raw HTTP request and OpenAI SDK client. Optional `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` overrides are supported, but a normal project key does not require them.
61+
62+
Current users must:
63+
64+
1. Select the correct OpenAI organization and project and create a new project key. For an unattended deployment, a project service-account key is preferable where available.
65+
2. Replace `OPENAI_API_KEY` in every VPS/service environment, Docker secret or `.env`, GitHub Actions secret, staging deployment, and `config/api_token.txt` fallback still in use.
66+
3. Restart or redeploy every instance.
67+
4. Run `python3 scripts/verify_openai_key.py --live-request`.
68+
5. Test normal chat, tool calls, and speech-to-text when enabled.
69+
6. Revoke the legacy key only after every deployment passes.
70+
71+
Full instructions: [docs/API_KEY_MIGRATION.md](./docs/API_KEY_MIGRATION.md).
4372

4473
---
4574

@@ -74,11 +103,18 @@
74103

75104
3. **Set up your Telegram bot token:**
76105

77-
- Either set your Telegram Bot API token as `TELEGRAM_BOT_TOKEN` environment variable, or put it into a text file named `bot_token.txt` inside the `config/` directory (= `config/bot_token.txt`)
106+
- Either set your Telegram Bot API token as `TELEGRAM_BOT_TOKEN` environment variable, or put it into `config/bot_token.txt`.
107+
- Token precedence is controlled by `PreferEnvForBotToken` in `config/config.ini`:
108+
- `PreferEnvForBotToken = True`: use `TELEGRAM_BOT_TOKEN` first, then `config/bot_token.txt` if fallback is enabled.
109+
- `PreferEnvForBotToken = False`: use `config/bot_token.txt` first, even when `TELEGRAM_BOT_TOKEN` is set. This is the manual/local override mode.
110+
- To **never** fall back to the environment variable when using the file override, also set `AllowBotTokenFallback = False`.
111+
- Existing installations should preserve their local `config/config.ini` when updating. Do not replace it wholesale with the repository default; use `src/configmerger.py` or merge the changed settings manually.
78112

79-
4. **Set up your OpenAI API token:**
113+
4. **Set up your OpenAI project API key:**
80114

81-
- Either as `OPENAI_API_KEY` environment variable or put into a text file named `api_token.txt` inside the main program directory
115+
- Recommended: set the project key as `OPENAI_API_KEY`
116+
- Backwards-compatible fallback: place it in `config/api_token.txt` and run `chmod 600 config/api_token.txt`
117+
- Startup logs only the credential source and a short one-way fingerprint, never the secret
82118

83119
5. **Other modules:**
84120

@@ -103,9 +139,9 @@
103139
1. **Docker** must be installed on your machine.
104140
- If not installed, you can download and install it from [Docker's official site](https://www.docker.com/get-started).
105141

106-
2. **Telegram Bot API Key** and **OpenAI API Key**:
142+
2. **Telegram Bot API Key** and **OpenAI project API key**:
107143
- You will need a valid Telegram Bot API key. You can get one by creating a bot with [BotFather](https://core.telegram.org/bots#botfather).
108-
- You will also need an OpenAI API key. If you don't have one, you can generate it from the [OpenAI API page](https://beta.openai.com/signup/).
144+
- Create an OpenAI project API key from the [OpenAI API Keys page](https://platform.openai.com/api-keys). Do not use a legacy user key for a new deployment.
109145

110146
### **Step 1: Clone the Repository**
111147

@@ -126,7 +162,15 @@ Run the script:
126162
./docker_setup.sh
127163
```
128164

129-
Follow the instructions provided by the script. It will ask for your OpenAI API key and Telegram Bot API key, validate them, and create a `.env` file with your credentials.
165+
Follow the instructions provided by the script. It hides the OpenAI key while it is entered and writes `.env` with owner-only permissions.
166+
167+
Verify the replacement before revoking the old key:
168+
169+
```bash
170+
python3 scripts/verify_openai_key.py --live-request
171+
```
172+
173+
The GitHub Actions deployment uses a repository secret named `OPENAI_API_KEY`. Updating a local `.env` does not update that secret.
130174

131175
### **Step 3: Build the Docker Image**
132176

@@ -241,6 +285,21 @@ If you run into any issues, consult the logs or reach out on the repository's [I
241285

242286
# Changelog
243287

288+
> The current application version is stored in the repository-root `VERSION` file and loaded by the runtime from there. Update `VERSION` once for a release instead of duplicating the current version in source files.
289+
290+
- v0.8.5 - OpenAI project-key migration and explicit credential handling
291+
- Removed the mutable process-global `openai.api_key` and passed one resolved credential object explicitly into raw HTTP requests and the OpenAI SDK client.
292+
- Added optional `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` routing overrides without requiring them for normal project keys.
293+
- Added `docs/API_KEY_MIGRATION.md` and a current-user migration section to this README.
294+
- Added `scripts/verify_openai_key.py` for secret-safe project access and live Chat Completions checks.
295+
- Hardened key loading, fallback warnings, placeholder/whitespace rejection, and secret-free fingerprint logging.
296+
- Hardened Docker setup and GitHub Actions secret passing.
297+
- Preserved Telegram bot-token source precedence: `PreferEnvForBotToken = False` continues to force `config/bot_token.txt` ahead of `TELEGRAM_BOT_TOKEN`.
298+
- Upgrade patch/overlay does not modify `config/config.ini`, so local token-selection overrides are not clobbered.
299+
- Fixed the python-telegram-bot error handler to be async, preventing a secondary `NoneType`/`await` traceback when Telegram reports polling errors such as a `getUpdates` conflict.
300+
- Added API credential and Telegram token-precedence regression tests.
301+
- Centralized the application version in the repository-root `VERSION` file; runtime banners, `/about`, and the DuckDuckGo User-Agent now use that single source of truth.
302+
244303
- v0.8.4 - DuckDuckGo search reliability hotfix
245304
- Added HTTPX connection retries for DuckDuckGo/web fetches: `httpx.AsyncHTTPTransport(retries=2)` provides up to three connection attempts before a request fails.
246305
- Fixes intermittent `httpx.ConnectError` failures observed in live service operation, including failures whose underlying cause surfaced as `BrokenResourceError`.

‎VERSION‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
0.8.5

‎src/api_get_duckduckgo_search.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@
3737
from urllib.parse import quote, unquote_plus
3838

3939
import httpx
40-
import openai
41-
4240
from config_paths import CONFIG_PATH
41+
from api_key import APIKeyConfigurationError, build_openai_headers
4342
from openai_reasoning_compat import apply_reasoning_effort
43+
from app_version import VERSION as CHATKEKE_VERSION
4444

4545

4646
# ---------------------------------------------------------------------------
@@ -361,7 +361,7 @@ async def _run_lynx_dump(url: str) -> str:
361361
Raises RuntimeError on HTTP or Lynx rendering failure.
362362
"""
363363
headers = {
364-
"User-Agent": "Lynx/2.9.0 ChatKeke/0.8.4",
364+
"User-Agent": f"Lynx/2.9.0 ChatKeke/{CHATKEKE_VERSION}",
365365
"Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
366366
}
367367

@@ -499,7 +499,7 @@ async def _fetch_duckduckgo_results(search_terms: str) -> str:
499499
# Main DuckDuckGo search function
500500
# ---------------------------------------------------------------------------
501501

502-
async def get_duckduckgo_search(search_terms, user_message):
502+
async def get_duckduckgo_search(search_terms, user_message, openai_auth=None):
503503
"""
504504
Main public entry point used by text_message_handler.py.
505505
@@ -557,6 +557,7 @@ async def get_duckduckgo_search(search_terms, user_message):
557557
search_results=unique_text,
558558
retries=3,
559559
timeout=timeout,
560+
openai_auth=openai_auth,
560561
)
561562

562563
# Failsafe: if sub-agent result is empty, return DuckDuckGo results instead.
@@ -575,7 +576,14 @@ async def get_duckduckgo_search(search_terms, user_message):
575576
# OpenAI sub-agent call handler
576577
# ---------------------------------------------------------------------------
577578

578-
async def sub_agent_openai_call(user_message, search_terms, search_results, retries=3, timeout=30):
579+
async def sub_agent_openai_call(
580+
user_message,
581+
search_terms,
582+
search_results,
583+
retries=3,
584+
timeout=30,
585+
openai_auth=None,
586+
):
579587
"""
580588
Small OpenAI sub-agent for agentic DuckDuckGo browsing.
581589
@@ -589,8 +597,10 @@ async def sub_agent_openai_call(user_message, search_terms, search_results, retr
589597
search_terms = search_terms or ""
590598
search_results = search_results or ""
591599

592-
if not (openai.api_key or "").strip():
593-
logger.error("OpenAI API key is missing for DuckDuckGo sub-agent.")
600+
try:
601+
headers = build_openai_headers(openai_auth)
602+
except APIKeyConfigurationError as exc:
603+
logger.error("OpenAI credential is missing for DuckDuckGo sub-agent: %s", exc)
594604
return format_for_telegram_html(search_results)
595605

596606
timeout = max(1, int(timeout or DEFAULT_TIMEOUT))
@@ -639,11 +649,6 @@ async def sub_agent_openai_call(user_message, search_terms, search_results, retr
639649
include_tools=True,
640650
)
641651

642-
headers = {
643-
"Content-Type": "application/json",
644-
"Authorization": f"Bearer {openai.api_key}",
645-
}
646-
647652
for attempt in range(retries):
648653
try:
649654
logger.info(

‎src/app_version.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""ChatKeke application version, loaded from the repository-root VERSION file."""
2+
3+
from pathlib import Path
4+
5+
ROOT_DIR = Path(__file__).resolve().parents[1]
6+
VERSION_FILE = ROOT_DIR / "VERSION"
7+
8+
9+
def read_version(version_file: Path = VERSION_FILE) -> str:
10+
"""Return the application version from VERSION, failing loudly if invalid."""
11+
try:
12+
version = version_file.read_text(encoding="utf-8").strip()
13+
except OSError as exc:
14+
raise RuntimeError(f"Unable to read ChatKeke version from {version_file}: {exc}") from exc
15+
16+
if not version:
17+
raise RuntimeError(f"ChatKeke VERSION file is empty: {version_file}")
18+
if any(char.isspace() for char in version):
19+
raise RuntimeError(f"ChatKeke VERSION must contain one whitespace-free version: {version_file}")
20+
21+
return version
22+
23+
24+
VERSION = read_version()

‎src/main.py‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@
55
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
77
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8-
# version of this program
9-
version_number = "0.8.4"
10-
118
# Add the project root directory to Python's path
129
import sys
1310
from pathlib import Path
11+
from app_version import VERSION as version_number
1412
# Adding the project root to the Python path to resolve imports from root level
1513
sys.path.append(str(Path(__file__).resolve().parents[1]))
1614

@@ -27,7 +25,6 @@
2725
from logging.handlers import RotatingFileHandler
2826
from functools import partial
2927

30-
import openai
3128
import json
3229
import httpx
3330
import asyncio
@@ -59,7 +56,7 @@
5956

6057
import db_utils
6158
from bot_token import get_bot_token
62-
from api_key import get_api_key
59+
from api_key import APIKeyConfigurationError, load_openai_credentials
6360
import bot_commands
6461
import utils
6562
from modules import count_tokens, read_total_token_usage, write_total_token_usage
@@ -171,12 +168,17 @@ def __init__(self):
171168
from config_paths import CHAT_LOG_FILE_PATH
172169
self.chat_log_file = CHAT_LOG_FILE_PATH
173170

174-
# Attempt to get bot & API tokens
171+
# Resolve bot and OpenAI credentials once at startup. OpenAI credentials
172+
# are then passed explicitly to HTTP calls and SDK clients; no mutable
173+
# process-global openai.api_key is used.
175174
try:
176175
self.telegram_bot_token = get_bot_token()
177-
self.openai_api_key = get_api_key() # Store the API key as an attribute
178-
openai.api_key = self.openai_api_key
179-
except FileNotFoundError as e:
176+
self.openai_credentials = load_openai_credentials()
177+
# Compatibility attributes for older helper paths and private forks.
178+
self.openai_api_key = self.openai_credentials.api_key
179+
self.openai_organization = self.openai_credentials.organization
180+
self.openai_project = self.openai_credentials.project
181+
except (FileNotFoundError, APIKeyConfigurationError) as e:
180182
self.logger.error(f"Required configuration not found: {e}")
181183
sys.exit(1)
182184

@@ -433,7 +435,7 @@ async def handle_message(self, update: Update, context: CallbackContext) -> None
433435

434436
# ~~~~~~~~~~~~~~~~~~~~
435437
# Function to handle errors
436-
def error(self, update: Update, context: CallbackContext) -> None:
438+
async def error(self, update: Update, context: CallbackContext) -> None:
437439
self.logger.warning('Update "%s" caused error "%s"', update, context.error)
438440

439441
def run(self):

‎tests/test_version.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from __future__ import annotations
2+
3+
import sys
4+
from pathlib import Path
5+
6+
ROOT_DIR = Path(__file__).resolve().parents[1]
7+
SRC_DIR = ROOT_DIR / "src"
8+
if str(SRC_DIR) not in sys.path:
9+
sys.path.insert(0, str(SRC_DIR))
10+
11+
import app_version # noqa: E402
12+
13+
14+
def test_root_version_file_is_single_source_of_truth() -> None:
15+
expected = (ROOT_DIR / "VERSION").read_text(encoding="utf-8").strip()
16+
assert expected
17+
assert app_version.VERSION == expected
18+
assert app_version.read_version() == expected
19+
20+
21+
def test_read_version_rejects_empty_file(tmp_path: Path) -> None:
22+
version_file = tmp_path / "VERSION"
23+
version_file.write_text("\n", encoding="utf-8")
24+
25+
try:
26+
app_version.read_version(version_file)
27+
except RuntimeError as exc:
28+
assert "empty" in str(exc)
29+
else:
30+
raise AssertionError("empty VERSION should fail")
31+
32+
33+
def test_read_version_rejects_whitespace_inside_version(tmp_path: Path) -> None:
34+
version_file = tmp_path / "VERSION"
35+
version_file.write_text("1.2.3 beta\n", encoding="utf-8")
36+
37+
try:
38+
app_version.read_version(version_file)
39+
except RuntimeError as exc:
40+
assert "whitespace-free" in str(exc)
41+
else:
42+
raise AssertionError("VERSION containing whitespace should fail")

0 commit comments

Comments
 (0)