A Telegram bot that uses ChatGPT as a backend with topic restrictions, rate limiting, and content ingestion capabilities.
✅ Topic Restriction: Only answers questions about a specific topic (customizable) ✅ Rate Limiting: Limits number of questions per user per time period ✅ Content Ingestion: Ingest information from messages or URLs to provide context ✅ User-friendly: Simple commands and status tracking
- Python 3.8 or higher
- A Telegram Bot Token (from @BotFather)
- An OpenAI API Key (from OpenAI Platform)
- Open Telegram and search for @BotFather
- Send
/newbotand follow the instructions - Choose a name and username for your bot
- Copy the bot token you receive
- Go to OpenAI Platform
- Sign up or log in
- Navigate to API Keys section
- Create a new API key and copy it
pip install -r requirements.txtCreate a .env file in the project directory:
cp .env.example .envEdit .env and add your credentials:
TELEGRAM_BOT_TOKEN=your_actual_bot_token
OPENAI_API_KEY=your_actual_openai_key
Alternatively, you can set environment variables directly:
export TELEGRAM_BOT_TOKEN="your_token"
export OPENAI_API_KEY="your_key"python telegram_bot.py/start- Show welcome message and instructions/status- Check remaining questions and ingested items/ingest- Ingest content for context- Reply to a message with
/ingestto ingest that message - Use
/ingest https://example.com/articleto ingest from URL
- Reply to a message with
/clear- Clear all ingested content
Basic Question:
User: How do I create a list in Python?
Bot: In Python, you can create a list using square brackets...
(9 questions remaining)
Ingest Content:
User: /ingest https://example.com/python-guide
Bot: ✅ Content ingested from URL!
Preview: This guide covers Python basics...
User: What does the guide say about loops?
Bot: Based on the ingested content, the guide explains...
Off-topic Question:
User: What's the weather like?
Bot: I can only help with Python programming related questions...
Edit the ChatBotConfig class in telegram_bot.py to customize:
ALLOWED_TOPIC = "Python programming" # Change to your topicMAX_QUESTIONS_PER_USER = 10 # Questions allowed
RATE_LIMIT_WINDOW_HOURS = 24 # Time window in hoursMODEL = "gpt-4o-mini" # Options: gpt-4, gpt-4-turbo, gpt-3.5-turbo, etc.
MAX_TOKENS = 500 # Maximum response length
TEMPERATURE = 0.7 # Creativity (0.0-2.0)Modify the get_system_prompt() method to change how the bot behaves:
def get_system_prompt(self, user_id: int) -> str:
base_prompt = f"""You are an expert in {self.config.ALLOWED_TOPIC}.
[Add your custom instructions here]
"""
# ... rest of the codeFor production use, consider replacing the in-memory storage with a database:
# Instead of dictionaries, use SQLite, PostgreSQL, or MongoDB
# Example with SQLite:
import sqlite3
class RateLimiter:
def __init__(self):
self.conn = sqlite3.connect('bot_data.db')
# Create tables and implement database logicThe basic URL fetching has limitations. For better results:
- For Twitter/X posts: Use the official Twitter API
- For general web pages: Use BeautifulSoup or newspaper3k
pip install beautifulsoup4 newspaper3kFor production deployment, use webhooks instead of polling:
application.run_webhook(
listen="0.0.0.0",
port=8443,
url_path="your_bot_token",
webhook_url="https://yourdomain.com/your_bot_token"
)python telegram_bot.pyHeroku:
- Create a
Procfile:worker: python telegram_bot.py - Deploy using Git
- Set environment variables in Heroku dashboard
Railway/Render:
- Connect your GitHub repository
- Set environment variables
- Deploy automatically
Docker:
Create a Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY telegram_bot.py .
CMD ["python", "telegram_bot.py"]- Check that environment variables are set correctly
- Verify bot token with BotFather
- Check console for error messages
- Ensure server time is correct
- Consider using a database for persistent storage
- Check API key is valid
- Verify you have credits in your OpenAI account
- Check rate limits on OpenAI dashboard
- Twitter/X requires API access (not available via simple scraping)
- Some websites block automated requests
- Consider using official APIs when available
- Never commit
.envfile - Add it to.gitignore - Use environment variables for sensitive data
- Implement user authentication if needed for private bots
- Monitor API usage to avoid unexpected costs
- Validate URLs before fetching to prevent SSRF attacks
OpenAI API Costs (approximate, as of 2024):
- GPT-4: ~$0.03 per 1K tokens input, ~$0.06 per 1K tokens output
- GPT-4o-mini: ~$0.00015 per 1K tokens input, ~$0.0006 per 1K tokens output
With 10 questions per user per day and 500 token responses:
- 100 users/day with GPT-4o-mini: ~$0.30/day
- 100 users/day with GPT-4: ~$30/day
MIT License - feel free to modify and use as needed.
For issues or questions:
- Check the troubleshooting section
- Review OpenAI and python-telegram-bot documentation
- Open an issue on GitHub (if hosted)
Contributions are welcome! Areas for improvement:
- Database integration
- Better URL scraping
- Multi-language support
- Conversation history
- Admin panel
- Analytics dashboard