How to use python-telegram-bot to send messages to a telegram channel
Asked Answered
W

1

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.

Waneta answered 13/3, 2021 at 11:1 Comment(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 intervalTram
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 timeWaneta
G
12

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!')
Garwood answered 13/3, 2021 at 11:11 Comment(9)
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!Waneta
Hey! you can read more about it in Telegram Bot API Manual You can use markdown formatting, it's Here!Garwood
It didn't work for meParkman
@Parkman what did not work?Garwood
@Garwood using requests.post didn't work.Parkman
@Parkman did it give any error? What statuscode?Garwood
no it didn't give any errorParkman
@Parkman did it just not send to the target?Garwood
Thanks a lot the problem was from ISP.Parkman

© 2022 - 2024 — McMap. All rights reserved.