skip to Main Content

I’m working with telegram-bot and mysql-connector with a MySQL DB to store all user data.

3 times a day I need to run the query:

UPDATE users SET rolls = rolls + 1 WHERE rolls < 12;

In the main file, that handles the commands for the telegram-bot I have some function, for e.g:

async def show_rolls(update: Update, context: ContextTypes.DEFAULT_TYPE, rolls):
    await update.message.reply_text(rolls)

if __name__ == '__main__':
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler('rolls', show_rolls))

Every time a user uses the /rolls
command the bot shows how many rolls they have (which are stored in the Database, they get 3 every day)

Tried the schedule module, in the database.py file:

import schedule

schedule.every().day.at('15:00').do(add_rolls)
while True:
    schedule.run_pending()

The add_rolls function just does the query I mentioned, it works as intended.

Entering the while loop stops everything, when the users sends a command the bot doesn’t respond.

Also tried the following, using the telegram-bot module itself:

async def add_roll_schedule(context: ContextTypes.DEFAULT_TYPE) -> None:
    roll1_time = datetime.time(
        hour=18, minute=0, tzinfo=pytz.timezone('America/Sao_Paulo'))
    context.job_queue.run_daily(add_rolls, roll1_time)
    
   job = context.job
   await context.bot.send_message(job.chat_id, text='Rolls Added') 

But I can’t find a way to call this command every time the bot is online, since is required to send the context.

2

Answers


  1. Chosen as BEST ANSWER

    Found a solution using the threading python module.

    To be more efficient I will not show my exact functions, just a e.g:

    import schedule, time, threading
    
    def hello():
        print('hello')
    
    def check_schedule():
        while True:
             schedule.run_pending()
             time.sleep(1)
    
    # Start a new thread only to check if there is any schedule pending.
    threading.Thread(target=check_schedule).start() 
    
    # Defining when the function is called
    schedule.every().day.at('19:00').do(hello) 
    

    If anyone has a more efficient/healthy way to do this, let me know! :)


  2. The JobQueue is also available as Application.job_queue. So you can schedule jobs directly after defining the app in your example.

    In general, I would advice not to mix threading and asyncio.


    Disclaimer: I’m currently the maintainer of python-telegram-bot.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search