如何在discord.py中点击后禁用Discord交互按钮并置灰未点击按钮
实现Discord版主申请按钮的状态更新功能
要实现点击「接受」或「拒绝」按钮后,对应按钮保持原样式并禁用、另一个按钮变为灰色禁用的效果,你需要在按钮回调函数中修改按钮的样式和禁用状态,再更新消息的视图。以下是具体实现步骤和修改后的代码:
关键修改点
- 在按钮回调中,将未点击的按钮的样式改为
discord.ButtonStyle.secondary(灰色),并设置disabled=True - 将点击的按钮设置为
disabled=True,防止重复点击 - 通过
interaction.response.edit_message()更新消息的视图,让状态变更生效
修改后的完整代码
import os import discord from discord import app_commands TOKEN = ' YOUR BOT TOKEN HERE ' GUILD = ' SERVER NAME HERE ' intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) tree = app_commands.CommandTree(client=client) @client.event async def on_ready(): for guild in client.guilds: if guild.name == GUILD: break print(f'{client.user} is connected to {guild.name}(id: {guild.id})') # 同步命令,确保服务器能获取最新命令定义 await tree.sync(guild=discord.Object(id=000000000)) @tree.command(name='apply', description='Apply for Moderator', guild=discord.Object(id=000000000)) async def firstcommand(interaction:discord.Interaction, name:str, reason:str, experience:str): submission_channel = await client.fetch_channel(00000000000000) emb = discord.Embed(title='Moderator App', description=f'Name: {name} \n Reason to be mod: {reason} \n Moderator Experience: {experience}') emb.set_author(name=f'Submitted by {interaction.user}') accept_button = discord.ui.Button(label="Accept", style=discord.ButtonStyle.success) reject_button = discord.ui.Button(label='Reject', style=discord.ButtonStyle.danger) view = discord.ui.View() view.add_item(accept_button) view.add_item(reject_button) async def accept_callback(interaction:discord.Interaction): # 更新按钮状态:接受按钮禁用,拒绝按钮变灰并禁用 accept_button.disabled = True reject_button.style = discord.ButtonStyle.secondary reject_button.disabled = True # 同步视图到原消息 await interaction.response.edit_message(view=view) # 发送仅操作人可见的反馈 await interaction.followup.send('Application Accepted.', ephemeral=True) async def reject_callback(interaction:discord.Interaction): # 更新按钮状态:拒绝按钮禁用,接受按钮变灰并禁用 reject_button.disabled = True accept_button.style = discord.ButtonStyle.secondary accept_button.disabled = True # 同步视图到原消息 await interaction.response.edit_message(view=view) # 发送仅操作人可见的反馈 await interaction.followup.send('Application Rejected.', ephemeral=True) accept_button.callback = accept_callback reject_button.callback = reject_callback await submission_channel.send(embed=emb, view=view) await interaction.response.send_message('Your Application has been submitted to the Head Admin for review. Thank you.', ephemeral=True) client.run(TOKEN)
额外说明
- 视图同步:修改按钮状态后必须用
edit_message更新视图,否则所有用户看到的按钮状态不会变化 - 反馈消息:使用
followup.send并设置ephemeral=True,可以避免在审核频道发送冗余提示,仅让操作按钮的版主看到反馈 - 命令同步:
tree.sync()用于确保服务器能获取最新的斜杠命令定义,首次部署或修改命令后建议执行
内容的提问来源于stack exchange,提问作者fuzzyexoskills
相关产品推荐
相关产品推荐

