Junior — Middle
How can you connect and use a database within a Telegram bot to store and retrieve information?
sobes.tech AI
Answer from AI
The following steps are usually used to connect and utilize a database in a Telegram bot:
-
Choosing a database: SQLite is often used for simple bots, or PostgreSQL/MySQL for more complex ones.
-
Connecting to the database: through libraries, for example,
sqlite3for SQLite,psycopg2for PostgreSQL, or ORM, such as SQLAlchemy or Django ORM. -
Creating tables and models: defining the data structure to store (e.g., users, states, settings).
-
Using in the bot code: saving or retrieving data from the database during message processing.
Example with SQLite and the sqlite3 library:
import sqlite3
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
# Initialize database
conn = sqlite3.connect('bot.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT)''')
conn.commit()
# Handler for /start command
def start(update: Update, context: CallbackContext):
user = update.effective_user
cursor.execute('INSERT OR IGNORE INTO users (id, username) VALUES (?, ?)', (user.id, user.username))
conn.commit()
update.message.reply_text(f'Hello, {user.first_name}!')
updater = Updater('TOKEN')
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
Thus, the database allows storing user states and information for further bot operation.