From f42d61a03fd12501d45d61eab4da8c8426be01aa Mon Sep 17 00:00:00 2001 From: wood Date: Tue, 3 Sep 2024 17:46:32 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=B3=A8=E5=86=8C=E5=91=BD?= =?UTF-8?q?=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bot_commands.py | 27 ++++++++++++++++ src/guard.py | 78 ++++++++++++++++++++++++--------------------- src/main.py | 16 ++++++++++ 3 files changed, 85 insertions(+), 36 deletions(-) create mode 100644 src/bot_commands.py diff --git a/src/bot_commands.py b/src/bot_commands.py new file mode 100644 index 0000000..7972543 --- /dev/null +++ b/src/bot_commands.py @@ -0,0 +1,27 @@ +from telethon.tl.types import InputPeerUser +from telethon.tl.functions.bots import SetBotCommandsRequest +from telethon.tl.types import BotCommand +import logging + +async def register_commands(client, admin_id): + commands = [ + # TeleGuard 命令 + BotCommand('add', '添加新的关键词'), + BotCommand('delete', '删除现有的关键词'), + BotCommand('list', '列出所有当前的关键词'), + + # 这里可以添加其他功能的命令 + # 例如:BotCommand('price', '获取当前价格'), + ] + + try: + await client(SetBotCommandsRequest( + commands=commands, + scope=InputPeerUser(admin_id, 0), + lang_code='' + )) + logging.info("Bot commands registered successfully.") + except Exception as e: + logging.error(f"Failed to register bot commands: {str(e)}") + +# 如果有其他功能需要注册命令,可以在这里添加新的函数 diff --git a/src/guard.py b/src/guard.py index 7395bdd..671282d 100644 --- a/src/guard.py +++ b/src/guard.py @@ -1,13 +1,19 @@ import os import json import logging +import asyncio import time from telethon import TelegramClient, events +# 环境变量 BOT_TOKEN = os.environ.get('BOT_TOKEN') -ADMIN_ID = int(os.environ.get('ADMIN_ID')) # 从环境变量获取 ADMIN_ID 并转换为整数 +ADMIN_ID = int(os.environ.get('ADMIN_ID')) KEYWORDS_FILE = '/app/data/keywords.json' +# 设置日志 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger('TeleGuard') + def load_keywords(): if os.path.exists(KEYWORDS_FILE): with open(KEYWORDS_FILE, 'r') as f: @@ -20,47 +26,47 @@ def save_keywords(keywords): KEYWORDS = load_keywords() -client = TelegramClient('bot', api_id=6, api_hash='eb06d4abfb49dc3eeb1aeb98ae0f581e') -client.start(bot_token=BOT_TOKEN) +async def start_bot(): + client = TelegramClient('bot', api_id=6, api_hash='eb06d4abfb49dc3eeb1aeb98ae0f581e') + await client.start(bot_token=BOT_TOKEN) + + @client.on(events.NewMessage(pattern='')) + async def handler(event): + global KEYWORDS + if event.is_private and event.sender_id == ADMIN_ID: + command = event.message.text.split() + if command[0].lower() == '/add' and len(command) > 1: + new_keyword = command[1].lower() + if new_keyword not in KEYWORDS: + KEYWORDS.append(new_keyword) + save_keywords(KEYWORDS) + await event.respond(f"关键词 '{new_keyword}' 已添加到列表中。") + else: + await event.respond(f"关键词 '{new_keyword}' 已经在列表中。") + elif command[0].lower() == '/delete' and len(command) > 1: + keyword_to_delete = command[1].lower() + if keyword_to_delete in KEYWORDS: + KEYWORDS.remove(keyword_to_delete) + save_keywords(KEYWORDS) + await event.respond(f"关键词 '{keyword_to_delete}' 已从列表中删除。") + else: + await event.respond(f"关键词 '{keyword_to_delete}' 不在列表中。") + elif command[0].lower() == '/list': + await event.respond(f"当前关键词列表:{', '.join(KEYWORDS)}") + return -@client.on(events.NewMessage(pattern='')) -async def handler(event): - global KEYWORDS - if event.is_private and event.sender_id == ADMIN_ID: - command = event.message.text.split() - if command[0].lower() == '/add' and len(command) > 1: - new_keyword = command[1].lower() - if new_keyword not in KEYWORDS: - KEYWORDS.append(new_keyword) - save_keywords(KEYWORDS) - await event.respond(f"关键词 '{new_keyword}' 已添加到列表中。") - else: - await event.respond(f"关键词 '{new_keyword}' 已经在列表中。") - elif command[0].lower() == '/delete' and len(command) > 1: - keyword_to_delete = command[1].lower() - if keyword_to_delete in KEYWORDS: - KEYWORDS.remove(keyword_to_delete) - save_keywords(KEYWORDS) - await event.respond(f"关键词 '{keyword_to_delete}' 已从列表中删除。") - else: - await event.respond(f"关键词 '{keyword_to_delete}' 不在列表中。") - elif command[0].lower() == '/list': - await event.respond(f"当前关键词列表:{', '.join(KEYWORDS)}") - return + if not event.is_private and any(keyword in event.message.text.lower() for keyword in KEYWORDS): + if event.sender_id != ADMIN_ID: + await event.delete() + await event.respond("已撤回该消息。注:已发送的推广链接不要多次发送,置顶已有项目的推广链接也会自动撤回。") - if not event.is_private and any(keyword in event.message.text.lower() for keyword in KEYWORDS): - if event.sender_id != ADMIN_ID: - await event.delete() - await event.respond("已撤回该消息。注:已发送的推广链接不要多次发送,置顶已有项目的推广链接也会自动撤回。") + logger.info("TeleGuard is running...") + await client.run_until_disconnected() def run(): - logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') - logger = logging.getLogger('TeleGuard') - while True: try: - logger.info("TeleGuard is starting...") - client.run_until_disconnected() + asyncio.get_event_loop().run_until_complete(start_bot()) except Exception as e: logger.error(f"An error occurred in TeleGuard: {str(e)}") logger.info("Attempting to restart TeleGuard in 60 seconds...") diff --git a/src/main.py b/src/main.py index 62c34c8..3920ce9 100644 --- a/src/main.py +++ b/src/main.py @@ -1,7 +1,19 @@ +import os import multiprocessing import guard import binance import logging +from bot_commands import register_commands +from telethon import TelegramClient + +BOT_TOKEN = os.environ.get('BOT_TOKEN') +ADMIN_ID = int(os.environ.get('ADMIN_ID')) + +async def setup_bot(): + client = TelegramClient('bot', api_id=6, api_hash='eb06d4abfb49dc3eeb1aeb98ae0f581e') + await client.start(bot_token=BOT_TOKEN) + await register_commands(client, ADMIN_ID) + await client.disconnect() def run_guard(): while True: @@ -22,6 +34,10 @@ def run_binance(): if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') + # 注册机器人命令 + import asyncio + asyncio.get_event_loop().run_until_complete(setup_bot()) + # 创建两个进程分别运行 guard 和 binance 服务 guard_process = multiprocessing.Process(target=run_guard) binance_process = multiprocessing.Process(target=run_binance)