I use register handler ChatMemberHandler with the parameter ChatMemberHandler.CHAT_MEMBER, but I don't have the function callbacked.

I'm using: python-telegram-bot v 21.0.1 python v 3.12.2 anyio v 4.3.0 pymongo v 4.6.2 motor v 3.3.2 python-dotenv v 1.0.1

Main function

def main() -> None:
    application = Application.builder().token(TELEGRAM_TOKEN).build()

    handlers.register_handlers(application)

    application.run_polling()

My function

async def handle_member(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_member_update = update.chat_member
    chat_id = chat_member_update.chat.id
    collection = await connect_to_db()
    if chat_member_update.old_chat_member.status not in [ChatMember.MEMBER, ChatMember.ADMINISTRATOR] and chat_member_update.new_chat_member.status in [ChatMember.MEMBER, ChatMember.ADMINISTRATOR]:
        user_id = chat_member_update.new_chat_member.user.id
        await add_user_to_db(collection, chat_id, user_id)
    elif chat_member_update.new_chat_member.status in [ChatMember.LEFT, ChatMember.KICKED]:
        user_id = chat_member_update.old_chat_member.user.id
        await remove_user_from_db(collection, chat_id, user_id)

register handler

def register_handlers(application: Application) -> None:
   application.add_handler(ChatMemberHandler(handle_member, ChatMemberHandler.CHAT_MEMBER))

Functions for the database

async def connect_to_db():
    client = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URI)
    db = client["VoteBot"]
    collection = db["info"]
    return collection

async def add_user_to_db(collection, chat_id, user_id):
    joined_at = datetime.datetime.now()
    await collection.update_one(
        {"chat_id": chat_id, "user_id": user_id},
        {
            "$setOnInsert": {
                "joined_at": joined_at,
                "chat_id": chat_id,
                "user_id": user_id,
            }
            
        },
        upsert=True
    )

async def remove_user_from_db(collection, chat_id, user_id):
    await collection.delete_one({"chat_id": chat_id, "user_id": user_id})

I expect my bot to register a change in user statuses with the handler and callback the handle_member function, which in turn will call add_user_to_db or remove_user_from_db. But my code doesn't generate any errors, the logger doesn't register any errors. Other register handlers (MessageHandler, CommandHandler, CallbackQueryHandler) work stably and callback their functions.

0

There are 0 best solutions below