python-3.x 通过按钮跳转到另一条消息,同时分配另一个角色

yeotifhr  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(134)

我遇到了一个问题。我创建了一个按钮,可以让用户跳到另一个文本通道中的另一条消息。
用户拥有Role1,只要他按下按钮,他就应该获得角色Role2,并跳转到仅为Role2启用的文本通道。
很遗憾,由于出现以下错误,此操作无法正常工作discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'property' object has no attribute 'get_role'
如何使用户跳转到另一个消息并为其指定新角色?
第一个

klr1opcd

klr1opcd1#

正如我在注解中提到的,你传递给视图的是一个类对象,而不是交互对象。由于add_roles是一个协程,你不能在__init__中传递它,所以你最好在命令本身中传递它。因此,你的视图甚至不需要交互对象。

class Google(discord.ui.View):
    def __init__(self):
        super().__init__()
        # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
        url = f"https://discord.com/channels/<id>"

        # Link buttons cannot be made with the decorator
        # Therefore we have to manually create one.
        # We add the quoted url to the button, and add the button to the view.
        self.add_item(discord.ui.Button(label="Click Here", url=url))

@bot.tree.command(name="google", guild=None)
async def google(interaction: discord.Interaction):
    """Returns a google link for a query"""
    role = interaction.guild.get_role(<id>)
    await interaction.user.add_roles(role)
    await interaction.response.send_message(
        f"Google Result for", view=Google() # If for some reason you need the interaction in your view you can pass it as an argument.
    )

至于如何将其设置为斜杠命令而不是文本命令,需要在bot的命令树(bot.tree.command())中将其设置为命令。
要将slash命令注册为discord,你只需要owner一个sync命令。我的命令是这样的:

@bot.command()
@commands.is_owner()
async def sync(
    ctx: commands.Context[Bot],
    guilds: commands.Greedy[discord.Object],
    spec: Optional[Literal["~"]],
) -> None:
    if not guilds:
        if spec == "~":
            fmt: List[AppCommand] = await ctx.bot.tree.sync(guild=ctx.guild)
        else:
            fmt: List[AppCommand] = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(fmt)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    fmt_i: int = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            fmt_i += 1

    await ctx.send(f"Synced the tree to {fmt_i}/{len(guilds)} guilds.")

运行代码并使用<prefix>sync(不带参数sync as global)命令来同步斜杠命令,然后就可以使用它了。

相关问题