我正在为订单制作一个Discord bot。我需要做一个角色给予按钮列表,并添加按钮到第一个消息与命令后,我尝试了2天,但我不能添加按钮,只编辑第一条消息
我的代码是:class RolButton(Button):
def __init__(self, rol_name):
global a
a = role_name
super().__init__(label=rol_name, style=ButtonStyle.green)
async def callback(self, interaction):
author = interaction.user
role = discord.utils.get(author.guild.roles, name=a)
if role in author.roles:
await author.remove_roles(role)
await interaction.response.send_message(f"you dropped {role} role", ephemeral=True)
else:
await author.add_roles(role)
await interaction.response.send_message(f"You take {role} role", ephemeral=True)
@Bot.command()
async def role(ctx, *args):
args = str(args).replace("(", "").replace(")", "").replace("', '", " ").replace("'", "")
await ctx.channel.purge(limit=1)
button = RolButton(args)
view = MyView()
guild = ctx.guild
await guild.create_role(name=args)
view.add_item(button)
embed = Embed(
title="Take roles",
description="Click buttons you want"
)
await ctx.send(embed=embed, view=view)
@Bot.command()
async def rolekle(ctx, *args):
args = str(args).replace("(", "").replace(")", "").replace("', '", " ").replace("'", "")
await ctx.channel.purge(limit=1)
button = RolButton(args)
view = MyView()
guild = ctx.guild
await guild.create_role(name=args)
view.add_item(button)
async for message in ctx.channel.history(limit=1):
await message.edit(view=view)
如何在命令后添加按钮?
如果您想在消息中添加一个按钮,并希望保留已经存在的按钮,则需要重用现有视图或使用相同的组件创建一个新视图:
class RolButton(Button):
def __init__(self, rol_name):
super().__init__(label=rol_name, style=ButtonStyle.green)
async def callback(self, interaction):
author = interaction.user
role = discord.utils.get(author.guild.roles, name=self.label)
if role in author.roles:
await author.remove_roles(role)
await interaction.response.send_message(f"you dropped {role} role", ephemeral=True)
else:
await author.add_roles(role)
await interaction.response.send_message(f"You take {role} role", ephemeral=True)
@bot.command()
async def rolekle(ctx, *args):
# args is a list of arguments, do not convert it to string, this is very ugly
guild = ctx.guild
new_role = await guild.create_role(name=args[0])
# delete command message
await ctx.message.delete()
view = MyView()
async for message in ctx.channel.history(limit=1):
for row in message.components:
for button in row.children:
view.add_item(RolButton(button.label))
view.add_item(RolButton(new_role.name))
await message.edit(view=view)