skip to Main Content

Here I have a code for making a simple echo bot for telegram.

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging

from data.constants import API_TOKEN, LOGGING_FORMAT

logging.basicConfig(format=LOGGING_FORMAT, level=logging.DEBUG)

updater = Updater(token=API_TOKEN)
dispatcher = updater.dispatcher


def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='Hello, dude.')


def echo(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=update.message.text)


start_handler = CommandHandler('start', start)
echo_handler = MessageHandler(Filters.text, echo)


dispatcher.add_handler(start_handler)
dispatcher.add_handler(echo_handler)


if __name__ == '__main__':
    updater.start_polling()
    updater.idle()

I used a python-telegram-bot library for that.

For some reason, this bot recognizes only commands, but not plain text. I mean, the echo function echoes me only text, started from /. The function start works as it should.
The more interesting thing, that the same problem I had with another telegram-bot library – aiogram.

After got crazy I wrote to python-telegram-bot support to ask advice in solving my problem.
After running my snippet, support admitted, that it works fine for them and advice me last-hope-move: to try it on a new bot. I got new API key from @BotFather, tried it out, but now I’m here. That means my code still doesn’t work properly.

There’re some references, that could help us to solve it:

https://python-telegram-bot.readthedocs.io/en/latest/telegram.html
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-–-Your-first-Bot

But I suppose, that the problem is in my working environment, despite I tried to run my code on different fresh device.

2

Answers


  1. Chosen as BEST ANSWER

    SOLVED: for a bot to recognize not only commands, but text messages either we need to disable privacy mode


  2. My suggestion is to follow the Python Telegram samples where the CommandHandler and MessageHandler objects are defined when setting the handlers

    dp = updater.dispatcher
    
    dp.add_handler(CommandHandler("help", help_command_handler))
    dp.add_handler(MessageHandler(Filters.text, main_handler))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search