A Telegram bot that integrates with CustomGPT.ai to provide AI-powered responses using your custom knowledge base.
More information on GitHub - https://github.com/Poll-The-People/customgpt-integrations
Get your CustomGPT.ai RAG API key here, needed to use this integration.
Features
- AI-Powered Responses: Uses CustomGPT.ai's API to answer questions from your knowledge base
- Conversation Management: Maintains context within chat sessions
- Rate Limiting: Built-in daily (100) and per-minute (5) message limits
- Starter Questions: Interactive buttons with example queries
- Usage Statistics: Track your daily usage with
/stats - Session Management: 30-minute conversation timeout with auto-cleanup
- Security: SSL certificate handling and secure API communication
Quick Start
Prerequisites
- Python 3.8+
- Telegram Bot Token (from @BotFather)
- CustomGPT.ai API Key and Project ID
- SSL certificates (handled automatically with certifi)
Installation
-
Clone the repository:
cd Telegram-Bot/ -
Install dependencies:
pip install -r requirements.txt -
Set up environment variables: Create a
.envfile:TELEGRAM_BOT_TOKEN=your_bot_token_here CUSTOMGPT_API_KEY=your_api_key_here CUSTOMGPT_PROJECT_ID=your_project_id_here # Optional configuration DAILY_LIMIT=100 MINUTE_LIMIT=5 SESSION_TIMEOUT_MINUTES=30
Running the Bot
Local Development (Polling Mode)
python bot.pyThis runs the bot in polling mode - perfect for development and testing.
Bot Commands
/start- Welcome message with example question buttons/help- Show available commands and tips/examples- Display example questions you can ask/stats- View your usage statistics/clear- Clear conversation history and start fresh
Deployment Options
Option 1: Vercel (Webhook Mode) - Free
Best for: Simple bots with quick responses
Pros:
- Completely free
- Auto-scaling
- HTTPS included
- Easy deployment
Cons:
- 10-second timeout limit
- No persistent storage
- Cold starts
- No rate limiting
Vercel Setup Instructions
Prerequisites
- Telegram Bot Token (from @BotFather)
- CustomGPT API Key and Project ID
- Vercel account (free at vercel.com)
- Git installed locally
Deployment Steps
Option A: Deploy via Vercel CLI
# Install Vercel CLI
npm i -g vercel
# Login to Vercel
vercel login
# Navigate to vercel-bot directory
cd vercel-bot
# Deploy (follow prompts)
vercel
# Set environment variables
vercel env add TELEGRAM_BOT_TOKEN production
vercel env add CUSTOMGPT_API_KEY production
vercel env add CUSTOMGPT_PROJECT_ID production
# Redeploy to apply env vars
vercel --prodOption B: Deploy via GitHub
- Push code to GitHub repository
- Connect repository to Vercel
- Add environment variables in Vercel dashboard
- Deploy
Set Telegram Webhook
After deployment, set your bot's webhook:
import requests
BOT_TOKEN = "your_bot_token_here"
WEBHOOK_URL = "https://your-project.vercel.app/api/webhook"
response = requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
json={"url": WEBHOOK_URL}
)
print(response.json())Or use curl:
curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url": "https://your-project.vercel.app/api/webhook"}'Test Your Bot
- Open Telegram and search for your bot
- Send
/startto begin - Ask any question!
Vercel Limitations
10-Second Timeout
Vercel serverless functions have a 10-second execution timeout on the free tier. This means:
- Each webhook request (Telegram message) must complete within 10 seconds
- This includes: receiving message → calling CustomGPT API → sending response
- If CustomGPT takes too long to respond, the function will timeout
- The bot uses 8-second timeouts for API calls to stay within limits
Other Limitations
- No persistent storage: Sessions reset on cold starts
- No rate limiting: Each request is independent
- Cold starts: First message after inactivity may be slower
- No background tasks: Can't do async processing
How Vercel Deployment Works
- Webhook Reception: Telegram sends updates to
/api/webhook - Message Processing: Bot processes commands or forwards to CustomGPT
- Session Management: Maintains conversation context in memory
- Response Delivery: Sends CustomGPT response back to user
Option 2: Replit (Polling Mode) - Free with Limitations
Best for: Development and testing
Pros:
- Free tier available
- Persistent storage
- Web IDE
- Easy setup
Cons:
- Sleeps after inactivity
- Requires pinging to stay alive
- Limited resources
Replit Setup Instructions
Step 1: Create Replit Account
- Go to replit.com
- Sign up for free
Step 2: Create New Repl
- Click "Create Repl"
- Choose "Python" template
- Name it "customgpt-telegram-bot"
Step 3: Upload Files
Upload these files to your Repl:
bot.pycustomgpt_client.pysimple_cache.pyrequirements.txt
Step 4: Set Environment Variables
- Click "Secrets" (lock icon) in left sidebar
- Add these secrets:
TELEGRAM_BOT_TOKEN= your bot tokenCUSTOMGPT_API_KEY= your API keyCUSTOMGPT_PROJECT_ID= your project ID
Step 5: Update bot.py for Replit
Add this at the top of bot.py:
import os
# Replit uses Secrets instead of .env
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
CUSTOMGPT_API_KEY = os.environ.get('CUSTOMGPT_API_KEY')
CUSTOMGPT_PROJECT_ID = os.environ.get('CUSTOMGPT_PROJECT_ID')Step 6: Create main.py
from bot import main
if __name__ == '__main__':
main()Step 7: Run the Bot
- Click "Run" button
- Your bot should start!
Step 8: Keep Bot Alive (Optional)
For free tier with better uptime:
- Set up UptimeRobot to ping your Repl every 5 minutes
- Your Repl URL:
https://your-repl-name.your-username.repl.co
Replit-Specific Files
.replit
run = "python bot.py"
language = "python3"
[packager]
language = "python3"replit.nix
{ pkgs }: {
deps = [
pkgs.python39
pkgs.python39Packages.pip
];
}Option 3: Railway (Polling/Webhook) - Paid
Best for: Production bots
Pros:
- No timeout limits
- Persistent storage options
- Better performance
- Supports both modes
Cons:
- Requires payment
- More complex setup
Railway Setup
- Install Railway CLI:
npm install -g @railway/cli- Deploy:
railway login
railway init
railway up- Add environment variables in Railway dashboard:
TELEGRAM_BOT_TOKENCUSTOMGPT_API_KEYCUSTOMGPT_PROJECT_ID
Option 4: VPS/Cloud (Any Mode) - Varies
Best for: Full control
Options:
- AWS EC2 (free tier)
- Google Cloud (free tier)
- DigitalOcean ($5/month)
- Any Linux VPS
VPS Setup
- Install Python and dependencies:
sudo apt update
sudo apt install python3 python3-pip
pip3 install -r requirements.txt- Set up environment variables:
export TELEGRAM_BOT_TOKEN="your_token"
export CUSTOMGPT_API_KEY="your_key"
export CUSTOMGPT_PROJECT_ID="your_project_id"- Run bot:
python3 bot.py- Set up systemd service (optional):
[Unit]
Description=Telegram CustomGPT Bot
After=network.target
[Service]
Type=simple
User=youruser
WorkingDirectory=/path/to/bot
Environment="TELEGRAM_BOT_TOKEN=your_token"
Environment="CUSTOMGPT_API_KEY=your_key"
Environment="CUSTOMGPT_PROJECT_ID=your_project_id"
ExecStart=/usr/bin/python3 bot.py
Restart=always
[Install]
WantedBy=multi-user.targetDeployment Comparison
| Platform | Best For | Cost | Persistent Storage | Rate Limiting | Timeout |
|---|---|---|---|---|---|
| Vercel | Simple bots | Free | No | No | 10s |
| Replit | Development | Free* | Yes | Yes | None |
| Railway | Production | Paid | Yes | Yes | None |
| VPS | Full control | Varies | Yes | Yes | None |
*Free tier sleeps after inactivity
Recommended Strategy
- Development/Testing: Replit or local polling
- Simple production: Vercel (if responses are fast)
- Production with complex queries: Railway or VPS
- Enterprise/High traffic: VPS with load balancing
Technical Details
Rate Limiting
- Daily Limit: 100 messages per user
- Minute Limit: 5 messages per minute
- Implementation: In-memory cache (resets on restart)
Session Management
- Timeout: 30 minutes of inactivity
- Storage: In-memory (non-persistent)
- Cleanup: Automatic for expired sessions
API Integration
- CustomGPT API: RESTful API with streaming support
- SSL Handling: Uses certifi for certificate verification
- Error Handling: Graceful degradation with user-friendly messages
Common Issues & Solutions
SSL Certificate Error (macOS)
# Already fixed in customgpt_client.py
import certifi
import ssl
ssl_context = ssl.create_default_context(cafile=certifi.where())Bot Not Responding
- Check bot token is correct
- Verify API credentials
- Ensure bot is running (
python bot.py) - Check network connectivity
For webhook mode:
- Check webhook is set correctly:
https://api.telegram.org/bot<TOKEN>/getWebhookInfo - Verify environment variables in hosting platform dashboard
- Check function logs for errors
Rate Limit Exceeded
- Wait for the timeout period
- Daily limits reset at midnight
- Minute limits reset after 60 seconds
Session Expired
- Use
/clearto start a new conversation - Sessions timeout after 30 minutes of inactivity
Vercel Timeout Errors
- CustomGPT API might be slow - the bot has 8-second timeout
- Consider implementing a "thinking..." message for long responses
- For complex queries, responses might timeout
- Consider using Railway or VPS for complex bots
Sessions Reset Frequently (Vercel/Serverless)
- This is normal behavior on serverless platforms
- Each cold start resets the in-memory session cache
- Consider using a database for persistent sessions (requires paid tier)
Development
Testing Locally
- Use polling mode for easier debugging
- Set lower rate limits for testing
- Use
/statsto monitor usage
Adding Features
- Extend
handle_messageinbot.pyfor new commands - Modify
simple_cache.pyfor persistence - Update
customgpt_client.pyfor API changes
Debugging
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)Security Considerations
- Never commit
.envfile - It contains sensitive credentials - Use environment variables for all secrets
- Implement user allowlisting if needed:
ALLOWED_USERS = [123456789] # Telegram user IDs - Monitor usage with
/statscommand - Set appropriate rate limits based on your needs
Support
CustomGPT Links
- CustomGPT Landing Page
- Live Demo
- CustomGPT Starter Kit
- CustomGPT Integrations
- API Documentation
- Postman Collection
- MCP Documentation
- Office Hours
- YouTube Channel
Video Tutorial
Platform Documentation
- Telegram Bot Documentation: core.telegram.org/bots/api
Troubleshooting
For issues:
- Check the Common Issues section
- Review logs for error messages
- Ensure all prerequisites are met
- Verify API credentials are correct
For CustomGPT API issues, check the resources above. For Telegram Bot API issues, check Telegram Bot Documentation.
License
MIT
Ready to deploy? Choose your hosting option above and follow the deployment guide!
