Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
4.2 kB
11
Indexable
Never
import sqlite3
from telegram import Update, ForceReply
from telegram.ext import CommandHandler, MessageHandler, Application, ContextTypes, ConversationHandler
from credits import bot_token

class Database:
    def __init__(self, db_name):
        self.conn = sqlite3.connect(db_name)
        self.cursor = self.conn.cursor()
        self.create_table()

    def create_table(self):
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS users
                               (id INTEGER PRIMARY KEY AUTOINCREMENT,
                                name TEXT NOT NULL,
                                age INTEGER NOT NULL)''')
        self.conn.commit()

    def insert_data(self, name, age):
        self.cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', (name, age))
        self.conn.commit()

    def fetch_data(self):
        self.cursor.execute('''SELECT * FROM users''')
        rows = self.cursor.fetchall()

        print("Данные из базы данных:")
        for row in rows:
            print(f"ID: {row[0]}, Имя: {row[1]}, Возраст: {row[2]}")

        return rows

    def close_connection(self):
        self.conn.close()

class MyBot(Database):
    def __init__(self, bot_token):
        self.application = Application.builder().token(bot_token).build()
        self.db_name = "db/example.db"
        super().__init__(self.db_name)
        self.DB_SOURCE = 1

        self.application.add_handler(CommandHandler("fetchone", self.fetch_one_data))
        self.application.add_handler(CommandHandler("fetchall", self.fetch_all_data))
        self.application.add_handler(CommandHandler("fetchmany", self.fetch_many_data))

        self.application.add_handler(CommandHandler("start", self.start))
        self.application.add_handler(CommandHandler("help", self.help))
        conv_handler = ConversationHandler(
            entry_points=[CommandHandler("registration", self.registration)],
            states={
                self.DB_SOURCE: [MessageHandler(filters.TEXT, self.db_source)],
            }, fallbacks=[])
        self.application.add_handler(conv_handler)

        self.application.run_polling(allowed_updates=Update.ALL_TYPES)

    async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        user = update.effective_user
        await update.message.reply_html(
            f"Hi {user.mention_html()}! Please register with the bot. To do this, send the /registration command",
            reply_markup=ForceReply(selective=True),
        )

    async def help(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        await update.message.reply_text(text="Это простой бот. Он может отвечать на текстовые сообщения.")

    async def registration(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        await update.message.reply_text(text="Please, write your name and age:")
        return self.DB_SOURCE

    async def db_source(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        text = update.message.text
        text = text.split()
        self.insert_data(text[0], text[1])
        self.fetch_data()

        await update.message.reply_text(text="Write to DB")
        return ConversationHandler.END

    async def fetch_one_data(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        result = self.fetchone_data()
        await update.message.reply_text(text=result)

    async def fetch_all_data(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        result = self.fetchall_data()
        formatted_result = "\n".join([f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}" for row in result])
        await update.message.reply_text(text=formatted_result)

    async def fetch_many_data(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        result = self.fetchmany_data()
        formatted_result = "\n".join([f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}" for row in result])
        await update.message.reply_text(text=formatted_result)

    def __del__(self):
        self.close_connection()

if __name__ == "__main__":
    bot = MyBot(bot_token=bot_token)
Leave a Comment