How to send notifications to Telegram with Python

Andrei Kushniarou
7 min readAug 6, 2024

--

As a programmer, data engineer, and BI analyst, I often need to send messages to Telegram to ensure everything is running smoothly. Notifications are sent for various events, such as anomaly alerts when something breaks or stops working. My clients receive daily reports, price change notifications, or alerts when someone starts selling their product on Amazon (I recently wrote an article about creating such a bot [1])

Setting up notifications in your Python scripts via a Telegram bot is not only simple but also highly effective. Telegram is a versatile platform that allows you to send messages to different channels, and it can be easily integrated into both public and private groups with any number of participants. The bot will only have the ability to send messages, ensuring privacy and security for all other communications. Today, I’ll walk you through the process of automating these notifications with Python, making your workflow more efficient and hassle-free.

Picture from DALL-E to attract attention :)

Table of Contents:

  • Creating a Telegram Bot
  • Creating a New Group and Finding its ID
  • Sending a Message from Python
  • Sending a Very Long Message from Python
  • Sending an Image from Python

Creating a Telegram Bot

Creating a Telegram bot is very straightforward. To create your new bot, you need to find a special bot called BotFather on Telegram. BotFather is the “father” of all other bots and is used to manage your bots. Search for it (type “BotFather” in the search bar), then type /newbot.

Next, you’ll be asked to name your bot, which must end with “bot”. I named my bot andrew_medium_test_bot. If the name is available, you'll receive an API key.

Using this API key, we can interact with the bot and send messages.

Creating a New Group and Finding its Chat ID

Your newly created bot cannot just send messages to anyone or any group. To enable it to send messages, you need to add it to a Telegram group. You can add the bot to any existing group (if you have permission), or create a new group and add your Telegram bot to it.

Click on “Create a New Group”.

Set the group name (I wrote “Andrew Medium Test Group”)

Click on “Add Members”, search for your new bot, and add it to the members list.

Finally, click “Create” to create the new group.

Perfect! Now you have an empty group with two members, one of which is the bot.

If you click on the three dots and select “Info”, you can view the group members.

Note that by default, the bot doesn’t have access to messages (this can be changed in the bot’s settings).

The next step is to find the group’s Chat ID, which is necessary to know where to send messages. Unfortunately, Chat ID is not visible in the Telegram interface. The only way to find it is by sending a message to the bot and then using a small Python script to retrieve the latest messages.

Let’s write a message addressed directly to the bot (in private mode, by default, the bot can only read such messages). Type a short message starting with a slash, followed by the bot’s name.

Now, let’s write a script to find the Chat ID. Install the Python package to work with Telegram bots:

pip install python-telegram-bot

Then write the code to iterate through all the updates available to the bot and output the chat ID, chat title, and message:

import asyncio
from telegram import Bot

TELEGRAM_BOT_TOKEN = '[INSERT YOUR BOT TOKEN HERE]'

async def main():

#Create bot object
bot = Bot(token=TELEGRAM_BOT_TOKEN)

#Get updates
updates = await bot.get_updates()

if not updates:
print("No updates found")
else:
for update in updates:
if update.message:

#Show all message data if needed
#print(update.message)

#Show only chat id, title and message
chat_id = update.message.chat.id
chat_title = update.message.chat.title
message_text = update.message.text
print(f"Chat ID: {chat_id} | Chat Title: {chat_title} | Message: {message_text}")

asyncio.run(main())
Chat ID: -4206954951  | Chat Title: Andrew Medium Test Group | Message: /hello @andrew_medium_test_bot

When we run the script, we see the Chat ID of our group, for example: Chat ID: -4206954951. The negative group identifier in Telegram is normal, don't worry 😆

Sending a Message from Python

Now that we have the Chat ID, we can send a message to the group using bot.send_message. The Telegram bot in Python works through asyncio, asynchronous code, so I run it through a wrapper function.

from telegram import Bot
import asyncio

TELEGRAM_BOT_TOKEN = '[INSERT YOUR BOT TOKEN HERE]'
CHAT_ID = '[INSERT YOUR CHAT ID HERE]'

#Define bot
bot = Bot(token=TELEGRAM_BOT_TOKEN)

async def send_message(text, chat_id):
async with bot:
await bot.send_message(text=text, chat_id=chat_id)

