diff --git a/bot.py b/bot.py index 1c8b886..fa45bde 100644 --- a/bot.py +++ b/bot.py @@ -1,10 +1,12 @@ +import asyncio import logging from aiogram import executor -from load import dp, config import filters import handlers +from load import dp, config +from utils.updater import updater skip_updates=True @@ -28,10 +30,17 @@ async def on_shutdown(dp): if __name__ == "__main__": + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.create_task(updater()) if config["WebHook"]["use"].lower() in ["yes", "true"]: + # https://github.com/aiogram/aiogram/pull/795/commits/a7e0ce2971a0a320849c8b11080fa6b737b6935b + # Needed for async tasks :3 + # Only for webhooks! For polling not needed patching file executor.start_webhook( dispatcher=dp, + loop=loop, skip_updates=skip_updates, webhook_path="{}{}".format(config["WebHook"]["webhook_path"], config["Bot"]["token"]), on_startup=on_startup, diff --git a/database/worker.py b/database/worker.py index c8efeda..90a4430 100644 --- a/database/worker.py +++ b/database/worker.py @@ -1,3 +1,5 @@ +from typing import Union + from aiogram import types from .model import db, Users @@ -7,7 +9,16 @@ from .model import db, Users db.create_tables([Users]) -def register(user: types.User, data: dict): +def register(user: Union[types.User, int], data: dict, task_update: bool=False): + if task_update and (Users.select().where(Users.user_id==user, Users.tag == data['tag']).exists()): + Users.update( + tag = data['tag'], + nickname = data['name'], + townhall = data['townHallLevel'], + attackwins = data['attackWins'] + ).where(Users.user_id == user, Users.tag == data['tag']).execute() + return + if not Users.select().where(Users.user_id==user.id, Users.tag == data['tag']).exists(): Users.create( user_id = user.id, diff --git a/requirements.txt b/requirements.txt index 7625492..1ca3abd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ aiogram==2.19 requests==2.27.1 -peewee==3.14.10 \ No newline at end of file +peewee==3.14.10 +aioschedule==0.5.2 \ No newline at end of file diff --git a/utils/updater.py b/utils/updater.py new file mode 100644 index 0000000..b8604a0 --- /dev/null +++ b/utils/updater.py @@ -0,0 +1,24 @@ +import asyncio +import aioschedule as schedule + +from load import coc_api +from database.worker import get_users, register + + +async def check_update(): + users = get_users() + if users is None: + return + for user in users: + user_id = user["user_id"] + tag = user['tag'] + data = coc_api.get_player(tag) + register(user_id, data, task_update=True) + + +async def updater(): + schedule.every(1).hour.do(check_update) + + while True: + await schedule.run_pending() + await asyncio.sleep(5)