Issue
I am trying to send out price alerts for cryptocurrency in a telegram bot I am working on that uses aiogram. The issue I am having is that I am not certain how to start a function as a background, non blocking thread, and then proceed to start the dispatcher. I know how to do this using the standard synchronous telegram bot, but I am confused as to what I am supposed to do with aiogram. I read I can use dp.loop.create_task
here but that throws an error Nonetype has no attribute create_task
. Here is the code that I am trying to execute these threads with:
print('Starting watchlist process, this needs to run as a non blocking daemon...')
dp.loop.create_task(wl.start_process())
print('Starting broadcaster, this needs to run as a non blocking daemon ... ')
dp.loop.create_task(broadcaster())
print('Starting the bot ...')
executor.start_polling(dp, skip_updates=True)
I simply need the wl.start_process
and broadcaster
functions to run in the background. How do I accomplish this?
This is start_process
:
async def start_process(self):
"""
Start the watchlist process.
:return:
"""
threading.Thread(target=self.do_schedule).start()
await self.loop_check_watchlist()
And this is broadcaster
:
async def broadcaster():
count = 0
while True:
uid_alerts = que.__next__()
if uid_alerts:
for i in uid_alerts:
uid = i[0]
alert = i[1]
try:
if await send_message(uid, alert):
count += 1
await asyncio.sleep(.05) # 20 messages per second (Limit: 30 messages per second)
finally:
log.info(f"{count} messages successful sent.")
Solution
I created for your the following working example, it demonstrates how to create background task on bot start and how to create background task with the help of user commands.
from aiogram import Dispatcher, executor, Bot
from aiogram import types
import asyncio
import logging
TOKEN = "your token!"
async def background_on_start() -> None:
"""background task which is created when bot starts"""
while True:
await asyncio.sleep(5)
print("Hello World!")
async def background_on_action() -> None:
"""background task which is created when user asked"""
for _ in range(20):
await asyncio.sleep(3)
print("Action!")
async def background_task_creator(message: types.Message) -> None:
"""Creates background tasks"""
asyncio.create_task(background_on_action())
await message.reply("Another one background task create")
async def on_bot_start_up(dispatcher: Dispatcher) -> None:
"""List of actions which should be done before bot start"""
asyncio.create_task(background_on_start()) # creates background task
def create_bot_factory() -> None:
"""Creates and starts the bot"""
dp = Dispatcher(Bot(token=TOKEN))
# bot endpoints block:
dp.register_message_handler(
background_task_creator,
commands=['start']
)
# start bot
executor.start_polling(dp, skip_updates=True, on_startup=on_bot_start_up)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
create_bot_factory()
Answered By - Artiom Kozyrev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.