async def run_bot(messages, chat_id):
text = '\n'.join(messages)
await send_message(text, chat_id)

#Test messages
messages = [
'Product https://www.amazon.com/dp/B08C1W5N87, the price has changed from $24.99 to $26.99',
'New negative review (rating 2) added for product https://www.amazon.com/dp/B0CL61F39H',
'Attention! Average sales are 50% lower than usual over the last 3 hours!'
]

if messages:
asyncio.run(run_bot(messages, CHAT_ID))

I set up three example messages as an array, and here’s how the message appears in the group when the script is run.

Simple, right?

Sending a Very Long Message from Python

If the message length exceeds 4096 characters, an error will occur, so it’s better to split the message into parts:

from telegram import Bot
from telegram.error import BadRequest
import asyncio

TELEGRAM_BOT_TOKEN = '[INSERT YOUR BOT TOKEN HERE]'
CHAT_ID = '[INSERT YOUR CHAT ID HERE]'

#Define bot
bot = Bot(token=TELEGRAM_BOT_TOKEN)

async def send_long_message(text, chat_id):

MAX_MESSAGE_LENGTH = 4096
parts = [text[i:i + MAX_MESSAGE_LENGTH] for i in range(0, len(text), MAX_MESSAGE_LENGTH)]

async with bot:
for part in parts:
try:
await bot.send_message(chat_id=chat_id, text=part)
except BadRequest as e:
print(f"Failed to send message part: {str(e)}")

async def run_bot(messages, chat_id):

text = '\n'.join(messages)
await send_long_message(text=text, chat_id=chat_id)

#Test messages
messages = [
'Product https://www.amazon.com/dp/B08C1W5N87, the price has changed from $24.99 to $26.99',
'New negative review (rating 2) added for product https://www.amazon.com/dp/B0CL61F39H',
'Attention! Average sales are 50% lower than usual over the last 3 hours!'
]*20

if messages:
asyncio.run(run_bot(messages, CHAT_ID))

The result…

Now, very long messages are sent correctly.

Sending an Image from Python

Next, let’s try sending an image to Telegram. I’ll be sending a dynamically created chart based on data from pandas. This is a great use case, as our bot can send graphical statistics based on analytics data once a day.

from telegram import Bot, InputFile
import asyncio
import pandas as pd
import matplotlib.pyplot as plt
import io

TELEGRAM_BOT_TOKEN = '[INSERT YOUR BOT TOKEN HERE]'
CHAT_ID = '[INSERT YOUR CHAT ID HERE]'

# Define bot
bot = Bot(token=TELEGRAM_BOT_TOKEN)

async def send_image(image, chat_id):
async with bot:
await bot.send_photo(chat_id=chat_id, photo=InputFile(image))

async def run_bot_image(image, chat_id):
await send_image(image, chat_id)

def create_price_chart():
#Generate dummy data for dataframe
data = {
'Date': pd.date_range(start='2024-08-01', periods=10, freq='D'),
'Price': [24.99, 25.49, 26.00, 25.75, 26.99, 26.50, 27.00, 26.80, 27.20, 27.50]
}
df = pd.DataFrame(data)

#Build simple graph
fig, ax = plt.subplots()
ax.plot(df['Date'], df['Price'], marker='o')
ax.set_title('Price Trend')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
plt.xticks(rotation=45)

#Save graph to buffer
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
plt.close()

return buf

#Generate image with chart
image = create_price_chart()

#Send image to Telegram
asyncio.run(run_bot_image(image, CHAT_ID))

And here’s the result after running the script.

Excellent! Now we know how to quickly and easily send analytics data to a Telegram bot!

Userful Links

  1. Amazon Buy Box Tracking with Keepa and Python (with Telegram Bot) https://medium.com/@andrewkushnerov/amazon-buy-box-tracking-with-keepa-and-python-460d86037ebb
  2. Telegram Bot Official API: https://core.telegram.org/bots/api
  3. Python Telegram Bot Package: https://github.com/python-telegram-bot/python-telegram-bot

--

--

Andrei Kushniarou
Andrei Kushniarou

Written by Andrei Kushniarou

Full-stack developer, BI/data engineer, and entrepreneur with 20+ years of experience. Founder at SellerFlux, empowering e-commerce with data-driven solutions.

No responses yet