Home  /  Blog  /  Hadith Telegram Bot

Build a Hadith Telegram Bot with Python

Python7 min readNovember 2026

This post shows you how to build a Telegram bot that sends a fresh hadith every day and lets users search hadiths by keyword. You will use python-telegram-bot and the free UmmahAPI Hadith API.

What you need

Before writing any code, make sure you have these things ready.

Install the two packages you need. python-telegram-bot version 20 and above uses an async interface. The [job-queue] extra pulls in APScheduler, which handles the daily scheduling.

pip install "python-telegram-bot[job-queue]" requests

Tip. To find your Telegram chat ID, send a message to your bot and then visit https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates in a browser. The chat.id field in the response is what you need.

Project structure

Keep things simple. One file is enough for this bot.

hadith-bot/
  bot.py
  .env

Store your secrets in a .env file so you do not accidentally push them to GitHub. Install python-dotenv to load them.

pip install python-dotenv
# .env
BOT_TOKEN=your_telegram_bot_token_here
UMMAH_API_KEY=your_ummahapi_key_here
DAILY_CHAT_ID=your_chat_id_here

Fetching hadiths from UmmahAPI

UmmahAPI has two endpoints you will use most. The random hadith endpoint and the search endpoint. Check the full API docs for everything available.

Here is a small helper module that wraps both calls. It also formats the response into a clean string ready for Telegram.

import requests
import os

BASE = "https://ummahapi.com/api"
API_KEY = os.getenv("UMMAH_API_KEY", "")

HEADERS = {}
if API_KEY:
    HEADERS["x-api-key"] = API_KEY


def get_random_hadith():
    """Fetch a random hadith from UmmahAPI."""
    r = requests.get(f"{BASE}/hadith/random", headers=HEADERS, timeout=10)
    r.raise_for_status()
    return r.json()


def search_hadiths(keyword):
    """Search hadiths by keyword. Returns a list of results."""
    r = requests.get(
        f"{BASE}/hadith/search",
        params={"q": keyword},
        headers=HEADERS,
        timeout=10
    )
    r.raise_for_status()
    return r.json()


def format_hadith(hadith):
    """Turn a hadith dict into a readable Telegram message."""
    collection = hadith.get("collection", "Unknown").capitalize()
    number = hadith.get("number", "")
    narrator = hadith.get("narrator", "")
    text = hadith.get("text", "No text available.")

    lines = [f"📖 *{collection}* #{number}"]
    if narrator:
        lines.append(f"_{narrator}_")
    lines.append("")
    lines.append(text)
    return "\n".join(lines)

Building the bot commands

Now build the actual bot. You need three commands.

import logging
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    ContextTypes,
)
from hadith_api import get_random_hadith, search_hadiths, format_hadith

load_dotenv()

BOT_TOKEN = os.getenv("BOT_TOKEN")
DAILY_CHAT_ID = os.getenv("DAILY_CHAT_ID")

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = (
        "Assalamu alaikum! 👋\n\n"
        "Here are the available commands:\n"
        "/hadith — get a random hadith\n"
        "/search <keyword> — search hadiths by keyword"
    )
    await update.message.reply_text(text)


async def hadith(update: Update, context: ContextTypes.DEFAULT_TYPE):
    try:
        data = get_random_hadith()
        message = format_hadith(data)
        await update.message.reply_text(message, parse_mode="Markdown")
    except Exception as e:
        logging.error(f"Error fetching hadith: {e}")
        await update.message.reply_text("Could not fetch a hadith right now. Try again in a moment.")


