R
R
Radiss2020-11-21 01:29:00
Python
Radiss, 2020-11-21 01:29:00

Error with telegram bot and sqlite3 - why can't it find the table?

The database with the subscriptions table has been created, but when you run the /subscribe or /unsubscribe command in the console:

spoiler


sqlite3.OperationalError: no such table: subscriptions
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-136' coro=<Dispatcher._process_polling_updates() done, defined at /home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py:380> exception=OperationalError('no such table: subscriptions')>
Traceback (most recent call last):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 388, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 225, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 246, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "bot.py", line 39, in unsubscribe
    if(not db.subscriber_exists(message.from_user.id)):
  File "/home/user/Home/ASITES/python/ddghbot/sqlighter.py", line 18, in subscriber_exists
    result = self.cursor.execute('SELECT * FROM `subscriptions` WHERE `user_id` = ?', (user_id,)).fetchall()
sqlite3.OperationalError: no such table: subscriptions
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-139' coro=<Dispatcher._process_polling_updates() done, defined at /home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py:380> exception=OperationalError('no such table: subscriptions')>
Traceback (most recent call last):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 388, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 225, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 246, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "bot.py", line 39, in unsubscribe
    if(not db.subscriber_exists(message.from_user.id)):
  File "/home/user/Home/ASITES/python/ddghbot/sqlighter.py", line 18, in subscriber_exists
    result = self.cursor.execute('SELECT * FROM `subscriptions` WHERE `user_id` = ?', (user_id,)).fetchall()
sqlite3.OperationalError: no such table: subscriptions
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-192' coro=<Dispatcher._process_polling_updates() done, defined at /home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py:380> exception=OperationalError('no such table: subscriptions')>
Traceback (most recent call last):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 388, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 225, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 246, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/user/Home/ASITES/python/ddghbot/venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "bot.py", line 27, in subscribe
    if(not db.subscriber_exists(message.from_user.id)):
  File "/home/user/Home/ASITES/python/ddghbot/sqlighter.py", line 18, in subscriber_exists
    result = self.cursor.execute('SELECT * FROM `subscriptions` WHERE `user_id` = ?', (user_id,)).fetchall()
sqlite3.OperationalError: no such table: subscriptions



bot.py

spoiler

import config
import logging
import asyncio
from datetime import datetime

from aiogram import Bot, Dispatcher, executor, types
from sqlighter import SQLighter

# инициализируем бота
bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot)

# инициализируем соединение с БД
db = SQLighter('db.db')

# Команда активации подписки
@dp.message_handler(commands=['subscribe'])
async def subscribe(message: types.Message):
  if(not db.subscriber_exists(message.from_user.id)):
    # если юзера нет в базе, добавляем его
    db.add_subscriber(message.from_user.id)
  else:
    # если он уже есть, то просто обновляем ему статус подписки
    db.update_subscription(message.from_user.id, True)
  
  await message.answer("Вы успешно подписались на рассылку!\nЖдите, скоро выйдут новые обзоры и вы узнаете о них первыми =)")

# Команда отписки
@dp.message_handler(commands=['unsubscribe'])
async def unsubscribe(message: types.Message):
  if(not db.subscriber_exists(message.from_user.id)):
    # если юзера нет в базе, добавляем его с неактивной подпиской (запоминаем)
    db.add_subscriber(message.from_user.id, False)
    await message.answer("Вы итак не подписаны.")
  else:
    # если он уже есть, то просто обновляем ему статус подписки
    db.update_subscription(message.from_user.id, False)
    await message.answer("Вы успешно отписаны от рассылки.")

      sg.update_lastkey(nfo['id'])

# запускаем лонг поллинг
if __name__ == '__main__':
#	dp.loop.create_task(scheduled(10)) # пока что оставим 10 секунд (в качестве теста)
  executor.start_polling(dp, skip_updates=True)



sqlighter.py

spoiler
import sqlite3

class SQLighter:

    def __init__(self, database):
        """Подключаемся к БД и сохраняем курсор соединения"""
        self.connection = sqlite3.connect(database)
        self.cursor = self.connection.cursor()

    def get_subscriptions(self, status = True):
        """Получаем всех активных подписчиков бота"""
        with self.connection:
            return self.cursor.execute("SELECT * FROM `subscriptions` WHERE `status` = ?", (status,)).fetchall()

    def subscriber_exists(self, user_id):
        """Проверяем, есть ли уже юзер в базе"""
        with self.connection:
            result = self.cursor.execute('SELECT * FROM `subscriptions` WHERE `user_id` = ?', (user_id,)).fetchall()
            return bool(len(result))

    def add_subscriber(self, user_id, status = True):
        """Добавляем нового подписчика"""
        with self.connection:
            return self.cursor.execute("INSERT INTO `subscriptions` (`user_id`, `status`) VALUES(?,?)", (user_id,status))

    def update_subscription(self, user_id, status):
        """Обновляем статус подписки пользователя"""
        with self.connection:
            return self.cursor.execute("UPDATE `subscriptions` SET `status` = ? WHERE `user_id` = ?", (status, user_id))

    def close(self):
        """Закрываем соединение с БД"""
        self.connection.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artur Boyun, 2020-11-21
@arturboyun

No, not created.
Try to write a function to check the existence of such a table, also write a function to create tables, and add a check to the __init__ function in the sqlighter.py file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question