gpt4 book ai didi

python - 对这个 Discord.py Rewrite + Reaction Light 代码感到困惑 - 需要解释

转载 作者:行者123 更新时间:2023-12-04 10:28:17 27 4
gpt4 key购买 nike

因此,虽然我们都知道整个复制和粘贴其他人的代码,并且神奇地工作,但在弄清楚这段代码的实际工作和功能时,它会失去一些上下文和理解。

我正在使用 Discord.py Rewrite ,以及一段名为 Reaction Light 的代码为了创建 a bot允许在我的 Discord Server 中自我分配角色.该机器人 100% 正常运行并按预期工作。现在,我已经从他们的代码中改变了一些东西,所以我的方法位于不同的位置并从不同的区域调用。

这是我感到困惑的地方:

我有一个名为 isadmin() 的方法每当需要完成检查以确定发出命令的用户是否是管理员时,都会调用此方法。管理员角色在我使用 dotenv 模块检索的 .env 文件中定义。很直接的东西。 (我稍后会重写它的那一部分,并希望将所有管理员角色 id 放入一个文件中并从那里获取它们。)但是我对这个方法的第三个参数究竟做了什么感到困惑。 msg=False
每当我为此编写 cogs 时,我都会直接调用此方法,而无需将“msg”参数传递给它,如下所示:

admin.py

# admin.py
# Simple ping pong command
@commands.command()
async def ping(self, ctx):
if helpers.isadmin(ctx):
print("Running Command from admin.py")
await ctx.send('Pong!')

现在在我的 on_message() listener 方法,它正在传递 msg参数,然后执行一些与 ping 命令无关但与机器人的自分配角色部分的功能相关的代码。

message.py
# message.py
@commands.Cog.listener()
async def on_message(self, message):
if helpers.isadmin(message, msg=True):
# Execute some code here for the self-assigning roles

据我所知,此工作流程的工作方式是这样,我将使用 ping 命令作为示例,该命令由 r.ping 调用。命令。
  • on_message() 监听服务器中发送的所有消息
  • 用户在 channel 发出的 Ping 命令
  • on_message() 听到消息并检查用户是否是管理员,但也传递了 msg论据
  • admin.py 调用 ping 命令然后检查(再次?)用户是否是管理员,如果他/她是,则执行该命令。

  • 所以,我想弄清楚何时或何时不使用这个 msg参数,如果它已经在检查用户是否是监听器中的管理员,我是否必须检查 再次在实际命令本身中?是不是有点多余?

    这是 isadmin() helpers.py 中的方法文件
    # helpers.py
    def isadmin(self, ctx, msg=False):
    # Checks if command author has one of .env admin role IDs
    try:
    check = (
    [role.id for role in ctx.author.roles]
    if msg
    else [role.id for role in ctx.message.author.roles]
    )
    if self.admin_a in check or self.admin_b in check or self.admin_c in check:
    return True
    return False
    except AttributeError:
    # Error raised from 'fake' users, such as webhooks
    return False

    最佳答案

    老实说,我不确定为什么会这样。如果您有权访问 ctx.author您可以访问 ctx.messagectx.author只是那个消息的作者,似乎是多余的。但是我强烈建议您使用 checks为了这。例如我有:

    def is_owner():
    def predicate(ctx):
    return ctx.author.id in ctx.bot.config()["owners"]
    return commands.check(predicate)

    我用它作为装饰器

    # utils/checks/checks.py
    from utils.checks import checks

    @checks.is_owner()
    @commands.group(hidden=True, case_insensitive=True, description="Load a module")
    async def load(self, ctx):
    if not ctx.invoked_subcommand:
    return await ctx.send_help(ctx.command)

    例如你可以有

    def is_admin():
    def predicate(ctx):
    role_id = 123123123123123 # replace this with os.getenv("wherever your admin role is")
    return role_id in [x.id for x in ctx.author.roles]
    return commands.check(predicate)

    在我看来,它更干净,更容易使用/理解。

    关于python - 对这个 Discord.py Rewrite + Reaction Light 代码感到困惑 - 需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60535601/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com