如何获取特定时间范围的训练系统?Discord Bot消息获取求助
如何实现Discord Bot获取本周周一至周四的消息
问题背景
开发Discord Bot时,尝试使用ChatGPT提供的代码获取周一至周四的消息,但messages.size始终为0。排查发现当前版本的Discord.js中channel.messages.fetch()方法不支持after/before参数,需要调整实现方式。
解决方案
1. 准确计算目标时间范围
使用dayjs正确计算本周一00:00到本周四23:59:59的时间区间(dayjs默认周起始为周日,需加1天得到周一):
const now = dayjs().utcOffset(8); // 统一使用UTC+8时区 const mondayStart = now.startOf('week').add(1, 'day'); // 本周一00:00 const thursdayEnd = mondayStart.add(3, 'day').endOf('day'); // 本周四23:59:59
2. 分页拉取并过滤消息
由于无法通过fetch参数直接筛选时间,需分页拉取消息历史,再通过消息的createdTimestamp属性过滤出目标时间范围内的消息:
const channel = client.channels.cache.get('927408798027644990'); const targetMessages = []; let lastMsgId = null; try { while (true) { // 每次拉取最多100条消息(Discord API限制),分页拉取更早的消息 const fetchedMessages = await channel.messages.fetch({ limit: 100, ...(lastMsgId && { before: lastMsgId }) }); if (fetchedMessages.size === 0) break; // 无更多消息时停止 // 筛选出时间在目标区间内的消息 const filtered = fetchedMessages.filter(msg => { const msgTime = dayjs(msg.createdTimestamp).utcOffset(8); return msgTime.isBetween(mondayStart, thursdayEnd, 'day', '[]'); }); targetMessages.push(...filtered.values()); // 检查最早的消息是否早于周一,若是则停止拉取 const earliestMsgTime = dayjs(fetchedMessages.last().createdTimestamp).utcOffset(8); if (earliestMsgTime.isBefore(mondayStart)) break; lastMsgId = fetchedMessages.last().id; // 更新分页标记 } console.log('筛选出的消息数量:', targetMessages.length); // 此处处理筛选后的消息 } catch (error) { console.error('获取消息失败:', error); }
3. 必要注意事项
- 权限要求:Bot需拥有
VIEW_CHANNEL和READ_MESSAGE_HISTORY权限才能读取频道消息历史。 - 时区一致性:确保消息时间戳与计算的时间范围使用同一时区,避免过滤偏差。
- API限制:Discord API限制每次拉取最多100条消息,因此必须通过分页方式获取完整的消息历史。
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

