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

使用discord.js实现消息去重发送:如何查看频道内上一条消息

实现频道消息去重发送方案

以下是基于主流Discord机器人开发库的实现方式,核心逻辑是获取频道最新一条消息,对比内容后决定是否发送:

使用 Discord.js(JavaScript/TypeScript)

// 传入频道对象和待发送消息内容
async function sendIfDifferent(channel, messageContent) {
    // 获取频道最新1条消息(过滤机器人消息避免循环)
    const messages = await channel.messages.fetch({ limit: 1 });
    const lastMessage = messages.filter(msg => !msg.author.bot).first();

    // 无历史消息直接发送
    if (!lastMessage) {
        await channel.send(messageContent);
        return;
    }

    // 精确对比内容,不一致则发送
    if (lastMessage.content !== messageContent) {
        await channel.send(messageContent);
    }
}

可选优化:模糊匹配

如果需要忽略空格、大小写差异,可以对内容做预处理:

const processedLastContent = lastMessage.content.trim().toLowerCase();
const processedNewContent = messageContent.trim().toLowerCase();

if (processedLastContent !== processedNewContent) {
    await channel.send(messageContent);
}

使用 discord.py(Python)

# 传入频道对象和待发送消息内容
async def send_if_different(channel, message_content):
    # 获取频道最新1条消息(过滤机器人消息)
    last_message_list = await channel.history(limit=1, author__bot=False).flatten()
    last_message = last_message_list[0] if last_message_list else None

    # 无历史消息直接发送
    if not last_message:
        await channel.send(message_content)
        return

    # 精确对比内容,不一致则发送
    if last_message.content != message_content:
        await channel.send(message_content)

可选优化:模糊匹配

processed_last_content = last_message.content.strip().lower()
processed_new_content = message_content.strip().lower()

if processed_last_content != processed_new_content:
    await channel.send(message_content)

注意事项

  • 确保机器人拥有Read Message History权限,否则无法获取频道历史消息。
  • 若频道存在大量历史消息,limit=1的查询不会造成性能负担。

内容的提问来源于stack exchange,提问作者DevilPlays10

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:01:02