Sending message to Telegram Group, User or Bot using Python
In Programming world, most of the time while automating a system/tasks you need to send completion or timely notification about the status. Now a days the easiest way of notification is WhatsApp or Telegram as our SMS and email boxes are mostly flooded with spams. In this article we will try to explain about telegram automation using simple Python script.
Install json and telegram package using pip package manager:
pip install json
pip install python-telegram-bot
read token of your telegram bot and chat_id from json file telegram_credentials.json
call notify_(message) function from the point in your script where you need to send notification and pass token and chat_id to it.
import json
import telegram
def notify_(message):
t_bot = telegram.Bot(token=token)
t_bot.sendMessage(chat_id=chat_id, text=message)
with open('./telegram_credentials.json', 'r') as keys_file:
k = json.load(keys_file)
token = k['telegram_token']
chat_id = k['telegram_chat_id']
notify_("Some Message!")
The main problem developer face is to find out chat_id of user/group/channel, or creating a bot. Below are the simple steps to create bot and find out chat_id:
- Download telegram application to your phone if not present.
- Search for BotFather in seach box, and initate the chat.
- BotFather will guide you for new Bot creation using /newbot command.
- BotFather will ask you to choose your Bot name, which has to be unique, once created BotFather will respond with new bot's token. This bot is required by telegram APIs.
- You bot creation is complete and you have token.
- Now search for your bot in search box and initiate chat with bot using /start command and /my_id
- Now to find out chat_id, open below URL in browser by replacing your own bot's token.
https://api.telegram.org/bot<your-bot-token-comes-here>/getUpdates - you will find your chat_id in the response.
For public channel, chat_id is the unique id of the channel.
Happy Coding!
Comments
Post a Comment