【问题标题】:name 'guild' is not defined名称“公会”未定义
【发布时间】:2020-11-28 01:27:44
【问题描述】:

我正在编写一个机器人来在我的不和谐服务器上查找具有“管理员”角色的用户并打印信息admin用户名)并将所有角色存储在一个列表中peopleWithRole:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="$")
role_name = "Admin"
peopleWithRole = []

@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print("------")
    role = discord.utils.find(
        lambda r: r.name == role_name, guild.roles)
        
    for user in guild.members:
        if role in user.roles:
            peopleWithRole.append(user)

bot.run("My token")

但是,当我运行它时,返回 error 'guild' 未定义。我刚开始使用 discord python 模块。在这种情况下我应该如何使用客户端或bot?。

【问题讨论】:

    标签: python python-3.x discord


    【解决方案1】:
    import discord
    from discord.ext import commands
    
    bot = commands.Bot(command_prefix="$")
    role_name = "Admin"
    peopleWithRole = []
    
    @bot.event
    async def on_ready():
        print("Logged in as")
        print(bot.user.name)
        print("------")
        guild = bot.guilds[0]
    
        role = discord.utils.find(
            lambda r: r.name == role_name, guild.roles)
            
        for user in guild.members:
            if role in user.roles:
                peopleWithRole.append(user)
    
    bot.run("My token")
    

    在您的 find 调用中,您引用了 guild.roles 但从未定义公会。你需要选择公会(我相信公会是bot的成员)

    这是一个相当基本的 Python 调试错误,任何 IDE 都会识别出什么是错误的。我建议您查看一些有关如何调试的教程。

    【讨论】:

    • 有什么可以代替公会的吗?我只是看到其他人在使用它,我只是认为公会只是说服务器的方式。我以为 guild.members 是在谈论服务器的所有成员
    • 它是...如果 guild = discord.Guild 对象实例。现在它是一个未定义的变量。
    • 我正在建立一个测试实例来修复你的代码......但同样,你只需要从你的机器人对象中选择合适的公会。
    • 您能进一步解释一下吗?我创建了一个变量 guild = discord.Guild,但这给了我另一个错误 'property' object is not iterable
    • 是的,只是和一群朋友为我的服务器编写一个机器人。
    猜你喜欢
    • 2022-01-21
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2020-12-24
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多