How to send telegram messages with python tutorial

How to send telegram messages with python tutorial

Telegram provides an amazing Bot API for developer with the need of automation. The Telegram Bot API is HTTP-based and is useful in different scenearios. In this blog, we will guide you to configure the Bot to send messages with python.
For more information, you can go to the official site. Bot FAQ

Steps to configure Telegram Bot API with Python.

  1. First you will need to open the BOTFATHER menu using this link: https://t.me/botfather
  2. The link will redirect you to your telegram.
  3. Now you will have a chat opened with the BotFather which you can start it right away by clicking start or writing "/start"
  4. To create a new Bot you will have to write in the chat "/newbot" and follow the steps to create a new bot.
BotFather Menu

5. To configure your bot please notice that you will be asked for this:

* Bot name (can be anything)

* Bot username (have to be unique and needs to end with the word "bot")


The BotFather answer will contain the bot's username (like any telegram user) and the HTTP API token which is used to control the bot. Please save the token in a secure place and don't share it with anyone.

Telegram bot creation

6. To activate your bot, please go to the link that has your bot's username and in that chat click "start" or write "/start"

Starting the telegram BOT

7. Add your bot to the group chat where you want the bot to send the messages to.

8.Once the bot is in a telegram group, you can use curl or your normal browser to get the ID of the chat that the bot is in with:

https://api.telegram.org/bot{token}/getUpdates

9. Get the group-id by filtering or looking into the results provided by the step 8 for the name of the telegram group and next to it, it will be the ID of the group (yes it can start with a "-")

You can see something similar:

{"chat":{"id":{chat_id},"title":"GROUP TEST","type":"group","all_members_are_administrators":true}

FINALLY:

Let the bot write a message for you in the telegram group

https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={text}

With python you can use the requests library to send the message and get a response which can be used for error handling if is not 200.

Example(python):

$python3 
>>> import requests
>>> requests.get("https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text=This is a test")
The response will be:
<Response [200]>