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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -63
app.py CHANGED
@@ -18,6 +18,7 @@ PHP_PROXY_URL = os.environ.get('PHP_PROXY_URL')
18
  WEBDAV_URL = os.environ.get('WEBDAV_URL')
19
  WEBDAV_USERNAME = os.environ.get('WEBDAV_USERNAME')
20
  WEBDAV_PASSWORD = os.environ.get('WEBDAV_PASSWORD')
 
21
 
22
  if not all([TELEGRAM_BOT_TOKEN, AI_API_ENDPOINT, AI_API_KEY, AI_MODEL, WEBDAV_URL, WEBDAV_USERNAME, WEBDAV_PASSWORD]):
23
  raise ValueError("请设置所有必要的环境变量")
@@ -477,73 +478,100 @@ async def unbanUser(chatId, userId):
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)))
 
18
  WEBDAV_URL = os.environ.get('WEBDAV_URL')
19
  WEBDAV_USERNAME = os.environ.get('WEBDAV_USERNAME')
20
  WEBDAV_PASSWORD = os.environ.get('WEBDAV_PASSWORD')
21
+ WEBDAV_BASE_DIR = os.environ.get('WEBDAV_BASE_DIR', 'tg_bot')
22
 
23
  if not all([TELEGRAM_BOT_TOKEN, AI_API_ENDPOINT, AI_API_KEY, AI_MODEL, WEBDAV_URL, WEBDAV_USERNAME, WEBDAV_PASSWORD]):
24
  raise ValueError("请设置所有必要的环境变量")
 
478
  await sendTelegramMessage(chatId, f"用户 {userId} 已被解禁。")
479
  print(f"用户 {userId} 在群组 {chatId} 中被解禁。")
480
 
481
+ def backup_data():
482
+ global chatHistories, GROUP_SETTINGS, USER_SETTINGS, USER_LAST_ACTIVE, GROUP_ACTIVE_USERS, GROUP_INFO, BANNED_USERS
483
+ data = {
484
+ 'chatHistories': chatHistories,
485
+ 'GROUP_SETTINGS': GROUP_SETTINGS,
486
+ 'USER_SETTINGS': USER_SETTINGS,
487
+ 'USER_LAST_ACTIVE': USER_LAST_ACTIVE,
488
+ 'GROUP_ACTIVE_USERS': GROUP_ACTIVE_USERS,
489
+ 'GROUP_INFO': GROUP_INFO,
490
+ 'BANNED_USERS': BANNED_USERS,
491
+ }
492
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
493
+ filename = f"backup_{timestamp}.json"
494
+ filepath = os.path.join(WEBDAV_BASE_DIR, filename)
495
+
496
  try:
497
+ json_data = json.dumps(data)
498
+ curl_command = [
499
+ "curl",
500
+ "-v",
501
+ "-X", "PUT",
502
+ "-u", f"{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}",
503
+ "--data-binary", f"@{'-'}",
504
+ f"{WEBDAV_URL}/{filepath}"
505
+ ]
506
+ process = subprocess.Popen(curl_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
507
+ stdout, stderr = process.communicate(input=json_data.encode('utf-8'))
508
+ if process.returncode != 0:
509
+ print(f"备份失败: {stderr.decode('utf-8')}")
510
+ else:
511
+ print(f"备份成功: {filename} 已上传")
512
+ except Exception as e:
513
+ print(f"备份过程中发生错误: {e}")
514
+
515
+ def restore_data():
516
+ global chatHistories, GROUP_SETTINGS, USER_SETTINGS, USER_LAST_ACTIVE, GROUP_ACTIVE_USERS, GROUP_INFO, BANNED_USERS
517
+
518
  try:
519
+ curl_command = [
520
+ "curl",
521
+ "-v",
522
+ "-u", f"{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}",
523
+ f"{WEBDAV_URL}/{WEBDAV_BASE_DIR}/"
524
+ ]
525
+ process = subprocess.Popen(curl_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
526
+ stdout, stderr = process.communicate()
527
+ if process.returncode != 0:
528
+ print(f"获取文件列表失败: {stderr.decode('utf-8')}")
529
+ return
530
+
531
+ files = re.findall(r'href="([^"]*\.json)"', stdout.decode('utf-8'))
532
+ if not files:
533
+ print("没有找到备份文件")
534
+ return
535
+ files.sort(reverse=True)
536
+ latest_file = files[0]
537
+
538
+ curl_command = [
539
+ "curl",
540
+ "-v",
541
+ "-u", f"{WEBDAV_USERNAME}:{WEBDAV_PASSWORD}",
542
+ f"{WEBDAV_URL}/{WEBDAV_BASE_DIR}/{latest_file}"
543
+ ]
544
+ process = subprocess.Popen(curl_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
545
+ stdout, stderr = process.communicate()
546
+ if process.returncode != 0:
547
+ print(f"下载最新备份失败: {stderr.decode('utf-8')}")
548
+ return
 
 
 
 
 
549
 
550
+ try:
551
+ data = json.loads(stdout.decode('utf-8'))
552
+ chatHistories = data.get('chatHistories', {})
553
+ GROUP_SETTINGS = data.get('GROUP_SETTINGS', {})
554
+ USER_SETTINGS = data.get('USER_SETTINGS', {})
555
+ USER_LAST_ACTIVE = data.get('USER_LAST_ACTIVE', {})
556
+ GROUP_ACTIVE_USERS = data.get('GROUP_ACTIVE_USERS', {})
557
+ GROUP_INFO = data.get('GROUP_INFO', {})
558
+ BANNED_USERS = data.get('BANNED_USERS', {})
559
+ print(f"数据已从 {latest_file} 恢复")
560
+ except json.JSONDecodeError as e:
561
+ print(f"JSON解析失败: {e}")
562
+ except Exception as e:
563
+ print(f"恢复数据时发生错误: {e}")
564
 
565
  if __name__ == '__main__':
566
+ restore_data()
567
+
568
+ def schedule_backup():
569
+ while True:
570
+ backup_data()
571
+ time.sleep(60)
572
+
573
  import threading
574
+ backup_thread = threading.Thread(target=schedule_backup, daemon=True)
575
+ backup_thread.start()
576
+
577
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))