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

Twitch触发timeout事件时如何不通过ID删除Discord指定用户名的消息

报错原因

  • 你错误嵌套了discordClient.on('message')监听器:每次Twitch触发timeout事件都会新增一个message事件绑定,会导致内存泄漏和逻辑重复执行,且该事件回调的第二个参数本身不存在,你拿到的messages是undefined,调用undefined.first()自然触发报错
  • Collection.first()方法的作用是返回集合中前N个元素,不支持按用户名筛选,你的调用方法完全不符合Discord.js的API规范
  • Promise链式调用逻辑混乱,fetch消息后的后续操作没有正确接收到返回的消息集合

实现思路

你用单个webhook转发Twitch消息时,所有转发消息的真实作者ID都是webhook的ID,但是消息的author.username字段就是你转发时自定义的Twitch用户名,直接按这个字段筛选即可,不需要用到用户真实ID。

修正后的完整代码

twitchClient.on('timeout', async (channel, username, user, reason, duration) => {
    // 1. 删除指定频道内对应用户名的所有消息
    const targetChannel = discordClient.channels.cache.get("901568598538063932");
    if (targetChannel) {
        try {
            // 拉取频道内最多100条消息,可根据需求调整limit,单次最大支持100
            const fetchedMessages = await targetChannel.messages.fetch({ limit: 100 });
            // 筛选出作者用户名匹配的消息
            const messagesToDelete = fetchedMessages.filter(msg => msg.author.username === username);
            // 批量删除,自动过滤14天以上无法批量删除的消息
            if (messagesToDelete.size > 0) {
                await targetChannel.bulkDelete(messagesToDelete, true);
            }
        } catch (err) {
            console.error('删除消息失败:', err);
        }
    }

    // 2. 发送超时通知
    const request = new XMLHttpRequest();
    request.open("POST", "你的webhook API地址");
    request.setRequestHeader('Content-type', 'application/json');
    const payload = { 
        username: "User Timed Out",
        avatar_url: 'https://i.imgur.com/GUrbNsB.jpg',
        content: `**${username} has been timed out for ${duration} seconds.**`
    };
    request.send(JSON.stringify(payload));
});

注意事项

  • 如果你转发消息时给用户名加了自定义前缀/后缀,需要对应修改filter里的匹配规则
  • 单次最多拉取100条消息,如果需要删除更早的内容,需要分页拉取后单独调用单条消息的delete方法处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:36:03