1

I'm at my wits end trying to debug and solve this error. Basically, I have a variable (maxID) that thinks its not initialized when it very clearly is both before and after checking. It only seems to do this in my add method, as it is just fine in all the other methods I've tried (I've left a debug print in my code that I can confirm DOES work in the ping method that proves that maxID has been initialized). Relevant code below:

import discord
import asyncio
from discord.ext import commands

class Quote:
    def __init__(self, id, msg):
        self.id = id
        self.msg = msg

bot = commands.Bot(command_prefix = '-')

q = open("maxID.txt","r")
maxID = int(q.read())
q.close()

print(maxID)

temp = [0 for x in range(len(quotes))]
for i in range(0, len(quotes)):
    temp[i] = Quote(ids[i],quotes[i])
quotes = temp

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.event
async def on_message(message):
    await bot.process_commands(message)

@bot.command(pass_context=True)
async def ping(ctx):    
    await ctx.channel.send('Pong!')
    print(maxID)

@bot.command(pass_context=True)
async def add(ctx, *, arg):
    quotes.append(Quote(maxID, arg))
    maxID = maxID + 1
    await ctx.channel.send('Added Quote #' + str(len(quotes)))

Side note: Any time at all that maxID is mentioned in the above quote, outside of add, I can confirm works just fine with no issues that I can see.

The exact error I get from the add method:

Ignoring exception in command add:
Traceback (most recent call last):
  File "C:\Users\Acemcbean\AppData\Roaming\Python\Python36\site-packages\discord\ext\commands\core.py", line 62, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "C:\IzunaBot\run.py", line 51, in add
    quotes.append(Quote(maxID, arg))
UnboundLocalError: local variable 'maxID' referenced before assignment
hopethatsacleanwet
  • 418
  • 1
  • 4
  • 13
Acemcbean
  • 336
  • 1
  • 3
  • 7

1 Answers1

0

The maxID in the add command is being interpreted as a local variable instead of a global variable.

This thread (and specifically this answer) might be useful to you.

You could update your add command to include a line defining maxID as a nonlocal variable as a fix:

@bot.command(pass_context=True)
async def add(ctx, *, arg):
    nonlocal maxID
    quotes.append(Quote(maxID, arg))
    maxID = maxID + 1
    await ctx.channel.send('Added Quote #' + str(len(quotes)))
hopethatsacleanwet
  • 418
  • 1
  • 4
  • 13
  • I tried this but it doesn't seem to work. I am getting the following error from it: *SyntaxError: no binding for nonlocal 'maxID' found* – Acemcbean Mar 17 '18 at 07:18
  • @Acemcbean Try `global maxID` instead – Patrick Haugh Mar 17 '18 at 13:18
  • Yeah I did last night after sending my message and it worked, but I went right to bed after (it was about 4am) Thank you for your help though, I do appreciate it – Acemcbean Mar 17 '18 at 16:42