I'm getting this error below when My Message is something like 003-UG-CSE-2023 or 123-PG-CSE-2024
Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\ACER\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "C:\Users\ACER\Desktop\pika bot\pika.py", line 52, in on_message if cont: UnboundLocalError: local variable 'cont' referenced before assignment
import os
import discord
import discord.ext.commands as commands
import dotenv
import random
dotenv.load_dotenv()
bot = commands.Bot(command_prefix='$')
@bot.event
async def on_ready():
print('I am online')
print(bot.user.name)
print(bot.user.id)
print('-----')
@bot.event
async def on_message(message):
member = message.author
role = discord.utils.get(member.guild.roles, id="899279907216031744")
splits = message.content.split("-")
# it's not in the wanted format
if len(splits) != 4:
# return or something else
cont = False
# check if first is a number within range <1, 999>
try:
if int(splits[0]) <= 0 and int(splits[0]) >= 1000:
cont = True
except ValueError:
cont = False
# check if second is one of the options
if splits[1] not in ["UG", "PG", "D"]:
cont = False
# check if third is one of the options
if splits[2] not in ["CSAI","CSE","ECAI","ECE","IT","MAE","EEE","CE","PD","AE","CH","CE","EE","ME","ED","MV","ER","QT","RAS","AI","CS","CP","BE","CHE","CHEM","CG","CC","VLSI","EV","DES"]:
cont = False
# check if fourth is a number from range <2022 ...>
try:
if int(splits[3]) <= 2022:
cont = False
except ValueError:
cont = False
# it fits all the criteria
if cont:
await discord.Member.add_roles(member, role)
bot.run(os.getenv('TOKEN'))
Please lemme know if you found the mistake so I can fix the issue
CodePudding user response:
Try/except blocks have their own scope for variables. To use variables set inside a try/except block, you need to add an 'else' or 'finally' after except (where else runs only if there is no error and finally runs either way)
CodePudding user response:
The Error definitely shows, that the problem is laying on "if cont:", I would try to add cont to a global.
@bot.event
async def on_message(message):
global cont #Added cont to global
member = message.author
role = discord.utils.get(member.guild.roles, id="899279907216031744")
splits = message.content.split("-")