如何设置一个只能被特定角色按下的按钮?
这是代码:
class SimpleView(discord.ui.View):
def __init__(self):
self.start_time = None
self.stop_time = None
super().__init__(timeout=None)
@discord.ui.button(label="⬆️", style=discord.ButtonStyle.green, custom_id="1")
@commands.has_role("♂️ FUORI SERVIZIO")
async def entrata(self, interaction: discord.Interaction, button: discord.ui.Button):
orario_it = datetime.now(pytz.timezone('Europe/Rome'))
orario = orario_it.strftime('%H:%M')
SimpleView.start_time = time.time()
channel = bot.get_channel(1214495527924928522)
embed=discord.Embed(color=0x23a559)
embed.set_thumbnail(url="https://shft.cl/img/c/cdn.discordapp.com-101395680655364460.webp")
embed.add_field(name="⬆️⬆️", value="", inline=False) #BOTTONE ENTRATA
embed.add_field(name="NOME:", value=f"{interaction.user.mention}", inline=True)
embed.add_field(name="", value="", inline=True)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="DATA:", value=f"{data}", inline=True)
embed.add_field(name="ORARIO:", value=f"{orario}", inline=True)
embed.set_footer(text="ARMERIA200")
await channel.send(embed=embed)
await interaction.response.send_message(f"***SEI ENTRATO IN SERVIZIO ALLE: {orario}.***", ephemeral=True)
@discord.ui.button(label="⬇️", style=discord.ButtonStyle.red, custom_id="2")
@commands.has_role("♂️ IN SERVIZIO")
async def uscita(self, interaction: discord.Interaction, button: discord.ui.Button):
orario_it = datetime.now(pytz.timezone('Europe/Rome'))
orario = orario_it.strftime('%H:%M')
SimpleView.stop_time = time.time()
elapsed_time = SimpleView.stop_time - SimpleView.start_time
time_d = timedelta(seconds=int(elapsed_time))
channel = bot.get_channel(1215061241270374400)
embed=discord.Embed(color=0xda373c)
embed.set_thumbnail(url="https://shft.cl/img/c/cdn.discordapp.com-101395680655364460.webp")
embed.add_field(name="⬇️⬇️", value="", inline=False)
embed.add_field(name="NOME:", value=f"{interaction.user.mention}", inline=True) #BOTTONE USCITA
embed.add_field(name="", value="", inline=True)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="DATA:", value=f"{data}", inline=True)
embed.add_field(name="ORARIO:", value=f"{orario}", inline=True)
embed.add_field(name="TEMPO IN SERVIZIO:", value=f"{time_d}", inline=True)
embed.set_footer(text="ARMERIA200")
await channel.send(embed=embed)
await interaction.response.send_message(f"***SEI USCITO DI SERVIZIO ALLE: {orario}, DOPO: {time_d}***", ephemeral=True)
我希望这两个按钮只能被拥有“♂️ IN SERVIZIO”和“♂️ FUORI SERVIZIO”角色的人按。可是我不知道该怎么做。我试着找了不同的解决方案,但找不到有用的东西。请帮帮我。
1 个回答
0
你现在使用的装饰器只适用于discord.py的命令扩展,建议把它去掉。
如果你想让按钮只对某个角色可用:
首先,通过Discord的开发者设置获取你想检查的角色的ID。
然后检查用户是否拥有这些角色,只有在用户有这些角色时才执行后面的代码,否则就延迟处理这个互动。
role = interaction.guild.get_role({id here})
if role in interaction.user.roles:
# code here
else:
await interaction.response.defer()