D
D
dj_igoran2021-10-14 14:43:15
Python
dj_igoran, 2021-10-14 14:43:15

UnboundLocalError: local variable '' referenced before assignment, what should I do?

The bot does not work, with the "/start" command it works until the first user input.

Here is the error:

INFO:aiogram.dispatcher.dispatcher:Start polling.
ERROR:asyncio:Task exception was never retrieved
future: exception=UnboundLocalError("local variable 'signup' referenced before assignment")>
Traceback (most recent call last):
File "C:\Users\zamov\AppData\Local\Programs\ Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 414, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users \zamov\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 236,
return await asyncio.gather(*tasks)
File "C:\Users\zamov\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\zamov\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 257, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\zamov\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "c:\Users\zamov\OneDrive\Desktop\telebot\main.py", line 31, in bot_message
if db.get_singup(message.from_user.id) == "setnickname":
File "c:\Users\zamov\OneDrive\Desktop\telebot\db.py", line 26, in get_singup
return signup
UnboundLocalError: local variable 'signup ' referenced before assignment

db.py code:

import sqlite3

class Database:
    def __init__(self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()

    def add_user(self, user_id):
        with self.connection:
            return self.cursor.execute("INSERT INTO 'users' ('user_id') VALUES (?)", (user_id,))

    def user_exists(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))

    def set_nickname(self, user_id, nickname):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'nickname' = ? WHERE 'user_id' = ?", (nickname, user_id,))

    def get_singup(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'signup' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            for row in result:
               signup = str(row[0])
            return signup

    def set_singup(self, user_id, signup):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'signup' = ? WHERE 'user_id' = ?", (signup, user_id,))

main.py code:

import logging
from aiogram import Bot, Dispatcher, executor, types
import markups as nav
from db import Database

TOKEN = "2091008426:AAFgzkWhLouPSTWs2Yh8hZI0-KEmhaSDcmo"

logging.basicConfig(level=logging.INFO)

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)

db = Database('database.db')

@dp.message_handler(commands=['start'])
async def start(message: types.Message):
    if(not db.user_exists(message.from_user.id)):
        db.add_user(message.from_user.id)
        await bot.send_message(message.from_user.id, "Введите никнейм.")
    else:
        await bot.send_message(message.from_user.id, "Вы уже зарегестрированы.", reply_markup=nav.mainMenu)


@dp.message_handler()
async def bot_message(message: types.Message):
    if message.chat.type == 'private':
        if message.text == 'ПРОФИЛЬ':
            pass

        else:
            if db.get_singup(message.from_user.id) == "setnickname":
                if(len(message.text) > 20):
                    await bot.send_message(message.from_user.id, "Количество символов не должно превышать 20.")
                elif '@' in message.text or '*' in message.text:
                    await bot.send_message(message.from_user.id, "Вы ввели запрещенный символ.")
            else:
                db.set_nickname(message.from_user.id, message.text)
                db.set_singup(message.from_user.id, "done")
                await bot.send_message(message.from_user.id, "Регистрация завершена!", reply_markup=nav.mainMenu)
    else:
        await bot.send_message(message.from_user.id, "Неизвестная команда.", reply_markup=nav.mainMenu)




if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)


Please tell me what to do with this?
(Declaring signup global didn't help)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-14
@dj_igoran

Replace fetchall with fetchone and remove the loop before return signup.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question