I have a function to send a certain message to all telegram bot(set up through aiogram) users, but for some reason it works only half of the times.
async def send_text():
try:
users = getusers('./database/users.db', "bot_users")
#print(users)
txt = random.choice(fl)
for id in users:
print(id[0])
await SendMessage(chat_id=id[0], text=txt)
today_date = datetime.datetime.now(pytz.timezone('Europe/Paris')).strftime("%d-%m")
await SendMessage(chat_id=id[0], text=(holidays[today_date] if today_date in holidays else "Today is a perfectly normal day"))
logging.info("Sent daily advice and holiday to all bot users")
except:
logging.exception("An error has occurred while trying to send a daily advice")
It works fine, when I manually call it:
@router.message(filters.Command('st'))
async def test(message: types.Message):
await send_text()
When I use scheduler to call it at the specific time it breaks:
async def scheduler():
scheduler = AsyncIOScheduler()
scheduler.add_job(stuff.send_text, 'cron', hour=19, minute=10)
scheduler.start()
async def on_startup():
asyncio.create_task(scheduler())
with an error:
root :: 2023-07-12 20:04:00,014 :: ERROR :: An error has occurred while trying to send a daily advice: <ContextVar name='instance_Bot' at 0x0000026A98914720>
Traceback (most recent call last):
File "C:\Users\il290\Documents\Projects\Telegram_bot\bot.py", line 23, in send_text
await SendMessage(chat_id=id[0], text=txt)
File "c:\Users\il290\Documents\Projects\Telegram_bot\.venv\lib\site-packages\aiogram\methods\base.py", line 96, in __await__
bot = Bot.get_current(no_error=False)
File "c:\Users\il290\Documents\Projects\Telegram_bot\.venv\lib\site-packages\aiogram\utils\mixins.py", line 76, in get_current
current: Optional[ContextInstance] = cls.__context_instance.get()
LookupError: <ContextVar name='instance_Bot' at 0x0000026A98914720>
The scheduler I used is AsyncIOScheduler from apscheduler module
I was already advised to make bot instance accessible in the scheduler(), but passing it as an argument, making it global and moving the code from scheduler directly to where the bot instance is created didn't help