所以,尽管我们都知道了全部复制并粘贴了别人的代码,并且神奇地实现了它,但是在弄清楚该代码的实际工作方式和功能时,它失去了一些上下文和理解。
我正在使用Discord.py Rewrite和一大堆名为Reaction Light的代码来创建a bot,该代码允许在我的Discord Server中进行自我分配。该机器人具有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命令无关但与漫游器的自我分配角色部分的功能有关的代码。
# 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
命令调用。
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
答案 0 :(得分:2)
说实话,我不确定为什么会这样。如果您有权访问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)
我认为它更清洁,使用/理解起来也容易得多。