Skip to content

Commit

Permalink
Merge pull request #109 from discordjs-japan/fix/wait-for-starter-mes…
Browse files Browse the repository at this point in the history
…sage-on-thread-create
  • Loading branch information
cm-ayf authored Jun 20, 2024
2 parents 0a8ab4e + c4d50d5 commit 59ea812
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
18 changes: 11 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import { handleCreateNotify, handleOwnerClose } from './handleCreateNotify.js'
import { handleReopenNotify } from './handleReopenNotify.js'
import { onInterval } from './onInterval.js'
import { forumChannelSettings } from './forum.js'
import { fetchStarterMessageOrNull, lockThreadForNoStarter } from './starter.js'
import {
fetchStarterMessageOrNull,
getOrWaitForStarterMessage,
lockThreadForNoStarter,
} from './starter.js'
import { handleReactionClose } from './handleReactionClose.js'
import { handleLock } from './handleLock.js'
/**
Expand Down Expand Up @@ -71,12 +75,12 @@ client.on(Events.ThreadCreate, async (thread, newlyCreated) => {
const setting = forumChannelSettings.find(it => it.id === thread.parentId)
if (!setting) return

if (newlyCreated)
handleCreateNotify(
logger.createChild('onForumThreadCreate'),
thread,
setting
)
if (!newlyCreated) return

// ensure that the starter message is posted
await getOrWaitForStarterMessage(thread)

handleCreateNotify(logger.createChild('onForumThreadCreate'), thread, setting)
})

client.on(Events.GuildAuditLogEntryCreate, async (auditLogEntry, guild) => {
Expand Down
20 changes: 19 additions & 1 deletion src/starter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DiscordAPIError } from 'discord.js'
import { DiscordAPIError, ThreadOnlyChannel } from 'discord.js'

/**
* @typedef {import('discord.js').AnyThreadChannel} AnyThreadChannel
Expand All @@ -15,6 +15,24 @@ export async function fetchStarterMessageOrNull(thread) {
})
}

/**
* @param {AnyThreadChannel} thread
*/
export async function getOrWaitForStarterMessage(thread) {
const channel =
thread.parent instanceof ThreadOnlyChannel ? thread : thread.parent
const existing = channel?.messages.cache.get(thread.id)
if (existing) return existing

// if the starter message is not found, wait for it
const collected = await channel?.awaitMessages({
max: 1,
time: 60000,
filter: m => m.id === thread.id,
})
return collected?.get(thread.id)
}

/**
* @param {Logger} logger
* @param {AnyThreadChannel} thread
Expand Down

0 comments on commit 59ea812

Please sign in to comment.