I ask for help with the script for sending messages to the channel telegram, all searches lead to the creation of the bot and its registration, the bot I did, but this campaign is not what I need, I need that the script sent a text post to the channel and everything, maybe sometimes a photo . python 3

  • I advise you to look at pyTelegramBotApi. There is everything you need to start and even more. - Vladimir Chizhov

1 answer 1

Nothing is easier! First you need to at least briefly familiarize yourself with the bot api telegram from where we get the method we need in this particular case - sendMessage . Now you need to decide on the choice of the python library to work with http, since the api telegram works on http (s). Personally, without further ado, I chose requests . Now we start writing the function of sending a message.

#!/usr/bin/env python3 import requests def send_telegram(text: str): token = "ТУТ_ВАШ_ТОКЕН_КОТОРЫЙ_ВЫДАЛ_BotFather" url = "https://api.telegram.org/bot" channel_id = "@ИМЯ_КАНАЛА" url += token method = url + "/sendMessage" r = requests.post(method, data={ "chat_id": channel_id, "text": text }) if r.status_code != 200: raise Exception("post_text error") if __name__ == '__main__': send_telegram("hello world!") 

Sobsno, everything is very simple. We substitute the bot's token token of the botfather in the link, then we specify the api method name through a slash and finally call the post method using the requests library where we substitute the message text and the channel name. Also, if I am not mistaken, the bot must be the administrator of this channel in order to post something there.