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.
π‘ 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 Tβ¦
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.
π‘ 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
- Python 3.7+ - Main programming language
- pyTelegramBotAPI - Telegram Bot API wrapper
- OpenAI Python SDK - For GPT-5 integration
- SQLite3 - Lightweight database for user data and transactions
- python-dotenv - Environment variable management
- 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 β
βββββββββββββββββββ
π§ 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
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()
Key Design Decisions:
- Unified balance: Single
requestsfield 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
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)
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"
)
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)}")
π― 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"
)
π 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
- Environment Variables: Never commit
.envfiles - Input Validation: Check message length and content
- Rate Limiting: Prevent abuse (can add)
- Payment Verification: Always verify payment webhooks
- Database Locks: Thread-safe operations
- 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
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
π 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
- Telegram Stars are game-changing: No payment processor hassle
- SQLite is underrated: Perfect for MVPs
- User experience matters: Clear pricing, instant feedback
- Start simple: Can always add features later
- 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!