DEV Community

King Triton
King Triton

Posted on

Building a GPT-5 Telegram Bot with Telegram Stars Monetization

Introduction

Have you ever wanted to provide AI-powered services but found ChatGPT's $20/month subscription too expensive for casual users? I built a Telegram bot that offers GPT-5 access for just 1 Telegram Star per request - making AI accessible and affordable for everyone.

In this article, I'll walk you through building a monetized AI chatbot using Telegram's native payment system (Telegram Stars), OpenAI's GPT-5 API, and Python.

Try the bot: @ChatGPTTlgrmBot

Source code: GitHub Repository

💡 The Idea

The concept is simple but powerful:

  • Pay-per-use model: 1 Telegram Star = 1 AI request
  • No subscriptions: Users only pay for what they use
  • Lower barrier to entry: Much cheaper than $20/month ChatGPT Plus
  • Built-in payments: Telegram Stars integration means no external payment processors

🛠 Tech Stack

Core Technologies

  1. Python 3.7+ - Main programming language
  2. pyTelegramBotAPI - Telegram Bot API wrapper
  3. OpenAI Python SDK - For GPT-5 integration
  4. SQLite3 - Lightweight database for user data and transactions
  5. python-dotenv - Environment variable management
  6. Telegram Stars - Native Telegram payment system

Why These Technologies?

  • Python: Easy to read, fast to develop, excellent libraries
  • SQLite: Zero configuration, perfect for small to medium scale
  • Telegram Stars: No payment processor fees, instant transactions, built into Telegram
  • OpenAI API: Direct access to GPT-5, simple REST API

📐 Architecture Overview

┌─────────────┐
│   User      │
│  (Telegram) │
└──────┬──────┘
       │
       ▼
┌─────────────────┐
│  Telegram Bot   │
│   (bot.py)      │
└────┬──────┬─────┘
     │      │
     │      ▼
     │  ┌──────────────┐
     │  │  OpenAI API  │
     │  │   (GPT-5)    │
     │  └──────────────┘
     │
     ▼
┌─────────────────┐
│  SQLite DB      │
│  - Users        │
│  - Requests     │
│  - Payments     │
└─────────────────┘
Enter fullscreen mode Exit fullscreen mode

🔧 Implementation

1. Project Structure

chatgpt-telegram-bot/
├── bot.py           # Main bot logic
├── functions.py     # OpenAI API integration
├── db.py           # Database management
├── config.py       # Configuration loader
├── .env            # Environment variables
├── requirements.txt
└── README.md
Enter fullscreen mode Exit fullscreen mode

2. Database Schema

# db.py
import sqlite3
from threading import Lock

class DatabaseManager:
    def __init__(self, db_name='bot.db'):
        self.db_name = db_name
        self.lock = Lock()

    def create_tables(self):
        with self.lock, sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()

            # Users table - unified balance
            cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tg_id INTEGER UNIQUE NOT NULL,
                requests INTEGER DEFAULT 3,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )''')

            # Requests history with token metrics
            cursor.execute('''CREATE TABLE IF NOT EXISTS results (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tg_id INTEGER NOT NULL,
                prompt TEXT NOT NULL,
                result TEXT NOT NULL,
                prompt_tokens INTEGER DEFAULT 0,
                completion_tokens INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )''')

            # Payment transactions
            cursor.execute('''CREATE TABLE IF NOT EXISTS payments (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tg_id INTEGER NOT NULL,
                amount INTEGER NOT NULL,
                stars_paid INTEGER NOT NULL,
                payment_id TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )''')

            conn.commit()
Enter fullscreen mode Exit fullscreen mode

Key Design Decisions:

  • Unified balance: Single requests field instead of separate free/paid
  • Token tracking: Monitor API usage for cost optimization
  • Payment audit trail: Complete transaction history

3. OpenAI Integration

# functions.py
from openai import OpenAI
from config import AI_TOKEN

client = OpenAI(api_key=AI_TOKEN)

def get_openai_response(message: str, effort: str = "low", 
                       verbosity: str = "low"):
    """
    Get response from GPT-5 using new Responses API
    Returns: (text, prompt_tokens, completion_tokens)
    """
    try:
        result = client.responses.create(
            model="gpt-5",
            input=message,
            reasoning={"effort": effort},
            text={"verbosity": verbosity},
        )

        text = result.output_text
        usage = getattr(result, "usage", None)
        prompt_tokens = getattr(usage, "input_tokens", 0)
        completion_tokens = getattr(usage, "output_tokens", 0)

        return text, prompt_tokens, completion_tokens

    except Exception as e:
        print(f"Error in OpenAI API: {e}")
        return f"Error: {e}", 0, 0
Enter fullscreen mode Exit fullscreen mode

Why the new Responses API?

  • Simplified interface compared to Chat Completions
  • Built-in reasoning control
  • Better token management

4. Telegram Bot Core

# bot.py
import telebot
from telebot import types

bot = telebot.TeleBot(BOT_TOKEN)

# Dictionary to track users entering custom amounts
waiting_for_amount = {}

@bot.message_handler(commands=['start'])
def send_welcome(message):
    db_manager.add_user(message.chat.id, initial_requests=3)
    requests = db_manager.get_user_requests(message.chat.id)

    welcome_text = (
        "👋 Welcome! I'm your GPT-5 AI assistant.\n\n"
        f"💰 Your balance: {requests} requests\n\n"
        "Send me a message (min 10 characters) and I'll help!\n\n"
        "Commands:\n"
        "/start - start bot\n"
        "/help - get help\n"
        "/balance - check balance\n"
        "/buy - purchase requests\n"
        "/dev - about developer"
    )
    bot.reply_to(message, welcome_text)
Enter fullscreen mode Exit fullscreen mode

5. Telegram Stars Payment Integration

@bot.message_handler(commands=['buy'])
def buy_requests(message):
    markup = types.InlineKeyboardMarkup(row_width=3)

    # Quick purchase options
    buttons = [
        types.InlineKeyboardButton("1 ⭐", callback_data="buy_1"),
        types.InlineKeyboardButton("5 ⭐", callback_data="buy_5"),
        types.InlineKeyboardButton("10 ⭐", callback_data="buy_10"),
        types.InlineKeyboardButton("25 ⭐", callback_data="buy_25"),
        types.InlineKeyboardButton("50 ⭐", callback_data="buy_50"),
        types.InlineKeyboardButton("100 ⭐", callback_data="buy_100"),
    ]
    markup.add(*buttons)

    # Custom amount button
    custom_button = types.InlineKeyboardButton(
        "✏️ Custom Amount", 
        callback_data="buy_custom"
    )
    markup.add(custom_button)

    bot.send_message(
        message.chat.id, 
        "💳 Purchase Requests\n\n1 request = 1 ⭐ Telegram Star", 
        reply_markup=markup
    )

@bot.callback_query_handler(func=lambda call: call.data.startswith('buy_'))
def process_buy(call):
    if call.data == 'buy_custom':
        waiting_for_amount[call.from_user.id] = True
        bot.send_message(
            call.message.chat.id,
            "✏️ Enter amount (1-1000):"
        )
        return

    amount = int(call.data.split('_')[1])
    create_invoice(call.message.chat.id, call.from_user.id, amount)

def create_invoice(chat_id, user_id, amount):
    """Create Telegram Stars invoice"""
    prices = [types.LabeledPrice(
        label=f"{amount} requests", 
        amount=amount
    )]

    bot.send_invoice(
        chat_id=chat_id,
        title=f"Purchase {amount} requests",
        description=f"Buy {amount} requests to GPT-5 bot",
        invoice_payload=f"requests_{amount}_{user_id}",
        provider_token="",  # Empty for Telegram Stars
        currency="XTR",  # Telegram Stars currency code
        prices=prices
    )

@bot.pre_checkout_query_handler(func=lambda query: True)
def process_pre_checkout(pre_checkout_query):
    """Confirm payment"""
    bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)

@bot.message_handler(content_types=['successful_payment'])
def process_successful_payment(message):
    """Handle successful payment"""
    payment_info = message.successful_payment

    # Parse payload
    payload_parts = payment_info.invoice_payload.split('_')
    amount = int(payload_parts[1])
    user_id = int(payload_parts[2])

    # Add requests to user
    db_manager.add_requests(user_id, amount)

    # Save payment record
    db_manager.add_payment(
        tg_id=user_id,
        amount=amount,
        stars_paid=amount,
        payment_id=payment_info.telegram_payment_charge_id
    )

    requests = db_manager.get_user_requests(user_id)
    bot.send_message(
        message.chat.id,
        f"✅ Payment successful!\n\n"
        f"➕ Added: {amount} requests\n"
        f"💰 New balance: {requests} requests"
    )
Enter fullscreen mode Exit fullscreen mode

Telegram Stars Benefits:

  • No external payment processor needed
  • No transaction fees (Telegram takes a small cut)
  • Instant confirmation
  • Built into Telegram app
  • Supports custom amounts

6. Message Processing

@bot.message_handler(func=lambda message: True)
def generate_result(message):
    # Check if waiting for custom amount input
    if message.from_user.id in waiting_for_amount:
        try:
            amount = int(message.text.strip())
            if 1 <= amount <= 1000:
                del waiting_for_amount[message.from_user.id]
                create_invoice(
                    message.chat.id, 
                    message.from_user.id, 
                    amount
                )
            else:
                bot.send_message(
                    message.chat.id,
                    "❌ Invalid amount! Enter 1-1000:"
                )
            return
        except ValueError:
            bot.send_message(
                message.chat.id,
                "❌ Please enter a number:"
            )
            return

    # Validate message length
    if len(message.text) < 10:
        bot.send_message(
            message.chat.id,
            "⚠️ Message too short (min 10 characters)"
        )
        return

    if len(message.text) > 4000:
        bot.send_message(
            message.chat.id,
            "⚠️ Message too long (max 4000 characters)"
        )
        return

    # Check balance
    requests = db_manager.get_user_requests(message.chat.id)
    if requests <= 0:
        bot.send_message(
            message.chat.id,
            "❌ No requests left! Use /buy to purchase more.\n"
            "1 request = 1 ⭐ Telegram Star"
        )
        return

    # Show typing indicator
    bot.send_chat_action(message.chat.id, 'typing')

    try:
        # Get GPT-5 response
        response_text, prompt_tokens, completion_tokens = \
            get_openai_response(message.text)

        # Deduct request
        if db_manager.use_request(message.chat.id):
            # Save to database
            db_manager.add_result(
                message.chat.id,
                message.text,
                response_text,
                prompt_tokens,
                completion_tokens
            )

            # Send response
            bot.reply_to(message, response_text)

            # Show remaining balance
            requests = db_manager.get_user_requests(message.chat.id)
            if requests > 0:
                bot.send_message(
                    message.chat.id,
                    f"💰 Remaining: {requests} requests"
                )
            else:
                bot.send_message(
                    message.chat.id,
                    "❌ No requests left! Use /buy to purchase more."
                )
    except Exception as e:
        bot.reply_to(message, f"❌ Error: {str(e)}")
Enter fullscreen mode Exit fullscreen mode

🎯 Key Features Implemented

1. Flexible Payment System

  • Quick purchase buttons (1, 5, 10, 25, 50, 100 Stars)
  • Custom amount input (1-1000)
  • State management for user input flow

2. User Experience

  • Typing indicator: Shows bot is processing
  • Balance feedback: After each request
  • Clear pricing: 1 Star = 1 Request
  • Free trial: 3 free requests for new users

3. Admin Dashboard

@bot.message_handler(commands=['stats'])
def show_stats(message):
    if message.from_user.id == ADMIN_ID:
        total_users = db_manager.get_total_users()
        total_requests = db_manager.get_total_requests()
        total_revenue = db_manager.get_total_revenue()

        bot.reply_to(
            message,
            f"📊 Bot Statistics:\n\n"
            f"👥 Total users: {total_users}\n"
            f"💬 Total requests: {total_requests}\n"
            f"⭐ Revenue: {total_revenue} Stars"
        )
Enter fullscreen mode Exit fullscreen mode

📊 Performance & Scalability

Current Setup

  • Database: SQLite with threading locks
  • Suitable for: Up to 10,000 users
  • Response time: 2-5 seconds (depends on OpenAI API)

Scaling Considerations

For larger scale, consider:

  • PostgreSQL/MySQL: Better concurrent access
  • Redis: For session management and caching
  • Message Queue: For handling spike loads
  • Load Balancer: Multiple bot instances

💰 Cost Analysis

Running Costs

  • Server: $5-10/month (VPS)
  • OpenAI API: ~$0.03-0.15 per request (GPT-5)
  • Telegram Stars: ~30% commission to Telegram

Pricing Strategy

  • 1 Star ≈ $0.013 (varies by region)
  • Profit margin: ~20-40% after API costs
  • Break-even: ~500 paid requests/month

🔒 Security Best Practices

  1. Environment Variables: Never commit .env files
  2. Input Validation: Check message length and content
  3. Rate Limiting: Prevent abuse (can add)
  4. Payment Verification: Always verify payment webhooks
  5. Database Locks: Thread-safe operations
  6. Error Handling: Graceful failure recovery

🚀 Deployment

Quick Deploy Script

#!/bin/bash

# Clone repository
git clone https://github.com/king-tri-ton/chatgpt-telegram-bot.git
cd chatgpt-telegram-bot

# Install dependencies
pip install -r requirements.txt

# Setup environment
cp .env.example .env
nano .env  # Edit with your tokens

# Run bot
python bot.py
Enter fullscreen mode Exit fullscreen mode

Using systemd (Linux)

[Unit]
Description=GPT-5 Telegram Bot
After=network.target

[Service]
Type=simple
User=youruser
WorkingDirectory=/path/to/bot
ExecStart=/usr/bin/python3 bot.py
Restart=always

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

📈 Future Improvements

  • [ ] Image generation support (DALL-E)
  • [ ] Conversation history/context
  • [ ] Referral system
  • [ ] Subscription plans
  • [ ] Multi-language support
  • [ ] Voice message support
  • [ ] Analytics dashboard
  • [ ] A/B testing for pricing

🎓 Lessons Learned

  1. Telegram Stars are game-changing: No payment processor hassle
  2. SQLite is underrated: Perfect for MVPs
  3. User experience matters: Clear pricing, instant feedback
  4. Start simple: Can always add features later
  5. Monitor costs: OpenAI API costs can add up

🤝 Contributing

The project is open-source under MIT license. Contributions welcome!

Ways to contribute:

  • Report bugs
  • Suggest features
  • Submit pull requests
  • Improve documentation
  • Share feedback

📚 Resources

🎉 Conclusion

Building a monetized AI bot with Telegram Stars is surprisingly straightforward. The combination of:

  • Low entry barrier (1 Star per request)
  • Built-in payments (no Stripe/PayPal)
  • Powerful AI (GPT-5)
  • Simple tech stack (Python + SQLite)

...makes this a viable micro-SaaS project.

The bot is live at @ChatGPTTlgrmBot - try it out!

Full source code: GitHub


Questions? Feedback? Drop a comment below or reach out on Telegram: @king_triton

If you found this helpful, please ⭐ the GitHub repo and share with others!

python #telegram #openai #gpt5 #bot #monetization #telegramstars #ai #chatbot #opensource

Top comments (0)