Forums

MY python telegram bot works well on local environment but not on pythonanywhere.

.

from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re


def quote(bot, update):
    url = 'https://anime-chan.herokuapp.com/api/quotes/random'
    r = requests.get(url)
    data = r.json()[0]
    new_text="_{}_".format(data['quote'])
    new_char="*{}*".format(data['character'])
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, text= "Quote: "+new_text+'\n'+'\n'+" "+"*-*"+new_char,parse_mode='Markdown')

def main():
    updater = Updater(token)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('quote',quote))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

[edit by admin: formatting]

Does it print out any error messages when you try to run it? If so, what are they?

It doesn't show any error at all. Could it be my code though it works fine on my terminal and post messages when I give the respective command.

But does give me warning saying "Old Handler API is deprecated - see https://git.io/fxJuV for details ".

When you say that it's not working on PythonAnywhere, what are the symptoms of that? Is it just not responding when it is sent messages?

yes, It doesn't respond anything.

Which version of the Telegram API are you using? Is it the same as the version that you are using on your own machine? You can find out by running

pip3.8 freeze Telegram

...on PythonAnywhere, and then the equivalent on your own machine.

from bash console: python-telegram-bot==12.7 from my command prompt: python-telegram-bot==12.7

if possible, you may try the code yourself with your own telegram API token. Thank you.

Thanks! I think I've worked out the problem.

The first thing is that the python-telegram-bot library does not log errors very well in its default configuration. If you put this at the start of your code, it will log errors to the console:

import logging
logging.basicConfig(level=logging.ERROR,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

With that in place, I was able to see what the real error is; you're trying to access anime-chan.herokuapp.com when you receive a message, and that site was not on the whitelist of sites that free accounts can access. As it is a documented public API, I've added it to the whitelist now, so the sample code you posted above will work, but I recommend that you put that logging code into your bot so that if you have other errors in the future, you'll know what they are.

Thank you giles. That solved the problem. You are a saviour:)

MY python telegram bot works well on pythonanywhere, but dont launch on telegram

We need more details to help you. What does " don't launch on telegram" mean?