Skip to content

djproject-id/TelegramBotTemplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Telegram Bot Template

A production-ready, plugin-based Telegram bot scaffold with XP system, tickets, giveaways, and more.

Python python-telegram-bot PostgreSQL License


Stop building from scratch. This template gives you a battle-tested foundation for any Telegram community bot — with a dynamic plugin system, async PostgreSQL, XP/leveling, DM-based tickets, inline keyboards, and scheduled jobs out of the box.

Getting Started · Features · Architecture · Customization · Contributing


Features

Category What You Get
Plugin Handler System Dynamic register() pattern — add features without touching main.py internals
XP & Leveling Message XP with cooldowns, daily streaks, /rank, /leaderboard
Ticket System Inline button → DM category select → staff relay → /treply/tclose
Giveaways Timed giveaways with inline entry button, auto-end via job queue
Announcements Admin-only /announce with forum topic routing
Event Logging Member join/leave and message edits logged to Logs topic
Welcome System Auto-greet new members + create user in database
Forum Topics Full support for Supergroup forum topics (announcements, games, logs, etc.)
Scheduled Jobs Built-in job_queue integration for timed/recurring events
Inline Keyboards Interactive button menus with CallbackQueryHandler

Architecture

TelegramBotTemplate/
├── main.py                 # Entry point — dynamic handler loading
├── config.py               # All IDs, tokens, XP rates, schedule
├── requirements.txt        # Dependencies
├── .env.example            # Environment template
├── start_bot.sh            # tmux launcher script
│
├── handlers/               # Plugin-style handler modules
│   ├── help.py             # /start + /help commands
│   ├── welcome.py          # New member greeting (ChatMemberHandler)
│   ├── logging_handler.py  # Event logging to Logs topic
│   ├── tickets.py          # DM-based ticket system with staff relay
│   ├── announce.py         # Admin announcements
│   ├── leveling.py         # XP tracking, /rank, /daily, /leaderboard
│   └── giveaway.py         # Timed giveaways with inline buttons
│
├── shared/                 # Platform-agnostic core
│   ├── db.py               # AsyncPG connection pool + queries
│   ├── xp_engine.py        # Level formula + atomic XP operations
│   ├── models.py           # User & XPResult dataclasses
│   └── schema.sql          # PostgreSQL schema (run once)
│
└── data/                   # JSON data files (quiz banks, etc.)

Design Principles

  • Dynamic plugin loading — Each handler implements register(app), loaded at startup
  • Handler group priority — Control execution order (e.g., automod before leveling)
  • Async all the way — asyncpg, python-telegram-bot async, no blocking calls
  • Atomic XP updates — Race-condition safe with PostgreSQL UPDATE ... RETURNING
  • Forum topic routing — Messages go to the right topic automatically
  • Phase-based deployment — Enable handlers incrementally as your community grows

Getting Started

Prerequisites

  • Python 3.10+
  • PostgreSQL 14+
  • A Telegram bot token (get from @BotFather)

1. Clone & Install

git clone https://github.com/djproject-id/TelegramBotTemplate.git
cd TelegramBotTemplate
pip install -r requirements.txt

2. Configure

cp .env.example .env

Edit .env:

BOT_TOKEN=your_telegram_bot_token
DATABASE_URL=postgresql://user:pass@localhost:5432/mybot
GROUP_ID=-1001234567890
TOPIC_GENERAL=2
TOPIC_LOGS=5

3. Setup Database

psql -U your_user -d your_db -f shared/schema.sql

4. Run

python3 main.py

# Or use tmux (survives terminal close):
./start_bot.sh

Customization

Adding a New Handler

  1. Create handlers/my_feature.py:
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

import config


async def my_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello from my feature!")


def register(app: Application):
    app.add_handler(CommandHandler("mycommand", my_command))
  1. Add to main.py:
HANDLER_MODULES = [
    # ... existing handlers
    "handlers.my_feature",
]
  1. Restart the bot. Done.

Handler Patterns

Pattern Example Technique
Simple Command help.py CommandHandler("cmd", fn)
Message Listener leveling.py MessageHandler(filters.TEXT, fn) with group=1
Inline Button giveaway.py InlineKeyboardButton + CallbackQueryHandler
Member Events welcome.py ChatMemberHandler(fn, CHAT_MEMBER)
DM Relay tickets.py filters.ChatType.PRIVATE with group=5
Scheduled Job giveaway.py context.job_queue.run_once() / run_daily()
Admin Check announce.py get_chat_member() → check .status

Handler Group Priority

group=-2  # Anti-raid (before welcome)
group=-1  # Automod (before everything)
group=0   # Default (commands)
group=1   # Leveling (after commands)
group=5   # DM messages (ticket relay)
group=10  # Logging (after everything)

XP Formula

The leveling curve in shared/xp_engine.py:

Level 2:   90 XP    Level 10:  1,980 XP
Level 5:   510 XP   Level 20:  9,660 XP
Level 15:  4,590 XP Level 30:  28,830 XP

Modify calc_xp_for_level() to adjust difficulty.

Cross-Platform Support

The shared/ layer is platform-agnostic — the same database schema, XP engine, and models work with both Telegram and Discord bots. Check out DiscordBotTemplate for the Discord counterpart.

Users can link their Telegram and Discord accounts to share XP across platforms.

Tech Stack

Component Technology
Bot Framework python-telegram-bot 21+
Database PostgreSQL + asyncpg
Environment python-dotenv
Image (optional) Pillow for card generation

Contributing

Contributions are welcome! Here's how:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/amazing-feature
  3. Commit your changes: git commit -m "feat: add amazing feature"
  4. Push to the branch: git push origin feat/amazing-feature
  5. Open a Pull Request

Ideas for Contribution

  • Automod handler (spam detection, link filtering, bad word filter)
  • Anti-raid handler (join rate limiting)
  • Quiz/trivia game handler with scheduled jobs
  • Word scramble game handler
  • Poll/voting handler
  • Account linking handler (Discord ↔ Telegram)
  • Wallet connection handler (Web3)
  • Pillow-based rank card generation
  • Docker + docker-compose setup
  • SQLite fallback for shared/db.py
  • Unit tests for XP engine

License

This project is licensed under the MIT License — see the LICENSE file for details.


Built with python-telegram-bot · Made for the community

If this template saved you time, consider giving it a star!

About

Production-ready plugin-based Telegram bot template with XP system, tickets, giveaways, and more.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors