i'm creating a telegram bot using pyhton, specifically the following module
What i want to do is:
My current python implementation:
def echo(update: Update, context: CallbackContext) -> None:
if 'text' in update.message:
update.message.reply_text('I found your key value you are looking for')
else:
update.message.reply_text('Key not found')
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(MY_TOKEN)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Structure of update
object:
{
"update_id":id_update,
"message":{
"message_id":1579,
"date":1615193338,
"chat":{
"id":id_chat,
"type":"private",
"username":"XXX",
"first_name":"XXX"
},
"text":"Hello Bot",
"entities":[
],
"caption_entities":[
],
"photo":[
],
"new_chat_members":[
],
"new_chat_photo":[
],
"delete_chat_photo":false,
"group_chat_created":false,
"supergroup_chat_created":false,
"channel_chat_created":false,
"from":{
"id":id_chat,
"first_name":"xxx",
"is_bot":false,
"username":"xxx",
"language_code":"it"
}
}
}
When i test it i didn't get any output from the bot, it seems like it is ignoring the if/else condition.
If i print the update.message.text
i see correctly the input sent to the bot.
Thank you all
EDIT
I found the solution, i had to change the filter passed to MessageHandler in this way
dispatcher.add_handler(MessageHandler(Filters.all, echo))
Thanks anyway for the help
Your edit is very likely not the actual solution. Using Filters.all
instead of Filters.text & ~Filters.command
just says that the MessageHandler
will catch any message and not just messages that contain text and don't start with a botcommand.
The problem rather is that 'text' in update.message
can't work as update.message
is a telegram.Message
object and not iterable. Therefore 'text' in update.message
will probably throw an error, which you don't see as you have neither logging enabled nor an error handler registered (see the PTB readme and wiki, respectively for info on logging & error handlers).
My guess is that changing to 'text' in update.message.text
should do the trick.