How to use python-telegram-bot to send messages to a telegram channel

Viewed 10500

I created a telegram bot and added it to my telegram channel. Now, I want to use it to send messages to my channel, when something is happening in my python program. For example, I have a python program that checks the weather every 15 secs, and when there's a change in the weather, I want my bot to send the new weather information to my telegram channel.

So my question is, how can I do it? I'm stuck because python-telegram-bot requires a message from the user to get triggered, or a scheduled orders, while I can't schedule it because I don't know when the weather will change.

1 Answers

The easiest method to do this is to use the request method. Telegram provides a cool API to send messages with your bot, you need to do that with a link for example :

https://api.telegram.org/bot<yourbottoken>/sendMessage?chat_id=<yourchatid>&text=Hello World!

What this does is that it will send the Hello World message to a certain chat id. If you don't know how to get a chat id, you need to DM your bot and you can use this link :

https://api.telegram.org/bot<yourbottoken>/getUpdates

In the page, there will be quite a lot of JSON data, you need to use Control + F and search for your telegram username without the @ and search for the chat id

If you want to do this in a python code, you need to use the requests module.

import requests
requests.post('https://api.telegram.org/bot<yourbottoken>/sendMessage?chat_id=<yourchatid>&text=Hello World!')
Related