@Dmitrij_py

Почему интерпретатор не видит переменную?

Тг бот должен присылать "товары", записанные в sql таблице, но он просто не видит глобальную переменную cur = base.cursor().

Код
import json
import string
from aiogram.contrib.fsm_storage.memory import MemoryStorage
import aiogram
from aiogram import Dispatcher, executor
import logging
import time

from aiogram.dispatcher.filters import Text

from bot_telegram import data_base
from bot_telegram.admin_kb import button_case_admin
from client_kb import kb_client
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup


import sqlite3 as sq

"""                                                     DATA BASE                                                     """
def sql_start():
	global base, cur

	base = sq.connect('Cars-bikes.db')
	cur = base.cursor()
	if base:
		print('Data base connected successfully')
	base.execute('CREATE TABLE IF NOT EXISTS catalog (img TEXT, name TEXT PRIMARY KEY, description TEXT, price TEXT)')
	base.commit()



async def sql_add_command(state):
	async with state.proxy() as data:
		cur.execute('INSERT INTO catalog VALUES (?, ?, ?, ?)', tuple(data.values()))
		base.commit()


async def sql_read(message):
	for ret in cur.execute('SELECT * FROM catalog').fetchall():
		await bot.send_photo(message.from_user.id, ret[0], f'{ret[1]}\nОписание: {ret[2]}\nЦена: {ret[-1]}')

"""                                                                                                                    """











WORD_FILTER_MODE = True  # Turn 'False' if not need to filter mats


class FSMAdmin(StatesGroup):
	photo = State()
	name = State()
	description = State()
	price = State()

ID = None
TOKEN = '5735333111:AAHytpZj8PkVuOm3ntrTJLCeLX6v_akAZWQ'
bot = aiogram.Bot(token=TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot=bot, storage=storage)
main_msg = 'Hi, Я бот который руководит этой группой и отвечает за ваш комфортный доступ к каталогу товаров. ' \
           'Пожалуйста, будьте вежливы и не спамьте.\nI am the bot_telegram that manages this group and is responsible for your ' \
           'comfortable access to the product catalog. Please be polite and don\'t spam. '


async def on_startup(_):
	print('ONLINE')
	data_base.sql_start()




@dp.message_handler(commands=['start', 'help'])
async def start(message):
	logging.info(
		f'{message.from_user.id=}{message.from_user.first_name=}{message.from_user.full_name=}{time.asctime()}')
	try:
		await bot.send_message(message.from_user.id, f'{main_msg}', reply_markup=kb_client)
		await message.delete()
	except:
		await message.reply(
			'Пожалуйста, запустите бота через свои ЛС. \nАктуальная ссылка:\nhttp://t.me/Cars_end_bikes_bot')


@dp.message_handler(commands=['Режим_работы'])
async def work_mode(message):
	await bot.send_message(message.from_user.id, 'Пн - пт с 9:00 до 22:00 / Сб - Вс с 10:00 до 20:00')


@dp.message_handler(commands=['Расположение'])
async def location(message):
	await bot.send_message(message.from_user.id,
	                       'ул. Налибокская, 1 (ТЦ «Караван», 1 этаж),\nул. Свердлова, 11 (ТЦ «Centropol»),\nЛогойский тракт, 37 (ТЦ «Nord City», 1 этаж),\nпр. Дзержинского, 131 (Брилевичи, ст. м. Малиновка).')

@dp.message_handler(commands=['Каталог'])
async def see_catalog(message):
	await sql_read(message)

@dp.message_handler(commands=['admin'], is_chat_admin = True)
async def make_changes_rights(message):
	global ID
	ID = message.from_user.id
	await message.delete()
	await bot.send_message(message.from_user.id, 'Права администратора подтверждены', reply_markup=button_case_admin)



# Начало диалога загрузки нового товара
@dp.message_handler(commands=['Загрузить...'], state=None)
async def cm_start(message):
	if message.from_user.id == ID:
		await FSMAdmin.photo.set()
		await message.reply('Загрузи фото')

@dp.message_handler(state='*', commands='отмена')
@dp.message_handler(Text(equals = 'отмена', ignore_case=True), state='*')
async def cancel_handler(message, state: FSMContext):
	current_state = await state.get_state()
	if current_state is None:
		return
	await state.finish()
	await message.reply('OK')

@dp.message_handler(content_types=['photo'], state=FSMAdmin.photo)
async def load_photo(message, state: FSMContext):

	async with state.proxy() as data:
		data['photo'] = message.photo[0].file_id
	await FSMAdmin.next()
	await message.reply('Теперь введи название')


@dp.message_handler(state=FSMAdmin.name)
async def load_name(message, state: FSMContext):
	async with state.proxy() as data:
		data['name'] = message.text
	await FSMAdmin.next()
	await message.reply('Введи описание')


@dp.message_handler(state=FSMAdmin.description)
async def load_description(message, state: FSMContext):
	async with state.proxy() as data:
		data['description'] = message.text
	await FSMAdmin.next()
	await message.reply('Укажи цену')


@dp.message_handler(state=FSMAdmin.price)
async def load_price(message, state: FSMContext):
	try:
		async with state.proxy() as data:
			data['price'] = float(message.text)
	except:
		await message.reply('Введено некоректное значение цены. Попробуйте еще раз.')

	async with state.proxy() as data:
		await data_base.sql_add_command(state)
		await message.reply(str(data))
	await state.finish()


if WORD_FILTER_MODE == True:

	@dp.message_handler()
	async def filter(message):
		if {i.lower().translate(str.maketrans('', '', string.punctuation)) for i in message.text.split(' ')} \
				.intersection(set(json.load(open('C:\\Users\\user\\PycharmProjects\\Bot\\cenz1.json', 'r')))) != set():
			await message.reply('Маты запрещены!\nMats are prohibited!')
			await message.delete()
if __name__ == '__main__':
	executor.start_polling(dp, skip_updates=True, on_startup=on_startup)

Ошибка
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=NameError("name 'cursor' is not defined")>
Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "C:\Users\user\PycharmProjects\Bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\user\PycharmProjects\Bot\bot_telegram\bot.py", line 105, in see_catalog
    await catalog(message)
  File "C:\Users\user\PycharmProjects\Bot\bot_telegram\bot.py", line 40, in catalog
    for ret in cursor.execute('SELECT * FROM catalog').fetchall():
NameError: name 'cursor' is not defined
  • Вопрос задан
  • 131 просмотр
Пригласить эксперта
Ваш ответ на вопрос

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

Похожие вопросы