python.py代码中print()中不存在的变量

uemypmqf  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(371)

因此,我尝试创建一个不和谐机器人,我编写了以下代码:

import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

然后vscode告诉我:

f'{client.user} is connected to the following guild:\n'
UnboundLocalError: local variable 'guild' referenced before assignment

idk在哪里找到了“guild”变量,请帮我删除这个错误!

3yhwsihp

3yhwsihp1#

问题很可能是,行会可能没有定义。例如:
这样做有效:

for my_var in [0, 1]:
    pass

print(my_var)

这会产生一个名称错误,因为从未定义过我的\u var。

for my_var in []:
    pass

print(my_var)

你需要为公会设置一个默认值(你可以通过 guild=None 或者将print语句放入for循环中。

btqmn9zl

btqmn9zl2#

有点大的评论。
我把你的密码改了一点。因为厄洛尔是未知的。这段代码至少可以帮助您识别错误导入操作系统

import discord
import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    print(client.guilds) # try to print number of child of client.guilds. I think they are Zero
    for guild in client.guilds:
        if guild.name == GUILD:
            break # This break does not gurantee guild is initalized
    # safety check to make code showing proper error
    if guild is not None:
        print(dir(guild))
        print(
            f'{client.user} is connected to the following guild:\n'
            f'{guild.name}(id: {guild.id})'
        )

client.run(TOKEN)

相关问题