当我的消息类似于003-UG-CSE-2023或123-PG-CSE-2024时,我收到以下错误
忽略桌面回溯中的异常(最近一次调用):文件"C:\Users\ACER\AppData\Roaming\Python\Python39\site-packages\discord\client.py",第343行,在on_message等待coro(*args,**kwargs)文件"C:\Users\ACER\Desktop\pika bot\pika.py",第52行,在on_message中if cont: UnboundLocalError:赋值前引用的局部变量'cont‘
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'))
如果你发现了错误,请告诉我,这样我就可以解决这个问题了
发布于 2021-10-17 14:13:31
Try/except块有自己的变量作用域。要使用在try/ else块中设置的变量,您需要在except后面添加一个'else‘或' finally’(只有在没有错误的情况下才会运行,并且最终会以这两种方式运行)
发布于 2021-10-17 14:28:41
这个错误明确表明,问题出在"if cont:“上,我会尝试将cont添加到全局变量中。
@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("-")
https://stackoverflow.com/questions/69605118
复制相似问题