-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
83 lines (70 loc) · 2.94 KB
/
Copy pathbot.py
File metadata and controls
83 lines (70 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from __future__ import annotations
import os
import sys
import time
from telegram_ai_bot import AIClient, TelegramClient
HELP = (
"Send me a message and I will answer through the configured "
"OpenAI-compatible API.\n\n/model - show model\n/reset - clear history"
)
def required_env(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
def main() -> int:
try:
telegram = TelegramClient(required_env("TELEGRAM_BOT_TOKEN"))
ai = AIClient(
api_key=required_env("APIMART_API_KEY"),
base_url=os.environ.get("AI_API_BASE_URL", "https://api.apimart.ai/v1"),
model=os.environ.get("AI_MODEL", "gpt-4o-mini"),
)
max_history = max(2, int(os.environ.get("MAX_HISTORY_MESSAGES", "12")))
except (RuntimeError, ValueError) as exc:
print(exc, file=sys.stderr)
return 2
histories: dict[int, list[dict[str, str]]] = {}
offset: int | None = None
print(f"Bot started with model {ai.model}. Press Ctrl+C to stop.")
while True:
try:
for update in telegram.get_updates(offset):
offset = int(update["update_id"]) + 1
message = update.get("message") or {}
text = (message.get("text") or "").strip()
chat = message.get("chat") or {}
if not text or "id" not in chat:
continue
chat_id = int(chat["id"])
if text == "/start":
telegram.send_message(chat_id, HELP)
continue
if text == "/model":
telegram.send_message(chat_id, f"Current model: {ai.model}")
continue
if text == "/reset":
histories.pop(chat_id, None)
telegram.send_message(chat_id, "Conversation history cleared.")
continue
history = histories.setdefault(chat_id, [])
try:
reply = ai.chat(history, text)
except Exception as exc: # keep polling after a provider failure
telegram.send_message(chat_id, f"AI request failed: {type(exc).__name__}")
continue
history.extend(
[
{"role": "user", "content": text},
{"role": "assistant", "content": reply},
]
)
histories[chat_id] = history[-max_history:]
telegram.send_message(chat_id, reply)
except KeyboardInterrupt:
return 0
except Exception as exc: # keep the polling loop alive after network errors
print(f"Polling error: {type(exc).__name__}: {exc}", file=sys.stderr)
time.sleep(3)
if __name__ == "__main__":
raise SystemExit(main())