yangtb24 commited on
Commit
cf4f01f
·
verified ·
1 Parent(s): d9eb73c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -76
app.py CHANGED
@@ -84,7 +84,6 @@ BAN_TRIGGER_PHRASES = [
84
  r"(?:AI|bot|机器人).*(?:真|真是|简直|太).*(?:垃圾|废物|没用|蠢|笨|傻|弱)",
85
  ]
86
  UNBAN_PHRASE = "close username"
87
- BACKUP_INTERVAL = 60 # 1分钟
88
 
89
  def make_telegram_request(method, data=None):
90
  url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
@@ -478,96 +477,73 @@ async def unbanUser(chatId, userId):
478
  await sendTelegramMessage(chatId, f"用户 {userId} 已被解禁。")
479
  print(f"用户 {userId} 在群组 {chatId} 中被解禁。")
480
 
481
- def backup_data():
482
- data = {
483
- 'chatHistories': chatHistories,
484
- 'GROUP_SETTINGS': GROUP_SETTINGS,
485
- 'USER_SETTINGS': USER_SETTINGS,
486
- 'GROUP_INFO': GROUP_INFO,
487
- 'USER_LAST_ACTIVE': USER_LAST_ACTIVE,
488
- 'BANNED_USERS': BANNED_USERS,
489
- }
490
  json_data = json.dumps(data)
491
-
492
- timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
493
- filename = f"tg_bot/backup_{timestamp}.json"
494
-
495
  curl_command = [
496
  'curl',
497
- '-k',
498
  '-u', f'{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}',
499
  '-X', 'PUT',
500
- '-d', json_data,
501
- f'{WEBDAV_URL}/{filename}'
 
502
  ]
503
-
504
  try:
