Progressively develop a Telegram bot from basic joke delivery to a community-driven platform with AI integration.
1
Phase 1: Hardcoded Jokes
Initial Telegram bot with static joke list for API testing
2
Phase 2: AI-Generated Jokes
Integration with Yandex AI API for dynamic joke generation
3
Phase 3: User-Generated Content
Database integration with voting and approval system
Phase 1: Hardcoded Jokes
Initial implementation testing Telegram Bot API with static content.
# app.py — Teacher-Only Telegram Joke Botfrom telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import random
# 🔑 REPLACE WITH REAL TOKEN FROM @BotFather
BOT_TOKEN = "7864875699:AAEWf6ff1DYNzPvW6Dbn7D2W5aavg9KPhgY"# --- COPY STUDENT JOKES HERE BEFORE CLASS ---
JOKE_LIST = [
"Why did the robot go to school? To recharge his brain! 🔋",
"Knock knock!\\nWho's there?\\nBoo!\\nBoo who?\\nDon't cry! 😂",
"Why don't eggs tell jokes? They'd crack each other up! 🥚",
"What do you call a penguin in the desert? Lost! 🐧",
# Add student jokes here
]
async defstart(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("🤖 Hi! I'm your Joke Bot!\\nType /joke for a funny joke in English! 😄")
async defsend_joke(update: Update, context: ContextTypes.DEFAULT_TYPE):
joke = random.choice(JOKE_LIST)
await update.message.reply_text(joke)
defmain():
print("🚀 Starting Joke Bot...")
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("joke", send_joke))
print("✅ Bot is running! Press Ctrl+C to stop.")
app.run_polling()
if __name__ == "__main__":
main()
Initial Implementation Features
Basic Telegram Bot API integration
Static list of pre-approved jokes
/start and /joke command handlers
Random joke selection from hardcoded list
Phase 2: AI-Generated Jokes
Integration with Yandex AI API for dynamic content generation.
import os
import random
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
import requests
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
YANDEX_API_URL = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion'
YANDEX_FOLDER_ID = os.getenv('YANDEX_FOLDER_ID')
YANDEX_API_KEY = os.getenv('YANDEX_API_KEY')
# Store conversation history per user
user_histories = {}
async defstart(update: Update, context):
# Check if Yandex credentials are configuredifnot YANDEX_API_KEY or YANDEX_API_KEY == 'your_yandex_api_key_here'or \\
not YANDEX_FOLDER_ID or YANDEX_FOLDER_ID == 'your_yandex_folder_id_here':
await update.message.reply_text(
"⚠️ Bot not properly configured!\\n\\n""Please set up your Yandex Cloud credentials in the .env file:\\n""- YANDEX_API_KEY\\n""- YANDEX_FOLDER_ID\\n\\n""Check the README for setup instructions."
)
returnawait update.message.reply_text("Hi! I'm a joke bot powered by Yandex AI. Send me any message and I'll respond with a joke! 😄")
async defhandle_message(update: Update, context):
"""Handle incoming messages and respond using Yandex AI"""
user_id = update.effective_user.id
user_message = update.message.text
# Initialize user history if not existsif user_id notin user_histories:
user_histories[user_id] = [
{
"role": "system",
"text": "You are a funny chatbot that responds with jokes. Keep responses concise and family-friendly."
}
]
# Add user message to history
user_histories[user_id].append({
"role": "user",
"text": user_message
})
try:
headers = {
"Authorization": f"Api-Key {YANDEX_API_KEY}",
"Content-Type": "application/json"
}
data = {
"modelUri": f"gpt://{YANDEX_FOLDER_ID}/yandexgpt-lite",
"completionOptions": {
"stream": False,
"temperature": 0.8,
"maxTokens": 100
},
"messages": user_histories[user_id]
}
response = requests.post(YANDEX_API_URL, headers=headers, json=data, timeout=10)
response.raise_for_status()
ai_response = response.json()["result"]["alternatives"][0]["message"]["text"]
# Add AI response to history
user_histories[user_id].append({
"role": "assistant",
"text": ai_response
})
await update.message.reply_text(ai_response)
except Exception as e:
await update.message.reply_text(f"❌ Failed to generate response: {str(e)}")
defmain():
"""Start the bot."""
BOT_TOKEN = os.getenv("BOT_TOKEN", "7864875699:AAEWf6ff1DYNzPvW6Dbn7D2W5aavg9KPhgY")
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("Bot is running... Press Ctrl+C to stop.")
app.run_polling()
if __name__ == "__main__":
main()
Phase 3: User-Generated Content
Final implementation with database, voting, and approval system.
import sqlite3
import random
from datetime import datetime
# Calculate average user sentiment for a jokedefget_user_sentiment_for_joke(db, joke_id):
cursor = db.execute(''' SELECT CASE WHEN AVG(CASE WHEN user_sentiment = 'up' THEN 1 WHEN user_sentiment = 'down' THEN -1 ELSE 0 END) > 0.1 THEN '👍 Up' WHEN AVG(CASE WHEN user_sentiment = 'up' THEN 1 WHEN user_sentiment = 'down' THEN -1 ELSE 0 END) < -0.1 THEN '👎 Down' ELSE '😐 Neutral' END as avg_sentiment, COUNT(*) as total_votes FROM user_sentiments WHERE joke_id = ? ''', (joke_id,))
result = cursor.fetchone()
avg_sentiment, total_votes = result if result else ('😐 Neutral', 0)
return avg_sentiment, total_votes
# Record user sentiment for a jokedefadd_user_sentiment(db, joke_id, user_choice):
try:
db.execute(''' INSERT INTO user_sentiments (joke_id, user_sentiment) VALUES (?, ?) ''', (joke_id, user_choice))
db.commit()
returnTrueexcept Exception as e:
print(f"❌ Error saving sentiment: {e}")
returnFalse
Final System Features
SQLite database for joke storage
User-generated content with administrative approval
Community voting system (👍, 👎, 😐)
Sentiment analysis and rating calculation
Command-line interface for joke management
System Demonstration
Final System - Joke Retrieval
$ python joke_bot.py
🤖 JOKE BOT
==============================
1. Get random joke
2. Add new joke
3. Quit
Your choice: 1
🤣 Why don't scientists trust atoms?
Because they make up everything!
👤 Contributor: ScienceFan42
👥 Community Rating: 👍 Up (24 votes)
🎯 Rate this joke: 👍 (U)p, 👎 (D)own, or (N)eutral?
Your choice (u/d/n): u
✅ Your rating (👍 Up) recorded!
Technology Stack
Python 3.9+
Telegram Bot API
SQLite Database
Yandex AI API
Command-Line Interface
Modular Architecture
📱
Telegram Platform
Bot API for user interaction and message handling
🤖
AI Integration
Yandex GPT for dynamic content generation during Phase 2
🗄️
Database System
SQLite for storing jokes, votes, and user preferences
Learning Outcomes
💻
API Integration
Telegram Bot API and Yandex AI API implementation
🗄️
Database Design
SQLite database architecture and management
🔄
Iterative Development
Progressive implementation from basic to complex features
Development Methodology
The project followed an iterative approach: starting with a simple working prototype (hardcoded jokes), adding AI capabilities, and finally implementing a full database system with user-generated content and community features.
Future Applications
🏫
Educational Platform
Adapt voting system for feedback collection in school communication platforms.
📊
Survey System
Repurpose database structure for structured feedback collection.
🤖
Hybrid AI System
Combine user-generated content with AI moderation and enhancement.
Scalable Architecture
The modular design allows adaptation for various educational and institutional applications beyond joke sharing.
Conclusion
This project demonstrates practical application of Python programming, API integration, and database design through a progressive development approach.
🎯
Technical Implementation
Three-phase development from simple to complex system
📈
Iterative Approach
Progressive feature addition and system refinement
👨🏫
Educational Framework
Practical learning in API usage and database management
Thank You
Questions about the Telegram Joke Bot development process?