N
N
newbie632021-06-24 22:23:12
Python
newbie63, 2021-06-24 22:23:12

How can aiogram bot get number from sqlite database?

In the database, each user has a number. I wrote a code on aiogram, but the bot gives out the same number (each user has his own number). How to make the bot match the user ID and ID from the database and send the number of this particular user

from aiogram import Bot, types
from aiogram.types import ChatActions
import asyncio
import logging
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from config import TOKEN
import sqlite3

class SQLither:

    def __init__(self, database) -> object:
        self.conn = sqlite3.connect(database)
        self.c = self.conn.cursor()

    def exists_user(self, user_id):
        return bool(self.c.execute("SELECT * FROM users WHERE user_id=?", (user_id,)).fetchone())

    def add_to_db(self, user_id, first_name, last_name, username):
        self.c.execute("INSERT INTO users(user_id, first_name, last_name, username) VALUES(?,?,?,?,?)", (user_id, first_name, last_name, username, number))
        self.conn.commit()

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
db = SQLither("db.db")


@dp.message_handler(commands=['start'])
async def process_hi1_command(message: types.Message):
    user_id = message.from_user.id
    first_name = message.from_user.first_name
    last_name = message.from_user.last_name
    username = message.from_user.username
    if not db.exists_user(user_id):
        db.add_to_db(user_id, first_name, last_name, username)
    await message.answer('Добро пожаловать!')


@dp.message_handler(commands=['number'])
async def number(message: types.Message):
    conn = sqlite3.connect('db.db')
    cur = conn.cursor()
    cur.execute(f"SELECT * FROM users WHERE user_id")
    result = cur.fetchall()
    user_id = message.from_user.id
    await bot.send_message(message.from_user.id, f'Ваше число: = {[list(result[0])[5]][0]}')


if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2021-06-25
@newbie63

In the exists_user function, the query for selecting a specific user (using WHERE) is just correctly composed.
Similarly, the query in the number function should be composed. In its current form, that query selects everyone in a row.
To pass the user number itself to the command, you need to get it from the parameters:

async def number(message: types.Message):
    num = message.get_args()

U
UberPool, 2021-06-25
@UberPool

What number are we talking about?
You write telegram_id, if you need to write something else just add an entry.
Based on your architecture example:

user_id, first_name, last_name, username, <ваше число>
.
And then just display this number to the user by matching the telegram_id in the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question