PaiGram/main.py

81 lines
2.6 KiB
Python
Raw Normal View History

import asyncio
from warnings import filterwarnings
from telegram.ext import Application
from telegram.warnings import PTBUserWarning
2022-04-14 07:18:45 +00:00
2022-06-09 07:12:06 +00:00
from config import config
from handler import register_handlers
from logger import Log
2022-04-14 07:18:45 +00:00
from service import StartService
from utils.aiobrowser import AioBrowser
from utils.mysql import MySQL
from utils.redisdb import RedisDB
2022-04-14 07:18:45 +00:00
# 无视相关警告
# 该警告说明在官方GITHUB的WIKI中Frequently Asked Questions里的What do the per_* settings in ConversationHandler do?
filterwarnings(action="ignore", message=r".*CallbackQueryHandler", category=PTBUserWarning)
2022-04-14 07:18:45 +00:00
def main() -> None:
Log.info("正在启动项目")
2022-06-08 08:26:53 +00:00
# 初始化数据库
2022-06-08 08:26:53 +00:00
Log.info("初始化数据库")
mysql = MySQL(host=config.MYSQL["host"], user=config.MYSQL["user"], password=config.MYSQL["password"],
port=config.MYSQL["port"], database=config.MYSQL["database"])
# 初始化Redis缓存
Log.info("初始化Redis缓存")
redis = RedisDB(host=config.REDIS["host"], port=config.REDIS["port"], db=config.REDIS["database"])
# 初始化Playwright
Log.info("初始化Playwright")
browser = AioBrowser()
# 传入服务并启动
Log.info("传入服务并启动")
service = StartService(mysql, redis, browser)
# 构建BOT
Log.info("构建BOT")
2022-06-09 12:52:59 +00:00
application = Application.builder().token(config.TELEGRAM["token"]).build()
2022-05-28 09:26:56 +00:00
register_handlers(application, service)
# 启动BOT
try:
Log.info("BOT已经启动 开始处理命令")
2022-06-08 08:26:53 +00:00
# BOT 在退出后默认关闭LOOP 这时候得让LOOP不要关闭
application.run_polling(close_loop=False)
except (KeyboardInterrupt, SystemExit):
pass
except Exception as exc:
Log.info("BOT执行过程中出现错误")
raise exc
finally:
Log.info("项目收到退出命令 BOT停止处理并退出")
loop = asyncio.get_event_loop()
try:
2022-06-08 08:26:53 +00:00
# 需要关闭数据库连接
Log.info("正在关闭数据库连接")
loop.run_until_complete(mysql.wait_closed())
2022-06-08 08:26:53 +00:00
# 关闭Redis连接
Log.info("正在关闭Redis连接")
loop.run_until_complete(redis.close())
2022-06-08 08:26:53 +00:00
# 关闭playwright
Log.info("正在关闭Playwright")
loop.run_until_complete(browser.close())
except (KeyboardInterrupt, SystemExit):
pass
except Exception as exc:
2022-06-08 08:26:53 +00:00
Log.error("关闭必要连接时出现错误 \n", exc)
Log.info("正在关闭loop")
2022-06-08 08:26:53 +00:00
# 关闭LOOP
loop.close()
2022-06-08 08:26:53 +00:00
Log.info("项目已经已结束")
2022-04-14 07:18:45 +00:00
if __name__ == '__main__':
main()