如何开发支持通过命令向指定Discord频道发送预设消息的Discord bot?
实现方案
默认你使用目前主流的discord.py库开发,具体实现步骤如下:
前置准备
- 已完成Discord bot基础框架搭建,可正常上线运行
- 已在Discord开发者后台开启对应权限:如果使用前缀命令需要开启Message Content Intent,同时给bot授予「读取消息/查看频道」「发送消息」权限
- 先定义好你的预设内容,示例:
# 自定义预设消息,可按需求修改内容 PRESET_CONTENT = "这是你预先设置好的待发送消息,支持换行、emoji、@提及等格式"
方案1:前缀命令实现(即你提到的bot.send #general形式)
首先设置bot的命令前缀为bot.,然后编写send命令逻辑:
import discord from discord.ext import commands # 配置bot intents intents = discord.Intents.default() intents.message_content = True # 前缀命令必须开启这个权限 bot = commands.Bot(command_prefix="bot.", intents=intents) # send命令实现 @bot.command(name="send") async def send_preset_msg(ctx, channel: discord.TextChannel): # 向指定频道发送预设消息 await channel.send(PRESET_CONTENT) # 给命令发送者发操作反馈 await ctx.send(f"已成功向 {channel.mention} 发送预设消息") # 命令参数错误的回调处理 @send_preset_msg.error async def send_error(ctx, error): if isinstance(error, commands.ChannelNotFound): await ctx.send("错误:未找到你指定的频道,请确认你正确@了对应文本频道") elif isinstance(error, commands.MissingRequiredArgument): await ctx.send("错误:请指定要发送的频道,格式示例:`bot.send #general`") elif isinstance(error, commands.BotMissingPermissions): await ctx.send("错误:我没有对应频道的发送消息权限,请调整权限设置") # 运行bot,替换成你自己的bot token bot.run("你的bot token")
使用方法:在任意bot有权限的频道发送bot.send #目标频道即可触发功能。
方案2:斜杠命令实现(Discord官方推荐,无需开启消息内容权限)
如果使用discord.py v2.0+版本,可以直接用原生斜杠命令,实现更稳定:
import discord from discord import app_commands intents = discord.Intents.default() bot = discord.Client(intents=intents) tree = app_commands.CommandTree(bot) PRESET_CONTENT = "这是你预先设置好的待发送消息" @tree.command(name="send_preset", description="向指定频道发送预设消息") async def send_preset(interaction: discord.Interaction, channel: discord.TextChannel): if not channel.permissions_for(interaction.guild.me).send_messages: await interaction.response.send_message("我没有该频道的发送权限", ephemeral=True) return await channel.send(PRESET_CONTENT) await interaction.response.send_message(f"已向{channel.mention}发送预设消息", ephemeral=True) @bot.event async def on_ready(): # 同步全局命令,第一次同步可能需要最多1小时生效,测试可以同步到指定服务器 await tree.sync() print(f"已登录为 {bot.user}") bot.run("你的bot token")
常见问题排查
- 前缀命令无响应:先检查是否开启了Message Content Intent,以及bot是否有当前频道的读消息权限
- 发送失败:确认bot在目标频道拥有发送消息权限,频道不是禁言状态
- 命令参数不生效:确认输入格式正确,频道参数必须是@提及的可点击频道,不能手动输入#general文本
内容的提问来源于stack exchange,提问作者Zevzzz
相关产品推荐
相关产品推荐

