yangtb24 commited on
Commit
898e5e9
·
verified ·
1 Parent(s): 90a8bf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -47
app.py CHANGED
@@ -4,6 +4,7 @@ import requests
4
  from flask import Flask, request, jsonify
5
  from datetime import datetime
6
  import asyncio
 
7
 
8
  app = Flask(__name__)
9
 
@@ -114,7 +115,7 @@ class EventEmitter:
114
  'metadata': [{'name': title, 'source': url, 'html': False}],
115
  })
116
 
117
- def make_telegram_request(method, data=None):
118
  url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
119
  if PHP_PROXY_URL:
120
  method_name = url.split('/')[-1]
@@ -123,10 +124,11 @@ def make_telegram_request(method, data=None):
123
  if data:
124
  data = json.dumps(data)
125
  try:
126
- response = requests.post(url, headers=headers, data=data)
127
- response.raise_for_status()
128
- return response.json()
129
- except requests.exceptions.RequestException as e:
 
130
  print(f"Telegram request failed: {e}")
131
  return None
132
  except json.JSONDecodeError as e:
@@ -143,13 +145,13 @@ async def setBotCommands():
143
  set_url = f"{PHP_PROXY_URL}{set_method_name}"
144
 
145
  try:
146
- delete_response = make_telegram_request('deleteMyCommands')
147
  if delete_response:
148
  print('Telegram 命令删除成功')
149
  else:
150
  print('Telegram 命令删除失败')
151
 
152
- set_response = make_telegram_request('setMyCommands', {"commands": BOT_COMMANDS})
153
  if set_response:
154
  print('Telegram 命令设置成功')
155
  else:
@@ -292,22 +294,23 @@ async def processAiMessage(chatId, userMessage, fromUserId):
292
  eventEmitter = EventEmitter(event_handler)
293
 
294
  try:
295
- ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
 
296
  'model': AI_MODEL,
297
  'messages': messages,
298
  'max_tokens': MAX_TOKENS,
299
  'temperature': userTemp,
300
  'tools': TOOL_DEFINITIONS
301
- })
302
- ai_response.raise_for_status()
303
- ai_data = ai_response.json()
304
- ai_reply = await handleAiResponse(ai_data, chatId, history, eventEmitter)
305
 
306
- history.append({'role': 'assistant', 'content': ai_reply})
307
- chatHistories[chatId] = history
308
 
309
- await sendTelegramMessage(chatId, ai_reply)
310
- except requests.exceptions.RequestException as e:
311
  print(f'AI API 响应失败: {e}')
312
  await sendTelegramMessage(chatId, 'AI API 响应失败,请稍后再试')
313
  except Exception as error:
@@ -331,17 +334,18 @@ async def handleAiResponse(ai_data, chatId, history, eventEmitter):
331
  {'role': "assistant", 'content': None, 'tool_calls': toolCalls},
332
  *toolResults,
333
  ]
334
- ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
335
- 'model': AI_MODEL,
336
- 'messages': newMessages,
337
- 'max_tokens': MAX_TOKENS,
338
- 'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP)
339
- })
340
- ai_response.raise_for_status()
341
- ai_data = ai_response.json()
342
- if ai_data and ai_data.get('choices') and len(ai_data['choices']) > 0 and ai_data['choices'][0].get('message') and ai_data['choices'][0]['message'].get('content'):
343
- return ai_data['choices'][0]['message']['content']
344
- return 'AI 返回了无法识别的格式'
 
345
  return 'AI 返回了无法识别的格式'
346
 
347
  async def executeToolCall(toolCall, eventEmitter,chatId):
@@ -369,22 +373,23 @@ async def executeToolCall(toolCall, eventEmitter,chatId):
369
 
370
  async def processUrl(url):
371
  try:
372
- response = requests.post(api_url, headers=headers, json={
373
- "link": url,
374
- "ur": "summary of the page",
375
- "lp": True,
376
- "rt": False,
377
- "l": "en",
378
- })
379
- response.raise_for_status()
380
- result = response.json()
381
- if result.get('rules'):
382
- del result['rules']
383
- content = json.dumps(result)
384
- title = result.get('title', url)
385
- await eventEmitter.send_citation(title, url, content)
386
- return f"{content}\n"
387
- except requests.exceptions.RequestException as e:
 
388
  error_message = f"读取网页 {url} 时出错: {e}"
389
  await eventEmitter.update_status(error_message, False, "web_scrape", [url])
390
  await eventEmitter.send_citation(f"Error from {url}", url, str(e))
@@ -458,9 +463,10 @@ async def sendTelegramMessage(chatId, text, options={}):
458
  **options
459
  }
460
  try:
461
- response = requests.post(url, headers={'Content-Type': 'application/json'}, json=data)
462
- response.raise_for_status()
463
- except requests.exceptions.RequestException as e:
 
464
  print(f'发送 Telegram 消息失败: {e}')
465
 
466
  def getHelpMessage():
@@ -492,7 +498,6 @@ def getHelpMessage():
492
  - 机器人具有攻击性,请谨慎使用。
