Skip to content

Commit

Permalink
✨ Update thread name on message updates (#468)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusOtter authored Mar 23, 2024
1 parent 1f6e65f commit 51acc1b
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 18 deletions.
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"useTabs": true,
"tabWidth": 4,
"arrowParens": "avoid",
"printWidth": 120
"printWidth": 120,
"trailingComma": "all"
}
16 changes: 8 additions & 8 deletions src/NeedleBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default class NeedleBot {
buttonsService: DynamicImportService<typeof NeedleButton>,
modalsService: DynamicImportService<typeof NeedleModal>,
configService: ConfigService,
cooldownService: CooldownService
cooldownService: CooldownService,
) {
this.client = discordClient;

Expand Down Expand Up @@ -112,27 +112,27 @@ export default class NeedleBot {
const listener = new Class(this);

if (listener.runType === ListenerRunType.EveryTime) {
this.client.on(listener.name, (...args) => {
this.client.on(listener.name, async (...args) => {
try {
listener.handle(args).catch(this.handleError);
await listener.handle(args).catch(this.handleError);
} catch (e) {
console.error(e);
this.handleError(e);
}
});
} else if (listener.runType === ListenerRunType.OnlyOnce) {
this.client.once(listener.name, (...args) => {
this.client.once(listener.name, async (...args) => {
try {
listener.handle(args).catch(this.handleError);
await listener.handle(args).catch(this.handleError);
} catch (e) {
console.error(e);
this.handleError(e);
}
});
}
}

this.client.on("debug", msg => console.log(`[${this.getCurrentTime()}] DEBUG: ${msg}`));
this.client.on("shardError", (error, shardId) =>
console.log(`[${this.getCurrentTime()}] SHARD ERROR (id ${shardId}): ${error}`)
console.log(`[${this.getCurrentTime()}] SHARD ERROR (id ${shardId}): ${error}`),
);
this.client.on("warn", msg => console.log(`[${this.getCurrentTime()}] WARN: ${msg}`));
}
Expand Down
4 changes: 2 additions & 2 deletions src/eventListeners/messageCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default class MessageCreateEventListener extends NeedleEventListener {
const botMember = await message.guild.members.fetchMe();
const guildConfig = this.bot.configs.get(message.guildId);
const channelConfig = guildConfig.threadChannels?.find(
c => c.channelId === message.channelId || c.channelId === message.channel.parentId
c => c.channelId === message.channelId || c.channelId === message.channel.parentId,
);

if (!channelConfig) return;
Expand All @@ -61,6 +61,6 @@ export default class MessageCreateEventListener extends NeedleEventListener {
const { author, member, channel } = message;
const messageVariables = new MessageVariables().setChannel(channel).setUser(member ?? author);

await this.threadCreator.createThreadOnMessage(message, messageVariables);
await this.threadCreator.createOrUpdateThreadOnMessage(message, messageVariables);
}
}
51 changes: 51 additions & 0 deletions src/eventListeners/messageUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { ClientEvents } from "discord.js";
import NeedleEventListener from "../models/NeedleEventListener.js";
import ListenerRunType from "../models/enums/ListenerRunType.js";
import ThreadCreationService from "../services/ThreadCreationService.js";
import NeedleBot from "../NeedleBot.js";
import ObjectFactory from "../ObjectFactory.js";
import MessageVariables from "../models/MessageVariables.js";

export default class MessageUpdateEventListener extends NeedleEventListener {
public readonly name = "messageUpdate";
public readonly runType = ListenerRunType.EveryTime;

private readonly threadCreator: ThreadCreationService;

constructor(bot: NeedleBot) {
super(bot);
this.threadCreator = ObjectFactory.createThreadCreationService(true);
}

public async handle([oldMessage, newMessage]: ClientEvents["messageUpdate"]): Promise<void> {
await newMessage.fetch();

if (!newMessage.hasThread) return;
if (newMessage.thread?.ownerId !== this.bot.client.user?.id) return;
if (!oldMessage.inGuild() || !newMessage.inGuild()) return;

const guildConfig = this.bot.configs.get(newMessage.guildId);
const channelConfig = guildConfig.threadChannels?.find(
c => c.channelId === newMessage.channelId || c.channelId === newMessage.channel.parentId,
);

if (!channelConfig) return;

const oldMessageVariables = new MessageVariables()
.setChannel(oldMessage.channel)
.setUser(oldMessage.member ?? oldMessage.author)
.setThread(oldMessage.thread);

const newMessageVariables = new MessageVariables()
.setChannel(newMessage.channel)
.setUser(newMessage.member ?? newMessage.author)
.setThread(newMessage.thread);

const expectedOldName = await this.threadCreator.getThreadName(oldMessage, channelConfig, oldMessageVariables);
const actualOldName = oldMessage.thread?.name ?? "";
// If the previous title is the default title, do not overwrite it
if (expectedOldName !== actualOldName) return;

await this.threadCreator.createOrUpdateThreadOnMessage(newMessage, newMessageVariables);
}
}
4 changes: 2 additions & 2 deletions src/eventListeners/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ export default class ReadyEventListener extends NeedleEventListener {
const messageVariables = new MessageVariables()
.setChannel(channel)
.setUser(member ?? author);
return this.threadCreator.createThreadOnMessage(m, messageVariables);
})
return this.threadCreator.createOrUpdateThreadOnMessage(m, messageVariables);
}),
);
} catch {
continue;
Expand Down
16 changes: 11 additions & 5 deletions src/services/ThreadCreationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,10 @@ export default class ThreadCreationService {
return true;
}

public async createThreadOnMessage(
message: Message,
public async createOrUpdateThreadOnMessage(
message: Message<true>,
messageVariables: MessageVariables,
): Promise<AnyThreadChannel | undefined> {
if (!message.inGuild()) return;
if (!(message.channel instanceof TextChannel) && !(message.channel instanceof NewsChannel)) return;

const guildConfig = this.bot.configs.get(message.guildId);
Expand All @@ -100,7 +99,14 @@ export default class ThreadCreationService {
}

const name = await this.getThreadName(message, channelConfig, messageVariables);
if (message.hasThread) return;
if (message.hasThread) {
await message.fetch();
if (!message.thread || message.thread.name === name) return;

await message.thread.edit({ name });
return;
}

const thread = await message.startThread({
name,
rateLimitPerUser: channelConfig.slowmode === 0 ? undefined : channelConfig.slowmode,
Expand Down Expand Up @@ -145,7 +151,7 @@ export default class ThreadCreationService {
this.lastLogTime = currentTime;
}

private async getThreadName(
public async getThreadName(
message: Message,
config: AutothreadChannelConfig,
variables: MessageVariables,
Expand Down

0 comments on commit 51acc1b

Please sign in to comment.