You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Discord机器人编写!say命令,实现去前缀发消息及指定频道发送

解决方案

1. 去除!say命令前缀

你当前代码直接发送完整的message.content,所以会携带!say前缀。直接对消息内容做切片处理即可,!say共占4个字符长度,截取索引4之后的内容即可,额外加strip()处理前后多余空格:

# 原逻辑
await message.channel.send(message.content)
# 修改为
await message.channel.send(message.content[4:].strip())

2. 指定频道发送消息

提供两种常用实现方式:

固定指定某一个频道发送

提前复制目标频道ID(Discord开启开发者模式后右键频道即可复制),通过ID获取频道对象后发送:

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!say'):
        send_content = message.content[4:].strip()
        # 替换为你的目标频道ID
        target_channel = client.get_channel(替换为实际频道ID)
        if target_channel:
            await target_channel.send(send_content)

命令动态指定发送频道

支持用户输入!say #目标频道 消息内容格式,自动识别提及的频道发送:

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!say'):
        msg_parts = message.content.split(maxsplit=2)
        # 参数校验
        if len(msg_parts) < 3 or not message.channel_mentions:
            await message.channel.send("命令格式错误,正确格式:!say #目标频道 消息内容")
            return
        target_channel = message.channel_mentions[0]
        send_content = msg_parts[2]
        await target_channel.send(send_content)

补充说明

  • 机器人需要拥有目标频道的「发送消息」权限,否则会触发权限报错
  • 若使用discord.py v2.0及以上版本,需要开启消息内容意图:
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

内容的提问来源于stack exchange,提问作者Ákos Molnár

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:36:05