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

如何使用Discord API监听已加入公开频道中含指定关键词的公开消息?

实现方案推荐

方案1:使用Discord.js实现(和你现有JS代码适配性最高)

你已经通过OAuth2拿到了访问令牌,接下来按以下步骤操作即可:

  • 先安装依赖:npm install discord.js
  • 完整实现代码示例:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 替换为你前面OAuth流程拿到的access_token
const ACCESS_TOKEN = '你的OAuth访问令牌';
// 你要监听的关键词列表
const TARGET_KEYWORDS = ['关键词1', '关键词2'];

client.on('ready', () => {
  console.log(`已登录为 ${client.user.tag}`);
});

client.on('messageCreate', (message) => {
  // 跳过机器人自己发的消息避免重复触发
  if (message.author.bot) return;
  // 检查消息是否包含目标关键词
  const hasKeyword = TARGET_KEYWORDS.some(keyword => message.content.includes(keyword));
  if (hasKeyword) {
    // 这里写你的通知逻辑,比如打印、触发本地通知、调用其他通知接口都可以
    console.log(`匹配到关键词!频道:${message.channel.name},发送人:${message.author.tag},内容:${message.content}`);
  }
});

// 使用访问令牌登录
client.login(ACCESS_TOKEN).catch(err => console.error('登录失败:', err));

注意:你需要先在Discord开发者后台给你的应用开启Message Content Intent权限,否则无法读取消息内容,同时要确保你的OAuth授权时申请了guilds、guilds.messages.read、message.content.read相关权限。


方案2:使用Python discord.py实现

  • 安装依赖:pip install discord.py
  • 代码示例:
import discord
from discord.ext import commands

# 配置项
ACCESS_TOKEN = "你的OAuth访问令牌"
TARGET_KEYWORDS = ["关键词1", "关键词2"]

intents = discord.Intents.default()
intents.message_content = True
intents.guild_messages = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"已登录为 {bot.user}")

@bot.event
async def on_message(message):
    if message.author.bot:
        return
    if any(keyword in message.content for keyword in TARGET_KEYWORDS):
        print(f"匹配到关键词!频道:{message.channel.name},发送人:{message.author},内容:{message.content}")
        # 这里加自定义通知逻辑

bot.run(ACCESS_TOKEN)

方案3:使用REST API轮询实现(不依赖SDK)

如果不想用第三方SDK,可以定期调用Discord原生接口拉取消息检查关键词,注意不要请求太频繁触发限流,建议轮询间隔不低于1秒:

  • 首先调用 https://discord.com/api/users/@me/guilds 接口拿到你加入的所有服务器列表
  • 再调用 https://discord.com/api/guilds/{服务器ID}/channels 拿到对应服务器下的公开频道
  • 对每个公开频道调用 https://discord.com/api/channels/{频道ID}/messages?limit=10 拉取最新消息,检查是否包含关键词,只处理上次拉取之后的新消息即可
  • 所有请求的Header都要带上 Authorization: Bearer 你的访问令牌

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:06:03