@amogusnikovv

Как сделать так чтобы когда юзер пишет /start, его имя и айди попадали в базу данных, на библиотеке telebot?

Как сделать так чтобы когда юзер пишет /start, его имя и айди попадали в базу данных, на библиотеке telebot? Весь интернет облазил рабочих способов не нашел, если надо вот мой код:
import telebot
import random
import telegram
from telebot import types
import sqlite3
import time
from sqlite3 import Cursor, Error
from time import sleep, ctime
f = open('C:\\Users\\User\\Desktop\\bot\\fact(ru).txt', 'r', encoding='UTF-8')
facts = f.read().split('\n')
f.close()
f = open('C:\\Users\\User\\Desktop\\bot\\fact(en).txt', 'r', encoding='UTF-8')
thinks  = f.read().split('\n')
f.close()

bot = telebot.TeleBot('тут мой токен')
def post_sql_query(sql_query):
    with sqlite3.connect('C:\\Users\\User\\Desktop\\bot\\baza.db') as connection:
        cursor = connection.cursor()
        try:
            cursor.execute(sql_query)
        except Error:
            pass
        result = cursor.fetchall()
        return result
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)
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 )
create_tables()
@bot.message_handler(commands=['start'])
def start(m, res=False):
        register_user(m.from_user.id, m.from_user.username, m.from_user.first_name, m.from_user.last_name)
        markup=types.ReplyKeyboardMarkup(resize_keyboard=True)
        item1=types.KeyboardButton("Факт ")
        item2=types.KeyboardButton('Fact ')
        markup.add(item1)
        markup.add(item2)
        bot.send_sticker(m.chat.id, "CAACAgIAAxkBAAED_MBiFTEZAmR9KYkIJ27QNkNOf6EyEAACoAEAAjDUnRGDNNeGcpfWEyME", reply_markup=markup)
        bot.send_message(m.from_user.id, f'Привет {m.from_user.first_name}!\nНажми: \nФакт  для получения интересного факта\nHello {m.from_user.first_name}!\nHit:\nFact  to get an interesting fact',  reply_markup=markup )
        bot.send_sticker(m.chat.id, "CAACAgIAAxkBAAED_WliFf2as0gsHVuB9w4a4_z25ts_RAACpQEAAjDUnRGcG4MfBBqxeSME")
        bot.send_message(m.chat.id, 'Задонать разработчику на QIWI `` ведь он старается :)\nTo give the developer a hard time on QIWI `` because he is trying :)', parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=markup)
        @bot.message_handler(content_types=["text"])
        def handle_text(message, res=False):
                if message.text.strip() == 'Факт ' :
                        answer = random.choice(facts)
                        bot.send_sticker(message.chat.id, "CAACAgIAAxkBAAED_WtiFgZVixTQY8Q0A30rvgHa3FoorAACqQEAAjDUnRH4SPNAzJPf4iME")
                        bot.send_message(message.chat.id, answer)
                elif message.text.strip() == 'Fact ' :
                        answer = random.choice(thinks)
                        bot.send_sticker(message.chat.id, "CAACAgIAAxkBAAED_MtiFTbQPqqHNatcl6LD_kOm1c2bdwAClwEAAjDUnRHgxA0IjYYYhyME")
                        bot.send_message(message.chat.id, answer)

                else:
                        bot.send_sticker(message.chat.id, "CAACAgIAAxkBAAED_MJiFTLamvbOIQ-aExZo7e3KsVXR3AACkAEAAjDUnRFKhubiCfmrSSME")
                        bot.send_message(message.from_user.id, "\nЧто?\nЧтобы получить факт нажми на кнопку 'факт '\nWhat?\nTo get a fact click on the 'fact ' button")

bot.delete_webhook()




bot.polling(none_stop=True, timeout=123)
  • Вопрос задан
  • 276 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы