Update app.py
Browse files
app.py
CHANGED
@@ -20,6 +20,7 @@ TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
|
20 |
AI_API_ENDPOINT = os.environ.get("AI_API_ENDPOINT", "https://new.yangtb2024.me/v1/chat/completions")
|
21 |
AI_API_KEY = os.environ.get("AI_API_KEY")
|
22 |
AI_MODEL = os.environ.get("AI_MODEL", "gemini-2.0-flash-exp")
|
|
|
23 |
|
24 |
AI_API_HEADERS = {
|
25 |
"Content-Type": "application/json",
|
@@ -122,13 +123,25 @@ class EventEmitter:
|
|
122 |
|
123 |
async def set_bot_commands(bot: Bot):
|
124 |
try:
|
125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
logging.info("Telegram commands deleted successfully")
|
127 |
commands = [
|
128 |
(command[0], command[1])
|
129 |
for command in BOT_COMMANDS
|
130 |
]
|
131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
logging.info("Telegram commands set successfully")
|
133 |
except Exception as e:
|
134 |
logging.error(f"Error setting Telegram commands: {e}")
|
@@ -160,37 +173,38 @@ async def handle_telegram_update(update: Update, context):
|
|
160 |
|
161 |
if command == "clearall":
|
162 |
chat_histories.pop(chat_id, None)
|
163 |
-
await
|
164 |
return
|
165 |
if command == "help":
|
166 |
-
await
|
167 |
return
|
168 |
if command == "start":
|
169 |
-
await
|
170 |
chat_id=chat_id,
|
171 |
text="欢迎使用!请选择操作:",
|
172 |
reply_markup={
|
173 |
"inline_keyboard": [[{"text": "清空聊天记录", "callback_data": "clearall"}]],
|
174 |
},
|
|
|
175 |
)
|
176 |
return
|
177 |
if is_group_chat:
|
178 |
if command == "enableai":
|
179 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"aiEnabled": True})
|
180 |
-
await
|
181 |
return
|
182 |
if command == "disableai":
|
183 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"aiEnabled": False})
|
184 |
-
await
|
185 |
return
|
186 |
if user_message.startswith("/setprefix "):
|
187 |
prefix = user_message[len("/setprefix ") :].strip()
|
188 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"prefix": prefix})
|
189 |
-
await
|
190 |
return
|
191 |
if command == "getprefix":
|
192 |
prefix = GROUP_SETTINGS.get(chat_id, {}).get("prefix", "无")
|
193 |
-
await
|
194 |
return
|
195 |
else:
|
196 |
if user_message.startswith("/settemp "):
|
@@ -198,15 +212,15 @@ async def handle_telegram_update(update: Update, context):
|
|
198 |
temp = float(user_message[len("/settemp ") :].strip())
|
199 |
if 0 <= temp <= 2:
|
200 |
USER_SETTINGS.setdefault(from_user_id, {}).update({"temperature": temp})
|
201 |
-
await
|
202 |
else:
|
203 |
-
await
|
204 |
except ValueError:
|
205 |
-
await
|
206 |
return
|
207 |
if command == "gettemp":
|
208 |
temp = USER_SETTINGS.get(from_user_id, {}).get("temperature", DEFAULT_TEMP)
|
209 |
-
await
|
210 |
return
|
211 |
if user_message.startswith("/promat "):
|
212 |
try:
|
@@ -214,24 +228,24 @@ async def handle_telegram_update(update: Update, context):
|
|
214 |
if index in PROMPT_TEMPLATES:
|
215 |
global CURRENT_PROMPT_INDEX
|
216 |
CURRENT_PROMPT_INDEX = index
|
217 |
-
await
|
218 |
else:
|
219 |
-
await
|
220 |
-
chat_id=chat_id, text="提示词索引无效。请使用 /getpromat 查看可用的索引。"
|
221 |
)
|
222 |
except ValueError:
|
223 |
-
await
|
224 |
-
chat_id=chat_id, text="提示词索引无效。请使用 /getpromat 查看可用的索引。"
|
225 |
)
|
226 |
return
|
227 |
if command == "getpromat":
|
228 |
-
await
|
229 |
-
chat_id=chat_id, text=f"当前使用的提示词索引是: {CURRENT_PROMPT_INDEX}"
|
230 |
)
|
231 |
return
|
232 |
if command == "resetuser":
|
233 |
USER_SETTINGS.pop(from_user_id, None)
|
234 |
-
await
|
235 |
return
|
236 |
|
237 |
if is_group_chat:
|
@@ -286,7 +300,7 @@ async def process_ai_message(chat_id, user_message, from_user_id, context):
|
|
286 |
if not ai_response.ok:
|
287 |
error_text = await ai_response.text()
|
288 |
logging.error(f"AI API 响应失败: {ai_response.status}, {error_text}")
|
289 |
-
await
|
290 |
return
|
291 |
|
292 |
ai_data = await ai_response.json()
|
@@ -295,11 +309,11 @@ async def process_ai_message(chat_id, user_message, from_user_id, context):
|
|
295 |
history.append({"role": "assistant", "content": ai_reply})
|
296 |
chat_histories[chat_id] = history
|
297 |
|
298 |
-
await
|
299 |
|
300 |
except Exception as error:
|
301 |
logging.error(f"处理消息时发生错误: {error}")
|
302 |
-
await
|
303 |
|
304 |
|
305 |
async def handle_ai_response(ai_data, chat_id, history, event_emitter, context):
|
@@ -455,22 +469,39 @@ async def handle_callback_query(callback_query, context):
|
|
455 |
|
456 |
if data == "clearall":
|
457 |
chat_histories.pop(chat_id, None)
|
458 |
-
await
|
459 |
|
460 |
-
await
|
461 |
chat_id=chat_id,
|
462 |
text="请选择操作:",
|
463 |
reply_markup={
|
464 |
"inline_keyboard": [[{"text": "清空聊天记录", "callback_data": "clearall"}]],
|
465 |
},
|
|
|
466 |
)
|
467 |
|
468 |
|
469 |
async def send_event_message(chat_id, event, context):
|
470 |
if event["type"] == "status":
|
471 |
-
await
|
472 |
elif event["type"] == "citation":
|
473 |
-
await
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
474 |
|
475 |
def get_help_message():
|
476 |
return f"""
|
@@ -501,6 +532,7 @@ def get_help_message():
|
|
501 |
- 机器人具有攻击性,请谨慎使用。
|
502 |
"""
|
503 |
|
|
|
504 |
async def main():
|
505 |
logging.basicConfig(level=logging.INFO)
|
506 |
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
|
@@ -531,5 +563,6 @@ async def main():
|
|
531 |
# Start the bot
|
532 |
await application.run_polling()
|
533 |
|
|
|
534 |
if __name__ == "__main__":
|
535 |
-
asyncio.run(main())
|
|
|
20 |
AI_API_ENDPOINT = os.environ.get("AI_API_ENDPOINT", "https://new.yangtb2024.me/v1/chat/completions")
|
21 |
AI_API_KEY = os.environ.get("AI_API_KEY")
|
22 |
AI_MODEL = os.environ.get("AI_MODEL", "gemini-2.0-flash-exp")
|
23 |
+
CF_WORKER_URL = os.environ.get("CF_WORKER_URL")
|
24 |
|
25 |
AI_API_HEADERS = {
|
26 |
"Content-Type": "application/json",
|
|
|
123 |
|
124 |
async def set_bot_commands(bot: Bot):
|
125 |
try:
|
126 |
+
url = f"{CF_WORKER_URL}/bot{TELEGRAM_BOT_TOKEN}/deleteMyCommands"
|
127 |
+
async with aiohttp.ClientSession() as session:
|
128 |
+
async with session.post(url) as response:
|
129 |
+
if not response.ok:
|
130 |
+
error_text = await response.text()
|
131 |
+
logging.error(f"Telegram delete commands failed: {response.status}, {error_text}")
|
132 |
+
return
|
133 |
logging.info("Telegram commands deleted successfully")
|
134 |
commands = [
|
135 |
(command[0], command[1])
|
136 |
for command in BOT_COMMANDS
|
137 |
]
|
138 |
+
url = f"{CF_WORKER_URL}/bot{TELEGRAM_BOT_TOKEN}/setMyCommands"
|
139 |
+
async with aiohttp.ClientSession() as session:
|
140 |
+
async with session.post(url, json={"commands": commands}) as response:
|
141 |
+
if not response.ok:
|
142 |
+
error_text = await response.text()
|
143 |
+
logging.error(f"Telegram set commands failed: {response.status}, {error_text}")
|
144 |
+
return
|
145 |
logging.info("Telegram commands set successfully")
|
146 |
except Exception as e:
|
147 |
logging.error(f"Error setting Telegram commands: {e}")
|
|
|
173 |
|
174 |
if command == "clearall":
|
175 |
chat_histories.pop(chat_id, None)
|
176 |
+
await send_telegram_message(chat_id=chat_id, text="聊天记录已清空。", context=context)
|
177 |
return
|
178 |
if command == "help":
|
179 |
+
await send_telegram_message(chat_id=chat_id, text=get_help_message(), context=context)
|
180 |
return
|
181 |
if command == "start":
|
182 |
+
await send_telegram_message(
|
183 |
chat_id=chat_id,
|
184 |
text="欢迎使用!请选择操作:",
|
185 |
reply_markup={
|
186 |
"inline_keyboard": [[{"text": "清空聊天记录", "callback_data": "clearall"}]],
|
187 |
},
|
188 |
+
context=context
|
189 |
)
|
190 |
return
|
191 |
if is_group_chat:
|
192 |
if command == "enableai":
|
193 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"aiEnabled": True})
|
194 |
+
await send_telegram_message(chat_id=chat_id, text="已在群组中启用 AI 回复。", context=context)
|
195 |
return
|
196 |
if command == "disableai":
|
197 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"aiEnabled": False})
|
198 |
+
await send_telegram_message(chat_id=chat_id, text="已在群组中禁用 AI 回复。", context=context)
|
199 |
return
|
200 |
if user_message.startswith("/setprefix "):
|
201 |
prefix = user_message[len("/setprefix ") :].strip()
|
202 |
GROUP_SETTINGS.setdefault(chat_id, {}).update({"prefix": prefix})
|
203 |
+
await send_telegram_message(chat_id=chat_id, text=f"已设置群组触发前缀为: {prefix}", context=context)
|
204 |
return
|
205 |
if command == "getprefix":
|
206 |
prefix = GROUP_SETTINGS.get(chat_id, {}).get("prefix", "无")
|
207 |
+
await send_telegram_message(chat_id=chat_id, text=f"当前群组触发前缀为: {prefix}", context=context)
|
208 |
return
|
209 |
else:
|
210 |
if user_message.startswith("/settemp "):
|
|
|
212 |
temp = float(user_message[len("/settemp ") :].strip())
|
213 |
if 0 <= temp <= 2:
|
214 |
USER_SETTINGS.setdefault(from_user_id, {}).update({"temperature": temp})
|
215 |
+
await send_telegram_message(chat_id=chat_id, text=f"已设置AI回复温度为: {temp}", context=context)
|
216 |
else:
|
217 |
+
await send_telegram_message(chat_id=chat_id, text="温度设置无效,请输入0到2之间的数字。", context=context)
|
218 |
except ValueError:
|
219 |
+
await send_telegram_message(chat_id=chat_id, text="温度设置无效,请输入0到2之间的数字。", context=context)
|
220 |
return
|
221 |
if command == "gettemp":
|
222 |
temp = USER_SETTINGS.get(from_user_id, {}).get("temperature", DEFAULT_TEMP)
|
223 |
+
await send_telegram_message(chat_id=chat_id, text=f"当前AI回复温度为: {temp}", context=context)
|
224 |
return
|
225 |
if user_message.startswith("/promat "):
|
226 |
try:
|
|
|
228 |
if index in PROMPT_TEMPLATES:
|
229 |
global CURRENT_PROMPT_INDEX
|
230 |
CURRENT_PROMPT_INDEX = index
|
231 |
+
await send_telegram_message(chat_id=chat_id, text=f"已切换到提示词 {index}。", context=context)
|
232 |
else:
|
233 |
+
await send_telegram_message(
|
234 |
+
chat_id=chat_id, text="提示词索引无效。请使用 /getpromat 查看可用的索引。", context=context
|
235 |
)
|
236 |
except ValueError:
|
237 |
+
await send_telegram_message(
|
238 |
+
chat_id=chat_id, text="提示词索引无效。请使用 /getpromat 查看可用的索引。", context=context
|
239 |
)
|
240 |
return
|
241 |
if command == "getpromat":
|
242 |
+
await send_telegram_message(
|
243 |
+
chat_id=chat_id, text=f"当前使用的提示词索引是: {CURRENT_PROMPT_INDEX}", context=context
|
244 |
)
|
245 |
return
|
246 |
if command == "resetuser":
|
247 |
USER_SETTINGS.pop(from_user_id, None)
|
248 |
+
await send_telegram_message(chat_id=chat_id, text="已重置您的个人设置。", context=context)
|
249 |
return
|
250 |
|
251 |
if is_group_chat:
|
|
|
300 |
if not ai_response.ok:
|
301 |
error_text = await ai_response.text()
|
302 |
logging.error(f"AI API 响应失败: {ai_response.status}, {error_text}")
|
303 |
+
await send_telegram_message(chat_id=chat_id, text="AI API 响应失败,请稍后再试", context=context)
|
304 |
return
|
305 |
|
306 |
ai_data = await ai_response.json()
|
|
|
309 |
history.append({"role": "assistant", "content": ai_reply})
|
310 |
chat_histories[chat_id] = history
|
311 |
|
312 |
+
await send_telegram_message(chat_id=chat_id, text=ai_reply, context=context)
|
313 |
|
314 |
except Exception as error:
|
315 |
logging.error(f"处理消息时发生错误: {error}")
|
316 |
+
await send_telegram_message(chat_id=chat_id, text="处理消息时发生错误,请稍后再试", context=context)
|
317 |
|
318 |
|
319 |
async def handle_ai_response(ai_data, chat_id, history, event_emitter, context):
|
|
|
469 |
|
470 |
if data == "clearall":
|
471 |
chat_histories.pop(chat_id, None)
|
472 |
+
await send_telegram_message(chat_id=chat_id, text="聊天记录已清空。", context=context)
|
473 |
|
474 |
+
await send_telegram_message(
|
475 |
chat_id=chat_id,
|
476 |
text="请选择操作:",
|
477 |
reply_markup={
|
478 |
"inline_keyboard": [[{"text": "清空聊天记录", "callback_data": "clearall"}]],
|
479 |
},
|
480 |
+
context=context
|
481 |
)
|
482 |
|
483 |
|
484 |
async def send_event_message(chat_id, event, context):
|
485 |
if event["type"] == "status":
|
486 |
+
await send_telegram_message(chat_id=chat_id, text=f"状态更新: {event['data']['description']}", context=context)
|
487 |
elif event["type"] == "citation":
|
488 |
+
await send_telegram_message(chat_id=chat_id, text=f"引用信息: {event['data']['metadata'][0]['name']}", context=context)
|
489 |
+
|
490 |
+
|
491 |
+
async def send_telegram_message(chat_id, text, context, options=None):
|
492 |
+
url = f"{CF_WORKER_URL}/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
493 |
+
json_data = {"chat_id": chat_id, "text": text}
|
494 |
+
if options:
|
495 |
+
json_data.update(options)
|
496 |
+
try:
|
497 |
+
async with aiohttp.ClientSession() as session:
|
498 |
+
async with session.post(url, json=json_data) as response:
|
499 |
+
if not response.ok:
|
500 |
+
error_text = await response.text()
|
501 |
+
logging.error(f"发送 Telegram 消息失败: {response.status}, {error_text}")
|
502 |
+
except Exception as error:
|
503 |
+
logging.error(f"发送 Telegram 消息时发生错误: {error}")
|
504 |
+
|
505 |
|
506 |
def get_help_message():
|
507 |
return f"""
|
|
|
532 |
- 机器人具有攻击性,请谨慎使用。
|
533 |
"""
|
534 |
|
535 |
+
|
536 |
async def main():
|
537 |
logging.basicConfig(level=logging.INFO)
|
538 |
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
|
|
|
563 |
# Start the bot
|
564 |
await application.run_polling()
|
565 |
|
566 |
+
|
567 |
if __name__ == "__main__":
|
568 |
+
asyncio.run(main())
|