Search code examples
pythontelegrampy-telegram-bot-apitelebot

Can send a message using the Telegram API via. the browser but not a python script


I can send a message to a telegram channel that includes my own bot using the following url in a browser:

https://api.telegram.org/bot*****/sendMessage?chat_id=-********&text=Hello%20World! #there's a - before the chat id value

However, the following python code:

import telebot

API_TOKEN = '*********'
bot = telebot.TeleBot(API_TOKEN)
chat_id='-*******'

try:
    text_telegram='testing'
    print('line1')  
    print(bot.send_message(chat_id, text_telegram))
    print('line2')  
except Exception as e:
    print(e)

Returns:

{'ok': False, 'error': 'Got unexpected response. (404) - {"ok":false,"error_code":404,"description":"Not Found"}'}

UPDATE:

So running the following commands resolved my issue. Can someone please explain why I had to run this and what's the reason for the last line? Surely the third line installs the latest version?

pip3 uninstall telebot
pip3 uninstall PyTelegramBotAPI
pip3 install pyTelegramBotAPI
pip3 install --upgrade pyTelegramBotAPI

Solution

  • My guess is that you used the tele_bot package, which is not the offical one thus probably bugged and not working. So your fix removed the bad package (pip3 uninstall...), and the following lines installed the aproporaite (offical) package.

    Assuming you uninstalled PyTelegramBotAPI, reinstalling should have bee sufficent. If you hadn't uninstalled it, updating (line 4) is a good idea.

    Side note: You supplied the tele_bot package with your private API keys, I haven't examined that package, but it could be malicous and stole you API token. So I would recommend invalidating the old API token and generating a new one.