首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我会得到这个错误?机器人应该用ID=899279907216031744来分配角色,当我给出这种类型的输入时,我得到了错误

为什么我会得到这个错误?机器人应该用ID=899279907216031744来分配角色,当我给出这种类型的输入时,我得到了错误
EN

Stack Overflow用户
提问于 2021-10-17 14:07:06
回答 2查看 29关注 0票数 0

当我的消息类似于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‘

代码语言:javascript
运行
复制
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'))

如果你发现了错误,请告诉我,这样我就可以解决这个问题了

EN

回答 2

Stack Overflow用户

发布于 2021-10-17 14:13:31

Try/except块有自己的变量作用域。要使用在try/ else块中设置的变量,您需要在except后面添加一个'else‘或' finally’(只有在没有错误的情况下才会运行,并且最终会以这两种方式运行)

票数 0
EN

Stack Overflow用户

发布于 2021-10-17 14:28:41

这个错误明确表明,问题出在"if cont:“上,我会尝试将cont添加到全局变量中。

代码语言:javascript
运行
复制
@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("-")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69605118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档