8

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.

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 Commented Mar 13, 2021 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 Commented Mar 13, 2021 at 12:08

1 Answer 1

11

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!')
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks! I didn't know about telegram API. that makes my life much easier. where can I find all the API request method links? And one more thing, how can I send the message in a formatted string and let's say with \n in python? Thanks!
Hey! you can read more about it in Telegram Bot API Manual You can use markdown formatting, it's Here!
It didn't work for me
@SAM what did not work?
@Quebeh using requests.post didn't work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.