File size: 12,004 Bytes
a571bd0 3cdcea4 a571bd0 3cdcea4 a571bd0 3cdcea4 a571bd0 b65db79 3cdcea4 b65db79 a571bd0 3cdcea4 a571bd0 | 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | from __future__ import annotations
import logging
import re
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Message, Update, User
from telegram.constants import ChatType
from telegram.ext import (
Application,
ApplicationBuilder,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
from botik.config import FALLBACK_MODELS, Settings
from botik.gemini_client import GeminiError, GeminiService
from botik.storage import SQLiteStorage
logger = logging.getLogger(__name__)
BOT_INFO_KEY = "bot_info"
class TelegramBot:
def __init__(self, settings: Settings, storage: SQLiteStorage, gemini: GeminiService) -> None:
self.settings = settings
self.storage = storage
self.gemini = gemini
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
if message is None:
return
await message.reply_text(
"Привет. Я личный помощник на Gemini.\n\n"
"Пиши мне в личку или упоминай в группе. Команды: /help, /reset, "
"/soul, /reset_soul, /model."
)
async def help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
if message is None:
return
await message.reply_text(
"Что умею:\n"
"• отвечать в личке и группах;\n"
"• помнить историю текущего чата;\n"
"• понимать, кто пишет в группе;\n"
"• учитывать сообщение, на которое ты ответил свайпом;\n"
"• искать в интернете через Gemini, если это нужно.\n\n"
"Команды:\n"
"/reset — очистить память текущего чата;\n"
"/soul новый стиль — временно поменять душу текущего чата;\n"
"/reset_soul — вернуть стандартную душу;\n"
"/model — выбрать модель Gemini."
)
async def reset(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
chat = update.effective_chat
if message is None or chat is None:
return
self.storage.clear_messages(chat.id)
await message.reply_text("Память этого чата очищена.")
async def soul(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
chat = update.effective_chat
if message is None or chat is None:
return
soul_text = " ".join(context.args).strip()
settings = self.storage.get_chat_settings(chat.id, self.settings.default_model)
if not soul_text:
current = settings.custom_soul or "сейчас используется стандартная душа"
await message.reply_text(
"Напиши так: /soul отвечай как спокойный философ\n\n"
f"Текущая временная душа: {current}"
)
return
self.storage.set_custom_soul(chat.id, soul_text, self.settings.default_model)
await message.reply_text("Временная душа для этого чата обновлена.")
async def reset_soul(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
chat = update.effective_chat
if message is None or chat is None:
return
self.storage.reset_custom_soul(chat.id, self.settings.default_model)
await message.reply_text("Вернул стандартную душу для этого чата.")
async def model(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
chat = update.effective_chat
if message is None or chat is None:
return
requested_model = " ".join(context.args).strip()
if requested_model:
self.storage.set_model(chat.id, requested_model, self.settings.default_model)
await message.reply_text(f"Модель для этого чата: {requested_model}")
return
settings = self.storage.get_chat_settings(chat.id, self.settings.default_model)
models = await self._available_models()
keyboard = [
[InlineKeyboardButton(model_name, callback_data=f"model|{model_name}")]
for model_name in models
if len(model_name) <= 56
][:20]
if not keyboard:
keyboard = [
[InlineKeyboardButton(model_name, callback_data=f"model|{model_name}")]
for model_name in FALLBACK_MODELS
]
await message.reply_text(
f"Текущая модель: {settings.model}\nВыбери новую:",
reply_markup=InlineKeyboardMarkup(keyboard),
)
async def select_model(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query
if query is None or query.message is None or query.data is None:
return
await query.answer()
if not query.data.startswith("model|"):
return
model_name = query.data.removeprefix("model|")
self.storage.set_model(query.message.chat_id, model_name, self.settings.default_model)
await query.edit_message_text(f"Модель для этого чата: {model_name}")
async def text_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
chat = update.effective_chat
user = update.effective_user
if message is None or chat is None or user is None or message.text is None:
return
if not await self._message_addresses_bot(message, context):
return
cleaned_text = await self._clean_bot_mention(message.text, context)
if not cleaned_text:
await message.reply_text("Напиши вопрос после упоминания или ответь мне сообщением.")
return
chat_settings = self.storage.get_chat_settings(chat.id, self.settings.default_model)
history = self.storage.get_recent_messages(chat.id, self.settings.max_history_messages)
author = _display_name(user)
reply_context = _reply_context(message)
self.storage.append_message(
chat_id=chat.id,
telegram_message_id=message.message_id,
role="user",
user_id=user.id,
user_name=author,
text=cleaned_text,
)
await context.bot.send_chat_action(chat_id=chat.id, action="typing")
try:
answer = await self.gemini.generate_reply(
model=chat_settings.model,
default_system_prompt=self.settings.default_system_prompt,
custom_soul=chat_settings.custom_soul,
history=history,
current_author=author,
current_text=cleaned_text,
reply_context=reply_context,
)
except GeminiError:
logger.exception("Gemini request failed")
await message.reply_text(
"Gemini сейчас не ответил. Попробуй /model и выбери другую модель."
)
return
self.storage.append_message(
chat_id=chat.id,
telegram_message_id=None,
role="assistant",
user_id=None,
user_name="Botik",
text=answer,
)
await _reply_in_chunks(message, answer)
async def _available_models(self) -> list[str]:
models = await self.gemini.list_text_models()
return models or list(FALLBACK_MODELS)
async def _message_addresses_bot(
self,
message: Message,
context: ContextTypes.DEFAULT_TYPE,
) -> bool:
if message.chat.type == ChatType.PRIVATE:
return True
bot_id, username = await _get_bot_info(context)
if (
message.reply_to_message
and message.reply_to_message.from_user
and message.reply_to_message.from_user.id == bot_id
):
return True
return bool(username and f"@{username}" in message.text.lower())
async def _clean_bot_mention(
self,
text: str,
context: ContextTypes.DEFAULT_TYPE,
) -> str:
_, username = await _get_bot_info(context)
if not username:
return text.strip()
cleaned = re.sub(rf"@{re.escape(username)}\b", "", text, flags=re.IGNORECASE)
return cleaned.strip(" \n\t,:;—-")
def build_application(
settings: Settings,
storage: SQLiteStorage,
gemini: GeminiService,
) -> Application:
bot = TelegramBot(settings=settings, storage=storage, gemini=gemini)
application = (
ApplicationBuilder()
.token(settings.telegram_bot_token)
.connect_timeout(30)
.read_timeout(30)
.write_timeout(30)
.pool_timeout(30)
.post_init(_cache_bot_info)
.build()
)
application.add_handler(CommandHandler("start", bot.start))
application.add_handler(CommandHandler("help", bot.help))
application.add_handler(CommandHandler("settings", bot.help))
application.add_handler(CommandHandler("reset", bot.reset))
application.add_handler(CommandHandler("soul", bot.soul))
application.add_handler(CommandHandler("reset_soul", bot.reset_soul))
application.add_handler(CommandHandler("model", bot.model))
application.add_handler(CallbackQueryHandler(bot.select_model, pattern=r"^model\|"))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, bot.text_message))
return application
def _display_name(user: User) -> str:
username = f"@{user.username}" if user.username else f"user_id={user.id}"
return f"{user.full_name} ({username})"
async def _cache_bot_info(application: Application) -> None:
me = await application.bot.get_me()
application.bot_data[BOT_INFO_KEY] = {
"id": me.id,
"username": (me.username or "").lower(),
}
async def _get_bot_info(context: ContextTypes.DEFAULT_TYPE) -> tuple[int, str]:
bot_info = context.application.bot_data.get(BOT_INFO_KEY)
if bot_info:
return int(bot_info["id"]), str(bot_info["username"])
me = await context.bot.get_me()
username = (me.username or "").lower()
context.application.bot_data[BOT_INFO_KEY] = {"id": me.id, "username": username}
return me.id, username
def _reply_context(message: Message) -> str | None:
replied = message.reply_to_message
if replied is None:
return None
author = _display_name(replied.from_user) if replied.from_user else "неизвестный автор"
text = replied.text or replied.caption
if not text:
return f"{author}: [сообщение без текста]"
return f"{author}: {text}"
async def _reply_in_chunks(message: Message, text: str) -> None:
chunk_size = 3900
chunks = [text[index : index + chunk_size] for index in range(0, len(text), chunk_size)]
for chunk in chunks or ["Ответ пустой."]:
await message.reply_text(chunk)
|