I want to make a Discord Bot that can retrieve messages from Monday to Thursday I tried asking ChatGPT first, but the sample code he gave me didn't seem to work. as follows:
const channel = client.channels.cache.get('927408798027644990');
const now = dayjs().utcOffset(8); // UTC+8
const startOfWeek = now.startOf('week').add(1, 'day');
const endOfWeek = startOfWeek.add(3, 'day').endOf('day');
const lastMondaySnowflake = SnowflakeUtil.generate(new Date(startOfWeek.valueOf()));
const nextThursdaySnowflake = SnowflakeUtil.generate(new Date(endOfWeek.valueOf()));
console.log('Last Monday:', startOfWeek.toISOString());
console.log('Last Monday Snowflake:', lastMondaySnowflake);
console.log('Next Thursday:', endOfWeek.toISOString());
console.log('Next Thursday Snowflake:', nextThursdaySnowflake);
try {
const messages = await channel.messages.fetch({ after: lastMondaySnowflake, before: nextThursdaySnowflake });
console.log(messages.size); // why only 0?
} catch (error) {
console.error('撈取訊息時發生錯誤:', error);
}
I looked through the Discord.js file and it seems that the fetch method does not have after or before options.
I would like to ask how I can achieve the following requirements
Only the information from this Monday to Thursday will be retrieved?
You can calculate the before and after time then fetch
the messages with before and after options: FetchMessagesOptions
const channel = client.channels.cache.get('927408798027644990')
const dayInMs = 86400000 // 24 * 60 * 60 * 1000
let currentDate = new Date()
let daysUntilMonday = (currentDate.getDay() + 6) % 7 // difference between monday and the current day
// calculate the timestamp for the first day of the week
let firstDayOfWeek = new Date(currentDate.getTime() - daysUntilMonday * dayInMs)
// set the time to 00:00:00
firstDayOfWeek.setHours(0, 0, 0, 0)
// calculate the time until thursday 23:59:59
let timeUntilThursday = (4 - firstDayOfWeek.getDay() + 7) % 7 // 4 is thursday
// calculate the timestamp
let thursdayTimestamp = firstDayOfWeek.getTime() + timeUntilThursday * dayInMs + dayInMs - 1
// fetch channel messages from monday to thursday.
try {
let messages = await channel.messages.fetch({
after: firstDayOfWeek.getTime(),
before: thursdayTimestamp
})
console.log(messages.size)
}
catch (error) {
console.error('撈取訊息時發生錯誤:', error);
}