Answer the question
In order to leave comments, you need to log in
Why does the bot start with the error sqlite3.OperationalError: near "bazaa": syntax error?
When I write hello to the bot, he writes to me "Hi! Your name has been added to the database" and then the sqlite3.OperationalError: near "bazaa": syntax error is displayed in vs code, please help me solve this problem here is the code itself:
import telebot
import random
import telegram
from telebot import types
import sqlite3
from sqlite3 import Error
from time import 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('тут токен')
conn = sqlite3.connect('C:\\Users\\User\\Desktop\\bazaa.db', check_same_thread=False)
cursor = conn.cursor()
def db_table_val(user_id: int, user_name: str, username: str):
cursor.execute('INSERT OR IGNORE bazaa (user_id, user_name, username) VALUES (?, ?, ?)', (user_id, user_name, username))
conn.commit()
@bot.message_handler(content_types=['text'])
def get_text_messages(message):
if message.text.lower() == 'привет':
bot.send_message(message.chat.id, 'Привет! Ваше имя добавлено в базу данных!')
us_id = message.from_user.id
us_name = message.from_user.first_name
username = message.from_user.last_name
db_table_val(user_id=us_id, user_name=us_name, username=username)
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);'''
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) 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.chat.id, f'Привет {m.from_user.first_name}!\nСкинь пожалуйста этого бота друзьям, знакомым чтобы наш бот был все популярнее и популярнее, также не скупись и задонать разработчику копеечку на QIWI `` ведь он старается :)\nHello {m.from_user.first_name}!\nPlease send this bot to your friends, acquaintances so that our bot becomes more and more popular, also do not be stingy and give the developer a pretty penny on QIWI `` because he is trying :)', parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=markup)
bot.send_message(m.chat.id, 'Нажми: \nФакт для получения интересного факта\nHit:\nFact to get an interesting fact', reply_markup=markup )
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.message_handler(content_types=["text"])
def aga (m, res=False):
if m.text.strip() == 'Факт ' :
answer = random.choice(facts)
bot.send_message(m.chat.id, answer)
elif m.text.strip() == 'Fact ' :
answer = random.choice(thinks)
bot.send_message(m.chat.id, answer)
else:
bot.send_sticker(m.chat.id, "CAACAgIAAxkBAAED_MJiFTLamvbOIQ-aExZo7e3KsVXR3AACkAEAAjDUnRFKhubiCfmrSSME")
bot.send_message(m.chat.id, f"\n{m.from_user.first_name} я тебя не понимаю.\nЧтобы получить факт нажми на кнопку 'факт '\n{m.from_user.first_name} I don't understand you.\nTo get a fact click on the 'fact ' button")
bot.delete_webhook()
bot.polling(none_stop=True, timeout=123)
<code>
Answer the question
In order to leave comments, you need to log in
1) Paste the code in "Insert Source Code".
2) Give a full traceback.
3) Change the Hindu code
f'INSERT INTO USERS (user_id, username, first_name, last_name) VALUES ({user}, "{username}", "{first_name}", "{last_name}", "{ctime()}");'
to adequate.
In the code, porridge. On the one hand, you seem to know about placeholders, but not the SQL syntax:
cursor.execute('INSERT OR IGNORE bazaa (user_id, user_name, username) VALUES (?, ?, ?)', (user_id, user_name, username))
INSERT INTO USERS (user_id, username, first_name, last_name) VALUES ({user}, "{username}", "{first_name}", "{last_name}", "{ctime()}");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question