Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Telegram ChatGPT Bot

A Telegram bot that uses ChatGPT as a backend with topic restrictions, rate limiting, and content ingestion capabilities.

Features

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

Prerequisites

Setup Instructions

1. Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot and follow the instructions
  3. Choose a name and username for your bot
  4. Copy the bot token you receive

2. Get OpenAI API Key

  1. Go to OpenAI Platform
  2. Sign up or log in
  3. Navigate to API Keys section
  4. Create a new API key and copy it

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment Variables

Create a .env file in the project directory:

cp .env.example .env

Edit .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"

5. Run the Bot

python telegram_bot.py

Usage

Commands

  • /start - Show welcome message and instructions
  • /status - Check remaining questions and ingested items
  • /ingest - Ingest content for context
    • Reply to a message with /ingest to ingest that message
    • Use /ingest https://example.com/article to ingest from URL
  • /clear - Clear all ingested content

Example Conversations

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...

Customization

Edit the ChatBotConfig class in telegram_bot.py to customize:

Change the Topic

ALLOWED_TOPIC = "Python programming"  # Change to your topic

Adjust Rate Limits

MAX_QUESTIONS_PER_USER = 10  # Questions allowed
RATE_LIMIT_WINDOW_HOURS = 24  # Time window in hours

Change OpenAI Model

MODEL = "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)

Customize System Prompt

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 code

Advanced Features

Database Storage

For 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 logic

Enhanced URL Scraping

The basic URL fetching has limitations. For better results:

  1. For Twitter/X posts: Use the official Twitter API
  2. For general web pages: Use BeautifulSoup or newspaper3k
pip install beautifulsoup4 newspaper3k

Webhook Deployment

For 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"
)

Deployment Options

Local Machine

python telegram_bot.py

Cloud Platforms

Heroku:

  1. Create a Procfile: worker: python telegram_bot.py
  2. Deploy using Git
  3. Set environment variables in Heroku dashboard

Railway/Render:

  1. Connect your GitHub repository
  2. Set environment variables
  3. 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"]

Troubleshooting

Bot doesn't respond

  • Check that environment variables are set correctly
  • Verify bot token with BotFather
  • Check console for error messages

Rate limit not working

  • Ensure server time is correct
  • Consider using a database for persistent storage

OpenAI errors

  • Check API key is valid
  • Verify you have credits in your OpenAI account
  • Check rate limits on OpenAI dashboard

URL ingestion fails

  • Twitter/X requires API access (not available via simple scraping)
  • Some websites block automated requests
  • Consider using official APIs when available

Security Considerations

  1. Never commit .env file - Add it to .gitignore
  2. Use environment variables for sensitive data
  3. Implement user authentication if needed for private bots
  4. Monitor API usage to avoid unexpected costs
  5. Validate URLs before fetching to prevent SSRF attacks

Cost Estimation

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

License

MIT License - feel free to modify and use as needed.

Support

For issues or questions:

  1. Check the troubleshooting section
  2. Review OpenAI and python-telegram-bot documentation
  3. Open an issue on GitHub (if hosted)

Contributing

Contributions are welcome! Areas for improvement:

  • Database integration
  • Better URL scraping
  • Multi-language support
  • Conversation history
  • Admin panel
  • Analytics dashboard

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages