L
L
Liper2020-04-15 13:39:33
Python
Liper, 2020-04-15 13:39:33

Telegram bot. SQLite3 how to display id?

It is necessary that each time the user presses the /start command, his id is entered into the table if it is not there. At this stage, the ''built-in function id'' is written to the table and this is done every time (only needed if there is no id). What to add and what to remove? I will be grateful if the answer is detailed, I work with sqlite for the first time.

import telebot
import sqlite3
from telebot import types

bot = telebot.TeleBot('1084130875:AAGB5EfXIMo')
id = str(id)

@bot.message_handler(commands=['start'])
def start(message):
  markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  btn1 = types.KeyboardButton('Поиск')
  btn2 = types.KeyboardButton('Связь')
  btn3 = types.KeyboardButton('Добавить')
  markup.add(btn1, btn2, btn3)

  send_message = f"<b>Привет {message.from_user.first_name}!</b>"
  bot.send_message(message.chat.id, send_message, parse_mode='html', reply_markup=markup)

  connection = sqlite3.connect("database.db", check_same_thread = True)
  cursor = connection.cursor()

  cursor.execute("CREATE TABLE IF NOT EXISTS users (id)")
  cursor.execute("INSERT OR IGNORE INTO users (id) VALUES (:id)", {"id": id})

  connection.commit()
  connection.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-04-15
@Liperr

First, make imports:

import sqlite3
from sqlite3 import Error
from time import sleep, ctime

call all SQL statements through a function:
def post_sql_query(sql_query):
    with sqlite3.connect('my.db') as connection:
        cursor = connection.cursor()
        try:
            cursor.execute(sql_query)
        except Error:
            pass
        result = cursor.fetchall()
        return result

then you need to create a table in sqlite and make id user as the primary key (it will determine the uniqueness):
def create_tables():
    users_query = '''CREATE TABLE IF NOT EXISTS USERS 
                        (user_id INTEGER PRIMARY KEY NOT NULL,
                        username TEXT,
                        first_name TEXT,
                        last_name TEXT,
                        reg_date TEXT);'''
    post_sql_query(users_query)

and the user registration function:
def register_user(user, username, first_name, last_name):
    user_check_query = f'SELECT * FROM USERS WHERE user_id = {user};'
    user_check_data = post_sql_query(user_check_query)
    if not user_check_data:
        insert_to_db_query = f'INSERT INTO USERS (user_id, username, first_name,  last_name, reg_date) VALUES ({user}, "{username}", "{first_name}", "{last_name}", "{ctime()}");'
        post_sql_query(insert_to_db_query )

and then call it from the handler:
create_tables()  # вызываем функцию создания таблицы users


@bot.message_handler(commands=['start'])
def start(message):
    register_user(message.from_user.id, message.from_user.username,
                  message.from_user.first_name, message.from_user.last_name)
    bot.send_message(message.from_user.id, f'Welcome  {message.from_user.first_name}' )

I think the principle is clear, then you can work with all the data in this way and yes, the code is so-so, but it should work.
Enough detail?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question