Thursday, 31 March 2022

python telegram bot ignoring messages

From time to time my telegram bot seems to ignore messages. Unfortunately it never happens to me but to other users and only when they are asked to upload a photo or pdf. Sometimes the corresponding handler is not called. The problem persists even when the MessageHandler has no filters at all. I am using python-telegram-bot v13.7.

Please find below a minimal sample. It should print "receiving something" whenever the handler is called but sometimes it doesn't.

Is there anything I can do?

EDIT: modified the sample to be a MWE (you have to provide a valid telegram bot ID). Most of the time it works just fine but sometimes it will fail and not print "receiving something" although the user uploaded some document (mostly images).

from telegram import Update
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    ConversationHandler,
    CallbackContext,
)

UPLOAD = 0

def welcome(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('Available commands: /upload')
    return ConversationHandler.END

def upload(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('Please upload document.')
    return UPLOAD

def receive(update: Update, context: CallbackContext) -> int:
    print('receiving something...')
    update.message.reply_text('Thank you.')
    return ConversationHandler.END

def cancel(*args) -> int:
    print('cancelled')
    return welcome(*args)

def handle(*args, **options):
    updater = Updater(" ...... ")
    dispatcher = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('upload', upload),
                      MessageHandler(Filters.text, welcome)
                      ],
        states={
            # UPLOAD: [CommandHandler('cancel', cancel), MessageHandler(Filters.photo | Filters.document.pdf, receive)],
            UPLOAD: [CommandHandler('cancel', cancel), MessageHandler(Filters.all, receive)],
        },
        fallbacks=[CommandHandler('cancel', cancel)],
        conversation_timeout=60
    )

    dispatcher.add_handler(conv_handler)
    updater.start_polling()
    updater.idle()

handle()


from python telegram bot ignoring messages

No comments:

Post a Comment