因此,虽然我们都知道整个复制和粘贴别人的代码,并且它神奇地工作了,但在弄清楚该代码实际如何工作和运行时,它失去了一些上下文和理解。
我正在与 Discord.py Rewrite 合作,以及一段名为 Reaction Light 的代码为了创建a bot允许在我的 Discord Server 中 self 分配角色。该机器人 100% 正常运行并按预期工作。现在,我更改了他们的代码中的一些内容,因此我的方法位于不同的位置并从不同的区域调用。
这是我感到困惑的地方:
我有一个名为 isadmin()
的方法,只要需要完成检查以确定发出命令的用户是否是管理员,就会调用该方法。管理员角色在 .env 文件中定义,我使用 dotenv 模块检索该文件。非常简单的东西。 (我稍后会重写这一部分,并希望将所有管理角色 ID 放入一个文件中并从那里获取它们。)但是我对此方法的第三个参数到底做什么感到困惑。 msg=False
每当我为此编写齿轮时,我都会调用此方法,而不将“msg”参数传递给它,如下所示:
# 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()
监听器方法中,它传递 msg
参数,然后执行一些与 ping 命令无关但与 self 的功能相关的代码-分配机器人的角色部分。
# 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
参数,并且如果它已经在检查用户是否是监听器中的管理员,我是否必须检查再次在实际命令本身中?是不是有点多余?
这是 helpers.py 中的 isadmin()
方法文件
# 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.message
,因为 ctx.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 重写 + react 灯代码感到困惑 - 需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60535601/