DEV Community

Brad
Brad

Posted on

Build a Telegram Bot with Python: Complete 2024 Guide

Build a Telegram Bot with Python: Complete 2024 Guide

Telegram bots are useful for notifications, automation triggers, and team tools.

Setup

pip install python-telegram-bot
Enter fullscreen mode Exit fullscreen mode

Create your bot by messaging @botfather on Telegram, run /newbot, and get your token.

Basic Bot

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

TOKEN = "your-bot-token"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello! I am your automation bot.")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = update.message.text
    await update.message.reply_text("You said: " + text)

app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Enter fullscreen mode Exit fullscreen mode

Send Notifications from Python

import asyncio
from telegram import Bot

bot = Bot(token=TOKEN)
CHAT_ID = "your-chat-id"

async def notify(message):
    await bot.send_message(chat_id=CHAT_ID, text=message)

asyncio.run(notify("Server CPU is high!"))
Enter fullscreen mode Exit fullscreen mode

Inline Keyboards

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler

async def show_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [[
        InlineKeyboardButton("Report", callback_data="report"),
        InlineKeyboardButton("Status", callback_data="status"),
    ]]
    await update.message.reply_text("Choose:", reply_markup=InlineKeyboardMarkup(keyboard))

async def handle_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    if query.data == "report":
        await query.edit_message_text("Generating report...")
    elif query.data == "status":
        await query.edit_message_text("All systems OK")

app.add_handler(CallbackQueryHandler(handle_button))
Enter fullscreen mode Exit fullscreen mode

Schedule Daily Messages

import schedule, time, threading

def send_daily():
    asyncio.run(notify("Daily Report: Revenue $1,234"))

schedule.every().day.at("09:00").do(send_daily)

t = threading.Thread(target=lambda: [schedule.run_pending() or time.sleep(60) for _ in iter(int, 1)], daemon=True)
t.start()
Enter fullscreen mode Exit fullscreen mode

Telegram bots are one of the best tools for automating notifications. The API is free and reliable.


Want 50+ ready-to-use Python automation scripts? Get the complete toolkit for just $9: https://lukassbrad.gumroad.com/l/ugeka

Top comments (0)