4

The question is about using webhooks in a Telegram bot using the pyTelegramBotAPI module. I am using pythonanywhere.com to host the bot.

The following code works fine:

from flask import Flask, request
import telebot

secret = "A_SECRET_NUMBER"
bot = telebot.TeleBot ('YOUR_AUTHORIZATION_TOKEN')
bot.set_webhook("https://YOUR_PYTHONANYWHERE_USERNAME.pythonanywhere.c..
}".format(secret), max_connections=1)

app = Flask(__name__)
@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
   update = request.get_json()
   if "message" in update:
   text = update["message"]["text"]
   chat_id = update["message"]["chat"]["id"]
   bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
return "OK"

But when I use message handlers as shown in the example, I receive no answer from the bot:

# Process webhook calls
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
   if flask.request.headers.get('content-type') == 'application/json':
   json_string = flask.request.get_data().decode('utf-8')
   update = telebot.types.Update.de_json(json_string)
   bot.process_new_updates([update])
   return ''
else:
   flask.abort(403)

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
   def send_welcome(message):
   bot.reply_to(message,
   ("Hi there, I am EchoBot.\n"
   "I am here to echo your kind words back to you."))

# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
   def echo_message(message):
   bot.reply_to(message, message.text)

I have tried examples from different libraries, but still no answer.

Any ideas?

It would be great if you could share a working example of Telegram "echo-bot" on pythonanywhere.com.

Thanks.

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
AlexeyStepkin
  • 41
  • 1
  • 3

2 Answers2

5

You should disable threading in the TeleBot constructor like this:

bot = telebot.TeleBot('YOUR_AUTHORIZATION_TOKEN', threaded=False)

I had the same issue and found a solution here: https://www.pythonanywhere.com/forums/topic/9562/#id_post_40177

Threading is unavailable for free PythonAnywhere accounts.

makeiteasy
  • 766
  • 7
  • 11
  • On PythonAnywhere threading is currently not available in web apps for all account types, but it can be used in Always-on tasks (paid account required). – caseneuve Jan 20 '22 at 10:47
-1

Error in 17th line. return "ok" not in telegram_webhook function.

  • I believe line 17 was actually a copying error that was not present in the original code, as the OP says that the code works fine. – Patrick Yoder Jan 23 '22 at 19:10