7

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.

Tom
  • 71
  • 1
  • 1
  • 2
  • You can get the weather, then store it in another temp variable. Then You can use a if condition, to check if weather info in that temp variable is same or not. If it isn't, send the message via bot, and update the temp variable. You can use a while True loop, with time.sleep(interval) to run the check weather function after set interval – TechySharnav Mar 13 '21 at 11:06
  • yes, that's what I wanted to do, but the problem is with python-telegram-bot library. It doesn't allow you to send a message without a user request or schedule a message in a known time – Tom Mar 13 '21 at 12:08

1 Answers1

10

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!')
Quebeh
  • 134
  • 10