Slide 3 of 8

# Joke Bot Upgrade: SQLite Database

From Static List to Dynamic Database

Transform your simple joke bot into a collaborative joke database

## From Static List to Database

Original Code (Static List):

# Static joke list - hardcoded, unchanging 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!", ] async def get_random_joke(update: Update, context: ContextTypes.DEFAULT_TYPE): joke = random.choice(JOKE_LIST) # Limited to pre-defined jokes await update.message.reply_text(joke)

Upgraded Code (SQLite Database):

# Dynamic database - users can add jokes import sqlite3 async def joke(update, context): conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') joke = conn.execute("SELECT text FROM jokes ORDER BY RANDOM() LIMIT 1").fetchone() conn.close() await update.message.reply_text(joke[0] if joke else "No jokes! /addjoke to add one") async def addjoke(update, context): waiting[update.effective_user.id] = True await update.message.reply_text("Type your joke:")

Key Improvements:

- Static list → Dynamic SQLite database
- Hardcoded jokes → User-contributed content
- Limited selection → Unlimited joke storage
- Teacher-only → Collaborative system

## Step-by-Step Upgrade Guide - Part 1

Let's upgrade your Joke Bot one step at a time:

1
Remove the old joke list

Find this line in your original code:

JOKE_LIST = [ "Why did the robot go to school? To recharge his brain!", # ... more jokes ... ]

Delete everything from `JOKE_LIST = [` to the closing `]` including all jokes.

2
Add SQLite import

At the VERY TOP of your file, add this line:

import sqlite3

This should go right after the other imports, like:

from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes import random import sqlite3 # ← ADD THIS LINE
3
Add waiting dictionary

Find your `BOT_TOKEN` line and add this right after it:

BOT_TOKEN = "YOUR_BOT_TOKEN_HERE" waiting = {} # ← ADD THIS LINE

This dictionary will track users who are typing jokes.

## Step-by-Step Upgrade Guide - Part 2

4
Update the joke function

Find your `get_random_joke` function. DELETE this entire function:

async def get_random_joke(update: Update, context: ContextTypes.DEFAULT_TYPE): joke = random.choice(JOKE_LIST) await update.message.reply_text(joke)

REPLACE it with this new function:

async def joke(update, context): """Get random joke from database""" conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') joke = conn.execute("SELECT text FROM jokes ORDER BY RANDOM() LIMIT 1").fetchone() conn.close() if joke: await update.message.reply_text(joke[0]) else: await update.message.reply_text("No jokes in database! Use /addjoke to add one.")
5
Add the addjoke function

Right after your `joke` function, add this new function:

async def addjoke(update, context): """Initiate joke addition process""" waiting[update.effective_user.id] = True await update.message.reply_text("Type your joke (one message):")

This function starts the process when users type `/addjoke`.

## Step-by-Step Upgrade Guide - Part 3

6
Add the text handler function

Add this function after your `addjoke` function:

async def handle_text(update, context): """Handle text messages for joke addition""" user_id = update.effective_user.id if user_id in waiting: # User is adding a joke conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') # Insert joke with user info conn.execute("INSERT INTO jokes VALUES (?, ?, ?)", (update.message.text, user_id, update.effective_user.first_name)) conn.commit() conn.close() # Remove from waiting list del waiting[user_id] await update.message.reply_text("✅ Joke saved to database!") else: # Regular message, not adding joke await update.message.reply_text("Try /start to see available commands")

This function catches regular messages and saves jokes to the database.

7
Update the main function

Find your `main()` function. Change it from this:

def main(): print("🚀 Starting Joke Bot...") app = ApplicationBuilder().token(BOT_TOKEN).build() app.add_handler(CommandHandler("start", start)) app.add_handler(CommandHandler("joke", get_random_joke)) print("✅ Bot is running! Press Ctrl+C to stop.") app.run_polling()

To this (CHANGE the highlighted lines):

def main(): print("🚀 Starting Joke Bot...") app = ApplicationBuilder().token(BOT_TOKEN).build() app.add_handler(CommandHandler("start", start)) app.add_handler(CommandHandler("joke", joke)) # ← CHANGE get_random_joke to joke app.add_handler(CommandHandler("addjoke", addjoke)) # ← ADD THIS LINE app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text)) # ← ADD THIS LINE print("✅ Bot is running! Press Ctrl+C to stop.") app.run_polling()

## SQLite Database Implementation

Your Code Should Now Include:

import sqlite3 # Added at top # ... other imports ... BOT_TOKEN = "YOUR_BOT_TOKEN_HERE" waiting = {} # Added after token # ... start function remains the same ... async def joke(update, context): # New database-powered joke function conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') joke = conn.execute("SELECT text FROM jokes ORDER BY RANDOM() LIMIT 1").fetchone() conn.close() if joke: await update.message.reply_text(joke[0]) else: await update.message.reply_text("No jokes in database! Use /addjoke to add one.") async def addjoke(update, context): # New function for adding jokes waiting[update.effective_user.id] = True await update.message.reply_text("Type your joke (one message):") async def handle_text(update, context): # New function to handle text messages user_id = update.effective_user.id if user_id in waiting: # Save joke to database conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') conn.execute("INSERT INTO jokes VALUES (?, ?, ?)", (update.message.text, user_id, update.effective_user.first_name)) conn.commit() conn.close() del waiting[user_id] await update.message.reply_text("✅ Joke saved to database!") else: await update.message.reply_text("Try /start to see available commands")

## Database Structure & Bot Commands

SQLite Database Schema:

-- jokes.db SQLite database structure CREATE TABLE jokes ( text TEXT, -- The joke text user TEXT, -- User ID for tracking name TEXT -- User's first name ); -- Sample data: INSERT INTO jokes VALUES ('Why did the Python cross the road? To get to the other side!', '12345', 'Alice'), ('What do you call a fake noodle? An impasta!', '67890', 'Bob');

Your Bot Now Has These Commands:

/start - Start the bot and see commands /joke - Get a random joke from database /addjoke - Add your own joke to database

How It Works:

- When user types `/joke` → Bot gets random joke from database
- When user types `/addjoke` → Bot waits for their joke
- User types their joke → Bot saves it to SQLite database
- Everyone can now access that joke with `/joke`

Important Note: The database file `jokes.db` will be created automatically the first time you run your bot.

## Complete Implementation Code

from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, filters import sqlite3 # Replace with your actual bot token TOKEN = "YOUR_BOT_TOKEN_HERE" # Track users who are currently adding jokes waiting = {} async def start(update, context): """Handle /start command""" await update.message.reply_text( "Welcome to Joke Bot!\n\n" "Available commands:\n" "/joke - Get a random joke\n" "/addjoke - Add your own joke to the database" ) async def joke(update, context): """Handle /joke command - get random joke from database""" conn = sqlite3.connect('jokes.db') # Create table if it doesn't exist conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') # Get random joke joke = conn.execute("SELECT text FROM jokes ORDER BY RANDOM() LIMIT 1").fetchone() conn.close() if joke: await update.message.reply_text(joke[0]) else: await update.message.reply_text("No jokes in the database yet! Use /addjoke to add one.") async def addjoke(update, context): """Handle /addjoke command - start joke addition process""" waiting[update.effective_user.id] = True await update.message.reply_text("Type your joke (send it in one message):") async def handle_text(update, context): """Handle all text messages""" user_id = update.effective_user.id if user_id in waiting: # User is adding a joke conn = sqlite3.connect('jokes.db') conn.execute('CREATE TABLE IF NOT EXISTS jokes (text TEXT, user TEXT, name TEXT)') # Save joke with user information conn.execute( "INSERT INTO jokes VALUES (?, ?, ?)", (update.message.text, user_id, update.effective_user.first_name) ) conn.commit() conn.close() # Remove user from waiting list del waiting[user_id] await update.message.reply_text("Joke saved to the database! Others can now see it with /joke") else: # Regular message (not adding joke) await update.message.reply_text("I don't understand that. Try /start to see available commands.") # Main bot setup app = Application.builder().token(TOKEN).build() # Add command handlers app.add_handler(CommandHandler("start", start)) app.add_handler(CommandHandler("joke", joke)) app.add_handler(CommandHandler("addjoke", addjoke)) # Add text message handler (for joke input) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text)) print("Joke Bot is running with SQLite database support!") app.run_polling()