如何让Discord机器人执行自身创建的斜杠命令
让Discord机器人执行自身斜杠命令的解决方案
要实现机器人在on_ready中触发自身的rules斜杠命令,最简洁的方式是提取命令的核心逻辑为独立函数,避免构造复杂的Interaction对象(直接调用斜杠命令函数需要传入合法的Interaction,实现成本高且易出错)。
具体修改步骤
- 把
rules命令里发送规则嵌入的逻辑抽成单独的异步函数,实现逻辑复用,既可以在命令中调用,也能在on_ready中直接触发。 - 在
on_ready的频道清理逻辑完成后,调用这个独立函数发送规则。 - 原
rules命令只需保留权限检查逻辑,再调用抽离后的发送函数即可。
修改后的完整代码
import discord from discord import app_commands class aclient(discord.Client): def __init__(self): super().__init__(intents = discord.Intents.all()) self.synced = False # 避免重复同步命令 async def on_ready(self): await self.wait_until_ready() if not self.synced: await tree.sync(guild = discord.Object(id=1204091669943816213)) # 服务器专属命令同步 self.synced = True channel_id = 1204102053064871946 # 目标频道ID channel = self.get_channel(channel_id) if channel: await channel.purge(limit=1) # 删除频道内1条消息 # 调用抽离的规则发送函数 await send_rules_embed(channel, channel.guild) print(f"We have logged in as {self.user}.") class button_view(discord.ui.View): def __init__(self) -> None: super().__init__(timeout=None) @discord.ui.button(label = "Verify", style = discord.ButtonStyle.green, custom_id = "role_button") async def verify(self, interaction: discord.Interaction, button: discord.ui.Button): client.role = interaction.guild.get_role(1204110443258318928) if client.role not in interaction.user.roles: await interaction.user.add_roles(client.role) await interaction.response.send_message(f"I have given you {client.role.mention}!") with open("verified.txt", "w") as file: file.write(str(interaction.user.id) + "\n") else: await interaction.response.send_message(f"You already have {client.role.mention}!") # 抽离的规则发送逻辑 async def send_rules_embed(channel, guild): embed2=discord.Embed(title="📜 Rules 📜", description=''' **§1 -** __Be respectful__: Treat others with kindness and respect. Harassment, hate speech, or any form of discrimination will not be tolerated.\n **§2 -** __Keep discussions civil__: Debates and discussions are encouraged, but avoid personal attacks or insults. Disagreements should be handled respectfully.\n **§3 -** __No spam or self-promotion__: Avoid flooding the chat with unnecessary messages or advertisements.\n **§4 -** __Use appropriate content__: Keep conversations and content appropriate for all ages. NSFW (Not Safe For Work) content is strictly prohibited.\n **§5 -** __No trolling__: Do not engage in trolling, flaming, or intentionally disrupting the server environment. This includes excessive use of emojis or CAPS LOCK.\n **§6 -** __Follow Discord's Terms of Service and Community Guidelines__: Make sure all activities within the server comply with Discord's terms and guidelines.\n **§7 -** __Respect server staff__: Follow the instructions of moderators and administrators. Disrespect towards server staff will not be tolerated.\n **§8 -** __Use channels appropriately__: Post content in relevant channels and avoid off-topic discussions. If unsure, ask a staff member for guidance.\n **§9 -** __Report violations__: If you encounter any violations of the rules or Discord's guidelines, report them to the server staff. ''', color=discord.Colour.blue()) embed2.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Userbox_creeper.svg/800px-Userbox_creeper.svg.png") await channel.send(embed=embed2, view = button_view()) client = aclient() tree = app_commands.CommandTree(client) @tree.command(guild = discord.Object(id=1204091669943816213), name='rules', description='Rules') async def rules(interaction: discord.Interaction): role_id = 1205862534280642640 role = discord.utils.get(interaction.guild.roles, id=role_id) if role in interaction.user.roles: # 调用抽离的规则发送函数 await send_rules_embed(interaction.channel, interaction.guild) await interaction.response.send_message("规则已发送!", ephemeral=True) else: await interaction.response.send_message("你没有执行此命令的权限。") client.run('Token')
关键说明
- 抽离逻辑后代码复用性更强,无需重复编写发送规则的代码。
- 避免了手动构造
Interaction对象的复杂操作(Discord的Interaction包含大量上下文信息,手动构造极易出错)。 - 如果需要让机器人在
on_ready触发时也遵守权限限制,可以在调用send_rules_embed前,检查机器人自身是否拥有目标角色。
内容的提问来源于stack exchange,提问作者DZultra
相关产品推荐
相关产品推荐