505
- process = subprocess.Popen(curl_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
506
- stdout, stderr = process.communicate()
507
- if process.returncode == 0:
508
- print(f"备份成功,已上传到 {WEBDAV_URL}/{filename}")
509
- else:
510
- print(f"备份失败,curl 返回码: {process.returncode} 错误信息: {stderr.decode()}")
511
- except Exception as e:
512
- print(f"执行 curl 命令时发生错误: {e}")
513
 
514
- def load_data():
515
- global chatHistories, GROUP_SETTINGS, USER_SETTINGS, GROUP_INFO, USER_LAST_ACTIVE, BANNED_USERS
516
-
517
  curl_command = [
518
  'curl',
519
- '-k',
520
  '-u', f'{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}',
521
- f'{WEBDAV_URL}/tg_bot/'
 
522
  ]
523
-
524
  try:
525
- process = subprocess.Popen(curl_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
526
- stdout, stderr = process.communicate()
527
- if process.returncode == 0:
528
- output = stdout.decode()
529
- json_files = re.findall(r'backup_(\d+)\.json', output)
530
- if json_files:
531
- latest_file = sorted(json_files, reverse=True)[0]
532
- filename = f"tg_bot/backup_{latest_file}.json"
533
- download_command = [
534
- 'curl',
535
- '-k',
536
- '-u', f'{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}',
537
- f'{WEBDAV_URL}/{filename}'
538
- ]
539
- process = subprocess.Popen(download_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
540
- stdout, stderr = process.communicate()
541
- if process.returncode == 0:
542
- try:
543
- data = json.loads(stdout.decode())
544
- chatHistories = data.get('chatHistories', {})
545
- GROUP_SETTINGS = data.get('GROUP_SETTINGS', {})
546
- USER_SETTINGS = data.get('USER_SETTINGS', {})
547
- GROUP_INFO = data.get('GROUP_INFO', {})
548
- USER_LAST_ACTIVE = data.get('USER_LAST_ACTIVE', {})
549
- BANNED_USERS = data.get('BANNED_USERS', {})
550
- print(f"从 {WEBDAV_URL}/{filename} 加载数据成功")
551
- return
552
- except json.JSONDecodeError:
553
- print(f"加载数据失败: {filename} JSON 解析错误")
554
- else:
555
- print(f"下载文件失败,curl 返回码: {process.returncode} 错误信息: {stderr.decode()}")
556
- else:
557
- print("WebDAV 中未找到备份文件,初始化数据")
558
- else:
559
- print(f"列出文件失败,curl 返回码: {process.returncode} 错误信息: {stderr.decode()}")
560
- except Exception as e:
561
- print(f"执行 curl 命令时发生错误: {e}")
562
-
563
- def schedule_backup():
564
  while True:
565
- backup_data()
566
- time.sleep(BACKUP_INTERVAL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567
 
568
  if __name__ == '__main__':
569
- load_data()
570
  import threading
571
- backup_thread = threading.Thread(target=schedule_backup, daemon=True)
572
- backup_thread.start()
573
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
 
84
  r"(?:AI|bot|机器人).*(?:真|真是|简直|太).*(?:垃圾|废物|没用|蠢|笨|傻|弱)",
85
  ]
86
  UNBAN_PHRASE = "close username"
 
87
 
88
  def make_telegram_request(method, data=None):
89
  url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
 
477
  await sendTelegramMessage(chatId, f"用户 {userId} 已被解禁。")
478
  print(f"用户 {userId} 在群组 {chatId} 中被解禁。")
479
 
480
+ def webdav_upload(data, filename):
 
 
 
 
 
 
 
 
481
  json_data = json.dumps(data)
482
+ webdav_path = f"{WEBDAV_URL}/tg_bot/{filename}"
 
 
 
483
  curl_command = [
484
  'curl',
485
+ '-k', # 忽略证书验证
486
  '-u', f'{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}',
487
  '-X', 'PUT',
488
+ '-H', 'Content-Type: application/json',
489
+ '--data', json_data,
490
+ webdav_path
491
  ]
 
492
  try:
493
+ subprocess.run(curl_command, check=True, capture_output=True)
494
+ print(f'数据已上传到 WebDAV: {filename}')
495
+ except subprocess.CalledProcessError as e:
496
+ print(f'上传到 WebDAV 失败 ({filename}): {e.stderr.decode()}')
 
 
 
 
497
 
498
+ def webdav_download(filename):
499
+ webdav_path = f"{WEBDAV_URL}/tg_bot/{filename}"
 
500
  curl_command = [
501
  'curl',
502
+ '-k', # 忽略证书验证
503
  '-u', f'{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}',
504
+ '-s', # 静默模式
505
+ webdav_path
506
  ]
 
507
  try:
508
+ result = subprocess.run(curl_command, check=True, capture_output=True)
509
+ print(f'数据已从 WebDAV 下载: {filename}')
510
+ return json.loads(result.stdout.decode('utf-8'))
511
+ except subprocess.CalledProcessError as e:
512
+ print(f'从 WebDAV 下载失败 ({filename}): {e.stderr.decode()}')
513
+ return None
514
+ except json.JSONDecodeError as e:
515
+ print(f'解析 WebDAV 数据失败 ({filename}): {e}')
516
+ return None
517
+ def save_data_to_webdav():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  while True:
519
+ webdav_upload(chatHistories, 'chat_histories.json')
520
+ webdav_upload(GROUP_SETTINGS, 'group_settings.json')
521
+ webdav_upload(USER_SETTINGS, 'user_settings.json')
522
+ webdav_upload(GROUP_INFO, 'group_info.json')
523
+ webdav_upload(BANNED_USERS, 'banned_users.json')
524
+ time.sleep(60)
525
+
526
+ def load_data_from_webdav():
527
+ global chatHistories, GROUP_SETTINGS, USER_SETTINGS, GROUP_INFO, BANNED_USERS
528
+ chatHistories_data = webdav_download('chat_histories.json')
529
+ if chatHistories_data:
530
+ chatHistories = chatHistories_data
531
+ group_settings_data = webdav_download('group_settings.json')
532
+ if group_settings_data:
533
+ GROUP_SETTINGS = group_settings_data
534
+ user_settings_data = webdav_download('user_settings.json')
535
+ if user_settings_data:
536
+ USER_SETTINGS = user_settings_data
537
+ group_info_data = webdav_download('group_info.json')
538
+ if group_info_data:
539
+ GROUP_INFO = group_info_data
540
+ banned_users_data = webdav_download('banned_users.json')
541
+ if banned_users_data:
542
+ BANNED_USERS = banned_users_data
543
+
544
 
545
  if __name__ == '__main__':
546
+ load_data_from_webdav()
547
  import threading
548
+ threading.Thread(target=save_data_to_webdav, daemon=True).start()
 
549
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))