Update app.py
Browse files
app.py
CHANGED
@@ -51,6 +51,10 @@ BOT_COMMANDS = [
|
|
51 |
{"command": "test", "description": "获取当前使用的提示词索引"},
|
52 |
]
|
53 |
DEFAULT_TEMP = 1.5
|
|
|
|
|
|
|
|
|
54 |
|
55 |
def make_telegram_request(method, data=None):
|
56 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
@@ -106,6 +110,34 @@ async def handleTelegramUpdate(update):
|
|
106 |
isGroupChat = update['message']['chat']['type'] in ['group', 'supergroup']
|
107 |
fromUserId = update['message']['from']['id']
|
108 |
message_id = update['message'].get('message_id')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
if not userMessage:
|
111 |
return
|
@@ -172,9 +204,9 @@ async def handleTelegramUpdate(update):
|
|
172 |
|
173 |
messageContent = userMessage[len(prefix):].strip() if prefix else userMessage
|
174 |
if messageContent:
|
175 |
-
await processAiMessage(chatId, messageContent, fromUserId, message_id)
|
176 |
else:
|
177 |
-
await processAiMessage(chatId, userMessage, fromUserId, message_id)
|
178 |
|
179 |
def parseCommand(userMessage):
|
180 |
command = userMessage.split(' ')[0]
|
@@ -220,21 +252,45 @@ async def handlePrivateCommand(chatId, userMessage, fromUserId, isGroupChat):
|
|
220 |
await sendTelegramMessage(chatId, '已重置您的个人设置。')
|
221 |
return
|
222 |
|
223 |
-
async def processAiMessage(chatId, userMessage, fromUserId, message_id):
|
224 |
history = chatHistories.get(chatId, [])
|
225 |
userTemp = USER_SETTINGS.get(fromUserId, {}).get('temperature', DEFAULT_TEMP)
|
226 |
userPromptIndex = USER_SETTINGS.get(fromUserId, {}).get('prompt_index', CURRENT_PROMPT_INDEX)
|
227 |
currentPrompt = PROMPT_TEMPLATES.get(userPromptIndex, "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
228 |
history.append({'role': 'user', 'content': userMessage})
|
229 |
|
230 |
if len(history) > MAX_HISTORY_LENGTH:
|
231 |
history = history[-MAX_HISTORY_LENGTH:]
|
232 |
|
233 |
messages = [
|
234 |
-
{'role': 'system', 'content':
|
235 |
*history
|
236 |
]
|
237 |
-
|
238 |
thinking_message = await sendTelegramMessage(chatId, "正在思考,请等待...", options={'reply_to_message_id': message_id})
|
239 |
thinking_message_id = thinking_message.get('result', {}).get('message_id')
|
240 |
|
@@ -274,7 +330,7 @@ async def handleCallbackQuery(callbackQuery):
|
|
274 |
if data == "clearall":
|
275 |
chatHistories.pop(chatId, None)
|
276 |
await sendTelegramMessage(chatId, "聊天记录已清空。")
|
277 |
-
|
278 |
await sendTelegramMessage(chatId, '请选择操作:', {
|
279 |
'reply_markup': {
|
280 |
'inline_keyboard': [[{'text': "清空���天记录", 'callback_data': "clearall"}]],
|
@@ -286,13 +342,13 @@ async def sendTelegramMessage(chatId, text, options={}):
|
|
286 |
if PHP_PROXY_URL:
|
287 |
method_name = url.split('/')[-1]
|
288 |
url = f"{PHP_PROXY_URL}{method_name}"
|
289 |
-
|
290 |
data = {
|
291 |
'chat_id': chatId,
|
292 |
'text': text,
|
293 |
**options
|
294 |
}
|
295 |
-
|
296 |
try:
|
297 |
response = requests.post(url, headers={'Content-Type': 'application/json'}, json=data)
|
298 |
response.raise_for_status()
|
@@ -330,18 +386,18 @@ def getHelpMessage():
|
|
330 |
/disableai - 在群组中禁用AI回复。
|
331 |
/setprefix <prefix> - 设置群组中触发AI回复的前缀,例如:/setprefix @bot。
|
332 |
/getprefix - 获取当前群组的触发前缀。
|
333 |
-
|
334 |
私聊指令 (在群组中也可以使用):
|
335 |
/settemp <温度值> - 设置AI回复的温度 (0-2),例如:/settemp 1.0。
|
336 |
/gettemp - 获取当前AI回复的温度。
|
337 |
/resetuser - 重置你的个人设置。
|
338 |
/promat <index> - 切换提示词,例如: /promat 0, 1, 2。
|
339 |
/getpromat - 获取当前使用的提示词索引。
|
340 |
-
|
341 |
直接发送文本消息与AI对话 (私聊)。
|
342 |
|
343 |
群组中,需要使用前缀触发AI回复,如果设置了前缀的话。
|
344 |
-
|
345 |
注意:
|
346 |
- 机器人会记住最近的 {MAX_HISTORY_LENGTH} 条对话。
|
347 |
- 机器人具有攻击性,请谨慎使用。
|
@@ -368,5 +424,21 @@ async def handle_webhook():
|
|
368 |
def health_check():
|
369 |
return 'OK'
|
370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
371 |
if __name__ == '__main__':
|
372 |
-
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|
|
|
51 |
{"command": "test", "description": "获取当前使用的提示词索引"},
|
52 |
]
|
53 |
DEFAULT_TEMP = 1.5
|
54 |
+
# 新增的用户和群组信息存储
|
55 |
+
USER_LAST_ACTIVE = {}
|
56 |
+
GROUP_ACTIVE_USERS = {}
|
57 |
+
GROUP_INFO = {}
|
58 |
|
59 |
def make_telegram_request(method, data=None):
|
60 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
|
|
110 |
isGroupChat = update['message']['chat']['type'] in ['group', 'supergroup']
|
111 |
fromUserId = update['message']['from']['id']
|
112 |
message_id = update['message'].get('message_id')
|
113 |
+
fromUserFirstName = update['message']['from'].get('first_name', '用户')
|
114 |
+
fromUserLastName = update['message']['from'].get('last_name', '')
|
115 |
+
fromUserName = update['message']['from'].get('username', '')
|
116 |
+
|
117 |
+
# 更新用户最后活跃时间
|
118 |
+
USER_LAST_ACTIVE[fromUserId] = datetime.now()
|
119 |
+
|
120 |
+
if isGroupChat:
|
121 |
+
# 更新群组活跃用户
|
122 |
+
GROUP_ACTIVE_USERS.setdefault(chatId, set()).add(fromUserId)
|
123 |
+
if chatId not in GROUP_INFO:
|
124 |
+
chat_info = await getChatInfo(chatId)
|
125 |
+
if chat_info:
|
126 |
+
GROUP_INFO[chatId] = {
|
127 |
+
'name': chat_info.get('title', '未知群组'),
|
128 |
+
'description': chat_info.get('description', '无描述'),
|
129 |
+
'last_active': datetime.now()
|
130 |
+
}
|
131 |
+
else:
|
132 |
+
GROUP_INFO[chatId] = {
|
133 |
+
'name': '未知群组',
|
134 |
+
'description': '无描述',
|
135 |
+
'last_active': datetime.now()
|
136 |
+
}
|
137 |
+
else:
|
138 |
+
GROUP_INFO[chatId]['last_active'] = datetime.now()
|
139 |
+
|
140 |
+
|
141 |
|
142 |
if not userMessage:
|
143 |
return
|
|
|
204 |
|
205 |
messageContent = userMessage[len(prefix):].strip() if prefix else userMessage
|
206 |
if messageContent:
|
207 |
+
await processAiMessage(chatId, messageContent, fromUserId, message_id, fromUserFirstName, fromUserLastName, fromUserName)
|
208 |
else:
|
209 |
+
await processAiMessage(chatId, userMessage, fromUserId, message_id, fromUserFirstName, fromUserLastName, fromUserName)
|
210 |
|
211 |
def parseCommand(userMessage):
|
212 |
command = userMessage.split(' ')[0]
|
|
|
252 |
await sendTelegramMessage(chatId, '已重置您的个人设置。')
|
253 |
return
|
254 |
|
255 |
+
async def processAiMessage(chatId, userMessage, fromUserId, message_id, fromUserFirstName, fromUserLastName, fromUserName):
|
256 |
history = chatHistories.get(chatId, [])
|
257 |
userTemp = USER_SETTINGS.get(fromUserId, {}).get('temperature', DEFAULT_TEMP)
|
258 |
userPromptIndex = USER_SETTINGS.get(fromUserId, {}).get('prompt_index', CURRENT_PROMPT_INDEX)
|
259 |
currentPrompt = PROMPT_TEMPLATES.get(userPromptIndex, "")
|
260 |
+
|
261 |
+
# 获取用户和群组的上下文信息
|
262 |
+
user_last_active = USER_LAST_ACTIVE.get(fromUserId, None)
|
263 |
+
group_info = GROUP_INFO.get(chatId, None)
|
264 |
+
group_active_users = GROUP_ACTIVE_USERS.get(chatId, None)
|
265 |
+
|
266 |
+
# 构建更丰富的系统提示
|
267 |
+
system_prompt = f"""
|
268 |
+
{currentPrompt}
|
269 |
+
当前时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
270 |
+
|
271 |
+
用户信息:
|
272 |
+
- 用户ID: {fromUserId}
|
273 |
+
- 用户名: {fromUserFirstName} {fromUserLastName}
|
274 |
+
- 用户账号: {fromUserName}
|
275 |
+
- 最后活跃时间: {user_last_active.strftime("%Y-%m-%d %H:%M:%S") if user_last_active else "未知"}
|
276 |
+
|
277 |
+
群组信息:
|
278 |
+
- 群组ID: {chatId}
|
279 |
+
- 群组名称: {group_info['name'] if group_info else "未知"}
|
280 |
+
- 群组描述: {group_info['description'] if group_info else "无"}
|
281 |
+
- 群组最后活跃时间: {group_info['last_active'].strftime("%Y-%m-%d %H:%M:%S") if group_info and group_info.get('last_active') else "未知"}
|
282 |
+
- 群组活跃用户数: {len(group_active_users) if group_active_users else "未知"}
|
283 |
+
"""
|
284 |
history.append({'role': 'user', 'content': userMessage})
|
285 |
|
286 |
if len(history) > MAX_HISTORY_LENGTH:
|
287 |
history = history[-MAX_HISTORY_LENGTH:]
|
288 |
|
289 |
messages = [
|
290 |
+
{'role': 'system', 'content': system_prompt},
|
291 |
*history
|
292 |
]
|
293 |
+
|
294 |
thinking_message = await sendTelegramMessage(chatId, "正在思考,请等待...", options={'reply_to_message_id': message_id})
|
295 |
thinking_message_id = thinking_message.get('result', {}).get('message_id')
|
296 |
|
|
|
330 |
if data == "clearall":
|
331 |
chatHistories.pop(chatId, None)
|
332 |
await sendTelegramMessage(chatId, "聊天记录已清空。")
|
333 |
+
|
334 |
await sendTelegramMessage(chatId, '请选择操作:', {
|
335 |
'reply_markup': {
|
336 |
'inline_keyboard': [[{'text': "清空���天记录", 'callback_data': "clearall"}]],
|
|
|
342 |
if PHP_PROXY_URL:
|
343 |
method_name = url.split('/')[-1]
|
344 |
url = f"{PHP_PROXY_URL}{method_name}"
|
345 |
+
|
346 |
data = {
|
347 |
'chat_id': chatId,
|
348 |
'text': text,
|
349 |
**options
|
350 |
}
|
351 |
+
|
352 |
try:
|
353 |
response = requests.post(url, headers={'Content-Type': 'application/json'}, json=data)
|
354 |
response.raise_for_status()
|
|
|
386 |
/disableai - 在群组中禁用AI回复。
|
387 |
/setprefix <prefix> - 设置群组中触发AI回复的前缀,例如:/setprefix @bot。
|
388 |
/getprefix - 获取当前群组的触发前缀。
|
389 |
+
|
390 |
私聊指令 (在群组中也可以使用):
|
391 |
/settemp <温度值> - 设置AI回复的温度 (0-2),例如:/settemp 1.0。
|
392 |
/gettemp - 获取当前AI回复的温度。
|
393 |
/resetuser - 重置你的个人设置。
|
394 |
/promat <index> - 切换提示词,例如: /promat 0, 1, 2。
|
395 |
/getpromat - 获取当前使用的提示词索引。
|
396 |
+
|
397 |
直接发送文本消息与AI对话 (私聊)。
|
398 |
|
399 |
群组中,需要使用前缀触发AI回复,如果设置了前缀的话。
|
400 |
+
|
401 |
注意:
|
402 |
- 机器人会记住最近的 {MAX_HISTORY_LENGTH} 条对话。
|
403 |
- 机器人具有攻击性,请谨慎使用。
|
|
|
424 |
def health_check():
|
425 |
return 'OK'
|
426 |
|
427 |
+
async def getChatInfo(chatId):
|
428 |
+
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/getChat"
|
429 |
+
if PHP_PROXY_URL:
|
430 |
+
method_name = url.split('/')[-1]
|
431 |
+
url = f"{PHP_PROXY_URL}{method_name}"
|
432 |
+
data = {
|
433 |
+
'chat_id': chatId,
|
434 |
+
}
|
435 |
+
try:
|
436 |
+
response = requests.post(url, headers={'Content-Type': 'application/json'}, json=data)
|
437 |
+
response.raise_for_status()
|
438 |
+
return response.json().get('result', {})
|
439 |
+
except requests.exceptions.RequestException as e:
|
440 |
+
print(f'获取群组信息失败: {e}')
|
441 |
+
return None
|
442 |
+
|
443 |
if __name__ == '__main__':
|
444 |
+
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|