Files
ai6-m3/jokes_bot/v3.0/Joke Bot_ Telegram & SQLite Integration.html
2026-01-30 11:47:06 +03:00

684 lines
25 KiB
HTML

<!DOCTYPE html>
<!-- saved from url=(0069)file:///Users/home/Downloads/deepseek_html_20260120_a4e55e%20(1).html -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke Bot Upgrade: SQLite Database Integration</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
}
body {
background: #f8fafc;
height: 100vh;
display: flex;
flex-direction: column;
padding: 20px;
}
.container {
flex: 1;
display: flex;
flex-direction: column;
max-width: 1000px;
margin: 0 auto;
width: 100%;
height: calc(100vh - 80px);
}
.slide {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.08);
padding: 30px 40px;
margin: 10px 0;
display: none;
flex: 1;
overflow-y: auto;
}
.slide.active {
display: flex;
flex-direction: column;
}
h1 {
color: #2c3e50;
font-size: 2.2rem;
margin-bottom: 20px;
text-align: center;
}
h2 {
color: #2c3e50;
font-size: 1.8rem;
margin-bottom: 15px;
}
h3 {
color: #2c3e50;
font-size: 1.4rem;
margin: 20px 0 10px 0;
}
p {
font-size: 1.1rem;
line-height: 1.6;
margin: 15px 0;
color: #4a5568;
}
.code-block {
background: #1a202c;
color: #e2e8f0;
padding: 20px;
border-radius: 6px;
margin: 15px 0;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.95rem;
line-height: 1.5;
white-space: pre-wrap;
overflow-wrap: break-word;
}
.instruction-block {
background: #fff8e1;
border-left: 4px solid #ffb300;
padding: 15px;
margin: 15px 0;
border-radius: 0 4px 4px 0;
}
.step-number {
display: inline-block;
background: #ffb300;
color: white;
width: 24px;
height: 24px;
border-radius: 50%;
text-align: center;
line-height: 24px;
margin-right: 10px;
font-weight: bold;
}
.nav-container {
display: flex;
justify-content: space-between;
margin-top: 25px;
padding-top: 20px;
border-top: 1px solid #e2e8f0;
}
.nav-btn {
background: #4299e1;
color: white;
border: none;
padding: 10px 25px;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
min-width: 100px;
}
.nav-btn:hover {
background: #3182ce;
}
.nav-btn:disabled {
background: #cbd5e0;
cursor: not-allowed;
}
.slide-counter {
text-align: center;
color: #718096;
font-size: 0.9rem;
margin-bottom: 10px;
font-weight: 500;
}
.terminal {
background: #2d3748;
color: #e2e8f0;
padding: 15px;
border-radius: 6px;
font-family: 'Consolas', monospace;
margin: 10px 0;
font-size: 0.9rem;
line-height: 1.5;
white-space: pre-wrap;
}
.db-structure {
background: #f0fff4;
border: 1px solid #9ae6b4;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
font-family: 'Consolas', monospace;
font-size: 0.9rem;
color: #2f855a;
line-height: 1.5;
white-space: pre-wrap;
}
ul {
margin: 15px 0 15px 20px;
color: #4a5568;
}
li {
margin: 8px 0;
}
code {
background: #edf2f7;
padding: 2px 6px;
border-radius: 3px;
font-family: 'Consolas', monospace;
font-size: 0.9rem;
}
@media (max-width: 768px) {
body {
padding: 10px;
}
.slide {
padding: 20px;
}
h1 {
font-size: 1.8rem;
}
h2 {
font-size: 1.5rem;
}
h3 {
font-size: 1.2rem;
}
}
</style>
</head>
<body>
<div class="slide-counter" id="slide-counter">Slide 3 of 8</div>
<div class="container">
<!-- Slide 1: Title -->
<div class="slide" id="slide1">
<div style="flex: 1; display: flex; flex-direction: column; justify-content: center;">
<h1>Joke Bot Upgrade: SQLite Database</h1>
<p style="font-size: 1.3rem; color: #4a5568;">From Static List to Dynamic Database</p>
<p style="margin-top: 30px; font-size: 1.1rem; color: #718096;">
Transform your simple joke bot into a collaborative joke database
</p>
</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn1">Previous</button>
<button class="nav-btn" id="nextBtn1">Next</button>
</div>
</div>
<!-- Slide 2: Original vs Upgraded Code -->
<div class="slide" id="slide2">
<h2>From Static List to Database</h2>
<p><strong>Original Code (Static List):</strong></p>
<div class="code-block"># 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)</div>
<p><strong>Upgraded Code (SQLite Database):</strong></p>
<div class="code-block"># 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:")</div>
<p><strong>Key Improvements:</strong></p>
<ul>
<li>Static list → Dynamic SQLite database</li>
<li>Hardcoded jokes → User-contributed content</li>
<li>Limited selection → Unlimited joke storage</li>
<li>Teacher-only → Collaborative system</li>
</ul>
<div class="nav-container">
<button class="nav-btn" id="prevBtn2">Previous</button>
<button class="nav-btn" id="nextBtn2">Next</button>
</div>
</div>
<!-- Slide 3: Step-by-Step Guide - Part 1 -->
<div class="slide active" id="slide3">
<h2>Step-by-Step Upgrade Guide - Part 1</h2>
<p>Let's upgrade your Joke Bot one step at a time:</p>
<div class="instruction-block">
<div class="step-number">1</div>
<strong>Remove the old joke list</strong>
<p>Find this line in your original code:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
JOKE_LIST = [
"Why did the robot go to school? To recharge his brain!",
# ... more jokes ...
]</div>
<p>Delete everything from <code>JOKE_LIST = [</code> to the closing <code>]</code> including all jokes.</p>
</div>
<div class="instruction-block">
<div class="step-number">2</div>
<strong>Add SQLite import</strong>
<p>At the VERY TOP of your file, add this line:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
import sqlite3</div>
<p>This should go right after the other imports, like:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import random
import sqlite3 # ← ADD THIS LINE</div>
</div>
<div class="instruction-block">
<div class="step-number">3</div>
<strong>Add waiting dictionary</strong>
<p>Find your <code>BOT_TOKEN</code> line and add this right after it:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
waiting = {} # ← ADD THIS LINE</div>
<p>This dictionary will track users who are typing jokes.</p>
</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn3">Previous</button>
<button class="nav-btn" id="nextBtn3">Next</button>
</div>
</div>
<!-- Slide 4: Step-by-Step Guide - Part 2 -->
<div class="slide" id="slide4">
<h2>Step-by-Step Upgrade Guide - Part 2</h2>
<div class="instruction-block">
<div class="step-number">4</div>
<strong>Update the joke function</strong>
<p>Find your <code>get_random_joke</code> function. DELETE this entire function:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
async def get_random_joke(update: Update, context: ContextTypes.DEFAULT_TYPE):
joke = random.choice(JOKE_LIST)
await update.message.reply_text(joke)</div>
<p>REPLACE it with this new function:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
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.")</div>
</div>
<div class="instruction-block">
<div class="step-number">5</div>
<strong>Add the addjoke function</strong>
<p>Right after your <code>joke</code> function, add this new function:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
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):")</div>
<p>This function starts the process when users type <code>/addjoke</code>.</p>
</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn4">Previous</button>
<button class="nav-btn" id="nextBtn4">Next</button>
</div>
</div>
<!-- Slide 5: Step-by-Step Guide - Part 3 -->
<div class="slide" id="slide5">
<h2>Step-by-Step Upgrade Guide - Part 3</h2>
<div class="instruction-block">
<div class="step-number">6</div>
<strong>Add the text handler function</strong>
<p>Add this function after your <code>addjoke</code> function:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px; margin-bottom: 10px;">
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")</div>
<p>This function catches regular messages and saves jokes to the database.</p>
</div>
<div class="instruction-block">
<div class="step-number">7</div>
<strong>Update the main function</strong>
<p>Find your <code>main()</code> function. Change it from this:</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px; margin-bottom: 10px;">
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()</div>
<p>To this (CHANGE the highlighted lines):</p>
<div class="code-block" style="background: #4a5568; font-size: 0.9rem; padding: 10px;">
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 &amp; ~filters.COMMAND, handle_text)) # ← ADD THIS LINE
print("✅ Bot is running! Press Ctrl+C to stop.")
app.run_polling()</div>
</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn5">Previous</button>
<button class="nav-btn" id="nextBtn5">Next</button>
</div>
</div>
<!-- Slide 6: SQLite Database Implementation -->
<div class="slide" id="slide6">
<h2>SQLite Database Implementation</h2>
<p><strong>Your Code Should Now Include:</strong></p>
<div class="code-block">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")</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn6">Previous</button>
<button class="nav-btn" id="nextBtn6">Next</button>
</div>
</div>
<!-- Slide 7: Database Structure & Commands -->
<div class="slide" id="slide7">
<h2>Database Structure &amp; Bot Commands</h2>
<p><strong>SQLite Database Schema:</strong></p>
<div class="db-structure">-- 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');</div>
<p><strong>Your Bot Now Has These Commands:</strong></p>
<div class="terminal">/start - Start the bot and see commands
/joke - Get a random joke from database
/addjoke - Add your own joke to database</div>
<p><strong>How It Works:</strong></p>
<ul>
<li>When user types <code>/joke</code> → Bot gets random joke from database</li>
<li>When user types <code>/addjoke</code> → Bot waits for their joke</li>
<li>User types their joke → Bot saves it to SQLite database</li>
<li>Everyone can now access that joke with <code>/joke</code></li>
</ul>
<p><strong>Important Note:</strong> The database file <code>jokes.db</code> will be created automatically the first time you run your bot.</p>
<div class="nav-container">
<button class="nav-btn" id="prevBtn7">Previous</button>
<button class="nav-btn" id="nextBtn7">Next</button>
</div>
</div>
<!-- Slide 8: Complete Implementation -->
<div class="slide" id="slide8">
<h2>Complete Implementation Code</h2>
<div class="code-block">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 &amp; ~filters.COMMAND, handle_text))
print("Joke Bot is running with SQLite database support!")
app.run_polling()</div>
<div class="nav-container">
<button class="nav-btn" id="prevBtn8">Previous</button>
<button class="nav-btn" id="nextBtn8">Next</button>
</div>
</div>
</div>
<script>
const totalSlides = 8;
let currentSlide = 1;
function updateSlideCounter() {
document.getElementById('slide-counter').textContent = `Slide ${currentSlide} of ${totalSlides}`;
}
function showSlide(slideNumber) {
for (let i = 1; i <= totalSlides; i++) {
const slide = document.getElementById(`slide${i}`);
if (slide) slide.classList.remove('active');
}
const slideElement = document.getElementById(`slide${slideNumber}`);
if (slideElement) {
slideElement.classList.add('active');
currentSlide = slideNumber;
updateSlideCounter();
updateButtons();
}
}
function updateButtons() {
for (let i = 1; i <= totalSlides; i++) {
const prevBtn = document.getElementById(`prevBtn${i}`);
const nextBtn = document.getElementById(`nextBtn${i}`);
if (prevBtn) prevBtn.disabled = currentSlide === 1;
if (nextBtn) {
nextBtn.textContent = currentSlide === totalSlides ? 'Finish' : 'Next';
}
}
}
for (let i = 1; i <= totalSlides; i++) {
const nextBtn = document.getElementById(`nextBtn${i}`);
const prevBtn = document.getElementById(`prevBtn${i}`);
if (nextBtn) {
nextBtn.addEventListener('click', () => {
if (currentSlide < totalSlides) {
showSlide(currentSlide + 1);
} else {
alert('Congratulations! You have completed the Joke Bot upgrade tutorial. Your bot now has a SQLite database and can accept user-submitted jokes!');
}
});
}
if (prevBtn) {
prevBtn.addEventListener('click', () => {
if (currentSlide > 1) {
showSlide(currentSlide - 1);
}
});
}
}
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight' || e.key === ' ') {
if (currentSlide < totalSlides) showSlide(currentSlide + 1);
} else if (e.key === 'ArrowLeft') {
if (currentSlide > 1) showSlide(currentSlide - 1);
}
});
updateSlideCounter();
updateButtons();
</script>
</body></html>