async def search(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args:
        await update.message.reply_text("Please add a keyword. Example: /search patience")
        return

    keyword = " ".join(context.args)
    try:
        results = search_hadiths(keyword)
        if not results:
            await update.message.reply_text(f"No hadiths found for '{keyword}'.")
            return

        # Show up to 3 results so the message is not too long
        messages = [format_hadith(h) for h in results[:3]]
        reply = (f"Found {len(results)} result(s) for '{keyword}'. Showing top 3:\n\n"
                 + "\n\n---\n\n".join(messages))
        await update.message.reply_text(reply, parse_mode="Markdown")
    except Exception as e:
        logging.error(f"Search error: {e}")
        await update.message.reply_text("Search failed. Please try again.")

Adding the daily hadith job

This is where the bot gets useful for a group or channel. Every day at 08:00 UTC, the bot sends a random hadith to the chat ID you configured.

run_daily() takes the callback, the time, and optional days of the week. If you leave days out it runs every day.

from datetime import time as dtime


async def send_daily_hadith(context: ContextTypes.DEFAULT_TYPE):
    """Job callback that sends a hadith to the configured chat."""
    try:
        data = get_random_hadith()
        message = "🌅 *Daily Hadith*\n\n" + format_hadith(data)
        await context.bot.send_message(
            chat_id=DAILY_CHAT_ID,
            text=message,
            parse_mode="Markdown"
        )
    except Exception as e:
        logging.error(f"Daily hadith job failed: {e}")

Putting it all together

Now wire everything up in the main() function. Register the command handlers, schedule the daily job, and start polling.

def main():
    app = ApplicationBuilder().token(BOT_TOKEN).build()

    # Register commands
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("hadith", hadith))
    app.add_handler(CommandHandler("search", search))

    # Schedule daily hadith at 08:00 UTC
    app.job_queue.run_daily(
        send_daily_hadith,
        time=dtime(hour=8, minute=0, second=0)
    )

    logging.info("Bot is running...")
    app.run_polling()


if __name__ == "__main__":
    main()

Run it with:

python bot.py

Send /start to your bot in Telegram and you should see the welcome message straight away.

Searching a specific collection

The search endpoint searches across all collections by default. But you can also fetch from a specific collection. For example, to get hadith number 1 from Sahih Bukhari you call:

import requests

r = requests.get("https://ummahapi.com/api/hadith/bukhari/1", timeout=10)
data = r.json()
print(data["text"])

You could add a /collection command that lets users pick a collection and a hadith number. Here is a simple version of that command to drop into your bot.

async def collection(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """
    Usage: /collection bukhari 1
    Fetches a specific hadith by collection name and number.
    """
    if len(context.args) != 2:
        await update.message.reply_text(
            "Usage: /collection <name> <number>\nExample: /collection bukhari 1"
        )
        return

    name, number = context.args[0].lower(), context.args[1]
    url = f"https://ummahapi.com/api/hadith/{name}/{number}"

    try:
        r = requests.get(url, headers=HEADERS, timeout=10)
        r.raise_for_status()
        message = format_hadith(r.json())
        await update.message.reply_text(message, parse_mode="Markdown")
    except requests.HTTPError as e:
        if r.status_code == 404:
            await update.message.reply_text(f"Could not find hadith {number} in '{name}'.")
        else:
            logging.error(f"HTTP error: {e}")
            await update.message.reply_text("Something went wrong. Please try again.")

Register it with app.add_handler(CommandHandler("collection", collection)) in your main() function. The available collection names are: bukhari, muslim, tirmidhi, abudawud, nasai, ibnmajah, malik, nawawi, qudsi, and dehlawi. You can confirm them by calling /api/hadith/collections.

Tip. Telegram messages have a 4096 character limit. If a search returns very long hadiths, truncate the text field before sending. A quick way is text = text[:800] + "..." if the string is too long.

Deploying the bot

For a bot that runs all day you need a server. Some cheap options:

Make sure your environment variables are set on whatever platform you use. Never commit the .env file to a public repository.

FAQ

What Python library should I use to build a Telegram bot?

Use python-telegram-bot. It is the most popular Python library for the Telegram Bot API. Install it with pip install "python-telegram-bot[job-queue]". Version 20 and above is fully async.

Which hadith collections are available on UmmahAPI?

UmmahAPI provides 10 collections: bukhari, muslim, tirmidhi, abudawud, nasai, ibnmajah, malik, nawawi, qudsi, and dehlawi. You can list them all by calling GET /api/hadith/collections. See the Hadith API page for more detail.

How do I schedule a daily hadith message in a Telegram bot?

python-telegram-bot includes a JobQueue that uses APScheduler. Call app.job_queue.run_daily(callback, time=...) after building your app. Install the [job-queue] extra when you run pip install or the JobQueue will not be available.

Do I need an API key to use UmmahAPI?

No key is required to get started. The free tier allows 5,000 requests per 15 minutes. For unlimited requests, register for a free API key at ummahapi.com/register. Pass the key in an x-api-key header with each request.

Build more with UmmahAPI

UmmahAPI gives you free access to hadiths, Quran data, prayer times, duas, and more from a single base URL.

Read the docs