@kibernetshow

Ошибка многопоточности в телеграмме боте при использовании sqlite3?

Мой код

from telebot import types
import telebot, sqlite3
bot = telebot.TeleBot("Токен")
reghelper = telebot.types.ReplyKeyboardMarkup(True)
reghelper.row("Регистрация")
con = sqlite3.connect("test.db")


pname = ""
print("Bot started")
@bot.message_handler(commands=["start"])
def start_message(message):
    bot.send_message(message.chat.id, "Привет, зарегистрируйся", reply_markup = reghelper)

@bot.message_handler(content_types = ["text"])
def get_text_messages(message):
    if message.text.lower() == "регистрация" or message.text.lower() == "Нет":
        bot.send_message(message.from_user.id, "Введите ваше имя: ", reply_markup = reghelper)
        bot.register_next_step_handler(message, get_name)

def get_name(message):
    global pname
    pname = message.text
    if message.text.lower() != "назад":
        with con:
            cur = con.cursor()
            cur.execute("SELECT * FROM userListBD")
            a = 0
            while True:
                row = cur.fetchone()
                if row == None:
                    break
                if row[0] == pname:
                    bot.send_message(message.from_user.id, "Вы есть в базе.", reply_markup = reghelper)
                else:
                    bot.send_message(message.from_user.id, "Увы, вас нет в базе.", reply_markup = reghelper)

    else:
        bot.send_message(message.from_user.id, "Вернулись назад", reply_markup = reghelper)

@bot.callback_query_handler(func = lambda call: True)
def callback_worker(call):
    if call.data == "yes":
        bot.edit_message_text(chat_id = call.message.chat.id, message_id = call.message.message_id, text = "Отлично", parse_mode = "Markdown")
    elif call.data == "no":
        bot.delete_message(call.message.chat.id, call.message.message_id)
        bot.send_message(call.message.chat.id, """Нажмите на кнопку "Регистрация".""", reply_markup = reghelper)
bot.polling(none_stop = True, interval = 0)


Ошибка

Bot started
2019-09-28 21:53:34,879 (util.py:65 WorkerThread2) ERROR - TeleBot: "ProgrammingError occurred, args=('SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 7040 and this is thread id 7076',)
Traceback (most recent call last):
  File "otherTest.py", line 36, in get_name
    cur = con.cursor()
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 7040 and this is thread id 7076

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python35\lib\site-packages\telebot\util.py", line 59, in run
    task(*args, **kwargs)
  File "otherTest.py", line 46, in get_name
    bot.send_message(message.from_user.id, "Увы, вас нет в базе.", reply_markup = vkHelperBtn)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 7040 and this is thread id 7076
"
Traceback (most recent call last):
  File "otherTest.py", line 36, in get_name
    cur = con.cursor()
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 7040 and this is thread id 7076

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "otherTest.py", line 58, in <module>
    bot.polling(none_stop = True, interval = 0)
  File "C:\Python35\lib\site-packages\telebot\__init__.py", line 389, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:\Python35\lib\site-packages\telebot\__init__.py", line 413, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Python35\lib\site-packages\telebot\util.py", line 108, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:\Python35\lib\site-packages\six.py", line 693, in reraise
    raise value
  File "C:\Python35\lib\site-packages\telebot\util.py", line 59, in run
    task(*args, **kwargs)
  File "otherTest.py", line 46, in get_name
    bot.send_message(message.from_user.id, "Увы, вас нет в базе.", reply_markup = vkHelperBtn)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 7040 and this is thread id 7076

  • Вопрос задан
  • 274 просмотра
Решения вопроса 1
sergey-gornostaev
@sergey-gornostaev Куратор тега Python
Седой и строгий
Не стоит одно соединение таскать по разным потокам, у каждого потока должно быть своё. Да и использовать глобальные переменные - это само по себе плохо, а в многопоточном коде тем более.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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