fix commands

This commit is contained in:
jxxghp
2023-06-09 11:26:53 +08:00
parent 50d71621d7
commit 01428e9f8f
25 changed files with 228 additions and 202 deletions

View File

@ -8,12 +8,14 @@ from app.modules.telegram.telegram import Telegram
class TelegramModule(_ModuleBase):
telegram: Telegram = None
def init_module(self) -> None:
self.telegram = Telegram()
def stop(self):
self.telegram.stop()
def init_setting(self) -> Tuple[str, Union[str, bool]]:
return "MESSAGER", "telegram"
@ -51,13 +53,16 @@ class TelegramModule(_ModuleBase):
}
}
"""
# 校验token
token = args.get("token")
if not token or token != settings.API_TOKEN:
return None
try:
msg_json: dict = json.loads(body)
message: dict = json.loads(body)
except Exception as err:
logger.error(f"解析Telegram消息失败{err}")
return None
if msg_json:
message = msg_json.get("message", {})
if message:
text = message.get("text")
user_id = message.get("from", {}).get("id")
# 获取用户名
@ -117,3 +122,10 @@ class TelegramModule(_ModuleBase):
:return: 成功或失败
"""
return self.telegram.send_torrents_msg(title=title, torrents=items, userid=userid)
def register_commands(self, commands: dict):
"""
注册命令,实现这个函数接收系统可用的命令菜单
:param commands: 命令字典
"""
self.telegram.register_commands(commands)

View File

@ -1,13 +1,13 @@
from threading import Event, Thread
import threading
from threading import Event
from typing import Optional, List
from urllib.parse import urlencode
from app.core import settings, MediaInfo, TorrentInfo, Context
import telebot
from app.core import settings, MediaInfo, Context
from app.log import logger
from app.utils.http import RequestUtils
from app.utils.singleton import Singleton
import telebot
from app.utils.string import StringUtils
@ -26,16 +26,25 @@ class Telegram(metaclass=Singleton):
self._telegram_chat_id = settings.TELEGRAM_CHAT_ID
# 初始化机器人
if self._telegram_token and self._telegram_chat_id:
# bot
_bot = telebot.TeleBot(self._telegram_token, parse_mode="markdown")
# 记录句柄
self._bot = _bot
@_bot.message_handler(func=lambda message: True)
def echo_all(message):
RequestUtils(timeout=10).post_res(self._ds_url, json=message.json)
# 启动轮询
def run_polling():
"""
定义线程函数来运行 infinity_polling
"""
_bot.infinity_polling()
# 启动线程来运行 infinity_polling
self._polling_thread = threading.Thread(target=run_polling)
self._polling_thread.start()
def send_msg(self, title: str, text: str = "", image: str = "", userid: str = "") -> Optional[bool]:
"""
发送Telegram消息
@ -156,8 +165,25 @@ class Telegram(metaclass=Singleton):
return True if ret else False
def register_commands(self, commands: dict):
"""
注册菜单命令
"""
if not self._bot:
return
# 设置bot命令
if commands:
self._bot.delete_my_commands()
self._bot.set_my_commands(
commands=[
telebot.types.BotCommand(cmd[1:], str(desc.get("description"))) for cmd, desc in
commands.items()
]
)
def stop(self):
"""
停止Telegram消息接收服务
"""
self._bot.stop_polling()
self._polling_thread.join()