Python TelegramBot running a function in job_queue.run_repeating

125 views Asked by At

I want to send a message to the person at certain intervals, there is no problem when the code in check_who_likes works alone, but when I make it a function and try to run it with job_queue, I get an error.

async def check_who_likes(update: Update, context: CallbackContext):
    try:
        conn = connection_pool.get_connection()
        cursor = conn.cursor()
        user_id = update.message.from_user.id
        cursor.execute("SELECT LikeUserID FROM Likes WHERE LikedUserID = %s", (user_id,))
        likes = cursor.fetchall()
        like_ids = [like[0] for like in likes]
        like_ids_str = ', '.join(map(str, like_ids))
        sql_query = f"SELECT UserName FROM Users WHERE PersonID IN ({like_ids_str})"
        cursor.execute(sql_query)
        users = cursor.fetchall()
        liked_users_text = ", ".join(str(user[0]) for user in users)
        await context.bot.send_message(chat_id=user_id,
                                       text=f"{len(likes)} kişi sizi beğendi.Bakmak istermisin?\n\n\n1.Göster.\n2.Artık aramıyorum.")

    except Exception as e:
        pass
    finally:
        cursor.close()
        conn.close()
        await asyncio.sleep(1)
        if update.message.text == "1":
            return SHOW_WHO_LIKES
async def matching(update: Update, context: CallbackContext):
    context.job_queue.run_repeating(check_who_likes, interval=1, first=0)

Error:
No error handlers are registered, logging exception. Traceback (most recent call last): File "C:\wamp64\www\bot\venv\lib\site-packages\telegram\ext_jobqueue.py", line 898, in _run await self.callback(context) TypeError: check_who_likes() missing 1 required positional argument: 'context'

1

There are 1 answers

2
vuongtlt13 On

Your callback is invalid

From docs the Callback signature should be

async def callback(context: CallbackContext)

but your code is

async def check_who_likes(update: Update, context: CallbackContext):

First you need change signature of check_who_likes to correct signature

async def check_who_likes(context: CallbackContext, update: Update):

Next, if you want other arguments, there are 2 options, you could try:

Option 1: pass more kwargs by using job_kwargs in JobQueue.run_repeating WRONG OPTION
async def matching(context: CallbackContext):
    context.job_queue.run_repeating(check_who_likes, interval=1, first=0, job_kwargs=dict(update=update))
Option 2: using functools.partial function
from functools import partial

async def matching(context: CallbackContext):
    context.job_queue.run_repeating(partial(check_who_likes, update=update), interval=1, first=0)