493
  """
494
 
495
-
496
  @app.route('/update_commands', methods=['GET'])
497
  async def update_commands():
498
  await setBotCommands()
 
4
  from flask import Flask, request, jsonify
5
  from datetime import datetime
6
  import asyncio
7
+ import aiohttp
8
 
9
  app = Flask(__name__)
10
 
 
115
  'metadata': [{'name': title, 'source': url, 'html': False}],
116
  })
117
 
118
+ async def make_telegram_request(method, data=None):
119
  url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
120
  if PHP_PROXY_URL:
121
  method_name = url.split('/')[-1]
 
124
  if data:
125
  data = json.dumps(data)
126
  try:
127
+ async with aiohttp.ClientSession() as session:
128
+ async with session.post(url, headers=headers, data=data) as response:
129
+ response.raise_for_status()
130
+ return await response.json()
131
+ except aiohttp.ClientError as e:
132
  print(f"Telegram request failed: {e}")
133
  return None
134
  except json.JSONDecodeError as e:
 
145
  set_url = f"{PHP_PROXY_URL}{set_method_name}"
146
 
147
  try:
148
+ delete_response = await make_telegram_request('deleteMyCommands')
149
  if delete_response:
150
  print('Telegram 命令删除成功')
151
  else:
152
  print('Telegram 命令删除失败')
153
 
154
+ set_response = await make_telegram_request('setMyCommands', {"commands": BOT_COMMANDS})
155
  if set_response:
156
  print('Telegram 命令设置成功')
157
  else:
 
294
  eventEmitter = EventEmitter(event_handler)
295
 
296
  try:
297
+ async with aiohttp.ClientSession() as session:
298
+ async with session.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
299
  'model': AI_MODEL,
300
  'messages': messages,
301
  'max_tokens': MAX_TOKENS,
302
  'temperature': userTemp,
303
  'tools': TOOL_DEFINITIONS
304
+ }) as ai_response:
305
+ ai_response.raise_for_status()
306
+ ai_data = await ai_response.json()
307
+ ai_reply = await handleAiResponse(ai_data, chatId, history, eventEmitter)
308
 
309
+ history.append({'role': 'assistant', 'content': ai_reply})
310
+ chatHistories[chatId] = history
311
 
312
+ await sendTelegramMessage(chatId, ai_reply)
313
+ except aiohttp.ClientError as e:
314
  print(f'AI API 响应失败: {e}')
315
  await sendTelegramMessage(chatId, 'AI API 响应失败,请稍后再试')
316
  except Exception as error:
 
334
  {'role': "assistant", 'content': None, 'tool_calls': toolCalls},
335
  *toolResults,
336
  ]
337
+ async with aiohttp.ClientSession() as session:
338
+ async with session.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
339
+ 'model': AI_MODEL,
340
+ 'messages': newMessages,
341
+ 'max_tokens': MAX_TOKENS,
342
+ 'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP)
343
+ }) as ai_response:
344
+ ai_response.raise_for_status()
345
+ ai_data = await ai_response.json()
346
+ if ai_data and ai_data.get('choices') and len(ai_data['choices']) > 0 and ai_data['choices'][0].get('message') and ai_data['choices'][0]['message'].get('content'):
347
+ return ai_data['choices'][0]['message']['content']
348
+ return 'AI 返回了��法识别的格式'
349
  return 'AI 返回了无法识别的格式'
350
 
351
  async def executeToolCall(toolCall, eventEmitter,chatId):
 
373
 
374
  async def processUrl(url):
375
  try:
376
+ async with aiohttp.ClientSession() as session:
377
+ async with session.post(api_url, headers=headers, json={
378
+ "link": url,
379
+ "ur": "summary of the page",
380
+ "lp": True,
381
+ "rt": False,
382
+ "l": "en",
383
+ }) as response:
384
+ response.raise_for_status()
385
+ result = await response.json()
386
+ if result.get('rules'):
387
+ del result['rules']
388
+ content = json.dumps(result)
389
+ title = result.get('title', url)
390
+ await eventEmitter.send_citation(title, url, content)
391
+ return f"{content}\n"
392
+ except aiohttp.ClientError as e:
393
  error_message = f"读取网页 {url} 时出错: {e}"
394
  await eventEmitter.update_status(error_message, False, "web_scrape", [url])
395
  await eventEmitter.send_citation(f"Error from {url}", url, str(e))
 
463
  **options
464
  }
465
  try:
466
+ async with aiohttp.ClientSession() as session:
467
+ async with session.post(url, headers={'Content-Type': 'application/json'}, json=data) as response:
468
+ response.raise_for_status()
469
+ except aiohttp.ClientError as e:
470
  print(f'发送 Telegram 消息失败: {e}')
471
 
472
  def getHelpMessage():
 
498
  - 机器人具有攻击性,请谨慎使用。
499
  """
500
 
 
501
  @app.route('/update_commands', methods=['GET'])
502
  async def update_commands():
503
  await setBotCommands()