我正在嘗試撰寫我的幫助命令的斜杠命令版本,并且我想檢查用戶是否可以運行命令。
這是我的代碼:
@app_commands.command(name="help")
async def help(self, interaction: discord.Interaction, input: str = None):
embed = discord.Embed(title="Test")
cmd = self.bot.get_command(input)
ctx: commands.Context = await self.bot.get_context(interaction)
try:
await cmd.can_run(ctx)
embed.add_field(name="Usable by you:", value="Yes")
except commands.CommandError as exc:
embed.add_field(name="Usable by you:", value=f"No:\n{exc}")
await ctx.send(embed=embed)
現在,如果我想檢查正常命令 ( commands.Command),這可以正常作業,但是這不適用于混合命令 ( commands.HybridCommand)。我閱讀了檔案bot.get_context中的內容:
In order for the custom context to be used inside an interaction-based context (such as HybridCommand) then this method must be overridden to return that class.
但是我不確定這到底意味著什么。我如何覆寫它以及我需要回傳什么類?
為了完成,這是我嘗試在 HybridCommand 上使用它時遇到的錯誤:
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: AttributeError: '_MissingSentinel' object has no attribute 'guild'
同樣,當我在普通命令上使用它時,它作業正常。
我將不勝感激任何指標!
編輯:我的意思的一個例子:
@commands.command()
@commands.has_permissions(administrator=True)
async def test1(self, ctx):
print("Test1")
@commands.hybrid_command()
@commands.has_permissions(administrator=True)
async def test2(self, ctx):
print("Test 2")
如果您輸入/help test1,它將正常作業,但在/help test2. 未經許可檢查,它似乎也可以正常作業。
uj5u.com熱心網友回復:
解釋
似乎 discord.py 存在導致此錯誤的錯誤。在_check_can_run混合命令中,它interaction._baton用作命令背景關系來檢查。interaction._baton設定為缺少的哨兵值,因此在discord.py嘗試像常規Context物件一樣使用它時會遇到錯誤。
這可以很簡單地修補,盡管我不確定是否有任何意外的副作用。只需設定interaction._baton為您剛剛獲取的背景關系。我已經用兩個測驗用例對其進行了測驗,它們都有效:
代碼
@bot.tree.command(name="help", guild=discord.Object(id=703732969160048731))
async def help_command(interaction: discord.Interaction, parameter: str = None):
embed = discord.Embed(title="Test")
cmd = bot.get_command(parameter)
ctx: commands.Context = await bot.get_context(interaction)
interaction._baton = ctx # sketchy, but it works
try:
await cmd.can_run(ctx)
embed.add_field(name="Usable by you:", value="Yes")
except commands.CommandError as exc:
embed.add_field(name="Usable by you:", value=f"No:\n{exc}")
await ctx.send(embed=embed)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481934.html
