-
Notifications
You must be signed in to change notification settings - Fork 13
feat: manage recurring messages #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c68d02e
feat: /cron command to add recurring messages
luca-montaigut 4065e45
feat: add permissions on command /cron
luca-montaigut af07329
fix: better naming
luca-montaigut e1d2ba2
feat: add id to reccuring message and store them
luca-montaigut 2c970fb
feat: relaunch recurring messages on bot restart
luca-montaigut a07acf9
feat: remove recurring message
luca-montaigut 9c70038
feat: list recurring messages
luca-montaigut c3b2cb0
feat: inMemoryJobList to handle job stop
luca-montaigut 409f74e
fix: lockfile
luca-montaigut f7aa53d
refactor: event handler pattern
luca-montaigut 3003b31
fix: add type predicate for frequency
luca-montaigut File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { type APIInteractionGuildMember, GuildMember } from 'discord.js'; | ||
|
||
export const isAdmin = (member: GuildMember | APIInteractionGuildMember | null): boolean => | ||
member instanceof GuildMember && member.roles.cache.some((role) => role.name === 'Admin'); | ||
|
||
export const isModo = (member: GuildMember | APIInteractionGuildMember | null): boolean => | ||
member instanceof GuildMember && | ||
member.roles.cache.some((role) => role.name === 'Admin' || role.name === 'Modo'); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
src/modules/recurringMessage/recurringMessage.helpers.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
import { CronJob } from 'cron'; | ||
import { randomUUID } from 'crypto'; | ||
import type { ChatInputCommandInteraction, Client } from 'discord.js'; | ||
|
||
import { cache } from '../../core/cache'; | ||
import { isModo } from '../../helpers/roles'; | ||
|
||
const MAX_MESSAGE_LENGTH = 2000; | ||
|
||
const cronTime = { | ||
daily: '0 0 9 * * *', | ||
weekly: '0 0 9 * * 1', | ||
monthly: '0 0 9 1 * *', | ||
}; | ||
|
||
const frequencyDisplay = { | ||
daily: 'every day at 9am', | ||
weekly: 'every monday at 9am', | ||
monthly: 'the 1st of every month at 9am', | ||
}; | ||
|
||
const inMemoryJobList: { id: string; job: CronJob }[] = []; | ||
|
||
export type Frequency = keyof typeof cronTime; | ||
|
||
export const isFrequency = (frequency: string): frequency is Frequency => { | ||
return Object.keys(cronTime).includes(frequency); | ||
}; | ||
|
||
export const hasPermission = (interaction: ChatInputCommandInteraction) => { | ||
if (!isModo(interaction.member)) { | ||
interaction.reply('You are not allowed to use this command').catch(console.error); | ||
return false; | ||
} | ||
return true; | ||
}; | ||
|
||
export const createRecurringMessage = ( | ||
client: Client<true>, | ||
channelId: string, | ||
frequency: Frequency, | ||
message: string, | ||
): CronJob => { | ||
return new CronJob( | ||
cronTime[frequency], | ||
() => { | ||
const channel = client.channels.cache.get(channelId); | ||
if (!channel || !channel.isTextBased()) { | ||
console.error(`Channel ${channelId} not found`); | ||
return; | ||
} | ||
void channel.send(message); | ||
}, | ||
null, | ||
true, | ||
'Europe/Paris', | ||
); | ||
}; | ||
|
||
export const addRecurringMessage = async (interaction: ChatInputCommandInteraction) => { | ||
const jobId = randomUUID(); | ||
const channelId = interaction.channelId; | ||
const frequency = interaction.options.getString('frequency', true); | ||
if (!isFrequency(frequency)) { | ||
await interaction.reply(`${frequency} is not a valid frequency`); | ||
return; | ||
} | ||
const message = interaction.options.getString('message', true); | ||
|
||
const displayIdInMessage = `\n (id: ${jobId})`; | ||
const jobMessage = message + displayIdInMessage; | ||
|
||
if (jobMessage.length > MAX_MESSAGE_LENGTH) { | ||
await interaction.reply( | ||
`Message is too long (max ${MAX_MESSAGE_LENGTH - displayIdInMessage.length} characters)`, | ||
); | ||
return; | ||
} | ||
|
||
const job = createRecurringMessage(interaction.client, channelId, frequency, jobMessage); | ||
job.start(); | ||
|
||
inMemoryJobList.push({ id: jobId, job }); | ||
|
||
const recurringMessages = await cache.get('recurringMessages', []); | ||
await cache.set('recurringMessages', [ | ||
...recurringMessages, | ||
{ id: jobId, channelId, frequency, message }, | ||
]); | ||
|
||
await interaction.reply(`Recurring message added ${frequencyDisplay[frequency]}`); | ||
}; | ||
|
||
export const removeRecurringMessage = async (interaction: ChatInputCommandInteraction) => { | ||
const jobId = interaction.options.getString('id', true); | ||
|
||
console.log(jobId, inMemoryJobList); | ||
|
||
const recurringMessages = await cache.get('recurringMessages', []); | ||
await cache.set( | ||
'recurringMessages', | ||
recurringMessages.filter(({ id }) => id !== jobId), | ||
); | ||
|
||
const job = inMemoryJobList.find(({ id }) => id === jobId)?.job; | ||
if (!job) { | ||
await interaction.reply('Recurring message not found'); | ||
return; | ||
} | ||
|
||
job.stop(); | ||
|
||
await interaction.reply('Recurring message removed'); | ||
}; | ||
|
||
export const listRecurringMessages = async (interaction: ChatInputCommandInteraction) => { | ||
const recurringMessages = await cache.get('recurringMessages', []); | ||
|
||
if (recurringMessages.length === 0) { | ||
await interaction.reply('No recurring message found'); | ||
return; | ||
} | ||
|
||
const recurringMessagesList = recurringMessages | ||
.map( | ||
({ id, frequency, message }) => | ||
`id: ${id} - frequency: ${frequency} - ${message.substring(0, 50)}${ | ||
message.length > 50 ? '...' : '' | ||
}`, | ||
) | ||
.join('\n'); | ||
|
||
await interaction.reply(recurringMessagesList); | ||
}; | ||
|
||
export const relaunchRecurringMessages = async (client: Client<true>) => { | ||
const recurringMessages = await cache.get('recurringMessages', []); | ||
|
||
recurringMessages.forEach(({ id, channelId, frequency, message }) => { | ||
const job = createRecurringMessage(client, channelId, frequency, message); | ||
job.start(); | ||
inMemoryJobList.push({ id, job }); | ||
}); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import { SlashCommandBuilder } from 'discord.js'; | ||
|
||
import type { BotModule } from '../../types/bot'; | ||
import { | ||
addRecurringMessage, | ||
hasPermission, | ||
listRecurringMessages, | ||
relaunchRecurringMessages, | ||
removeRecurringMessage, | ||
} from './recurringMessage.helpers'; | ||
|
||
export const recurringMessage: BotModule = { | ||
slashCommands: [ | ||
{ | ||
schema: new SlashCommandBuilder() | ||
.setName('recurrent') | ||
.setDescription('Manage recurring messages') | ||
.addSubcommand((subcommand) => | ||
subcommand | ||
.setName('add') | ||
.setDescription('Add a recurring message') | ||
.addStringOption((option) => | ||
option | ||
.setName('frequency') | ||
.setDescription('How often to send the message') | ||
.addChoices( | ||
{ name: 'daily', value: 'daily' }, | ||
{ name: 'weekly', value: 'weekly' }, | ||
{ name: 'monthly', value: 'monthly' }, | ||
) | ||
.setRequired(true), | ||
) | ||
.addStringOption((option) => | ||
option.setName('message').setDescription('The message to send').setRequired(true), | ||
), | ||
) | ||
.addSubcommand((subcommand) => | ||
subcommand | ||
.setName('remove') | ||
.setDescription('Remove a recurring message') | ||
.addStringOption((option) => | ||
option | ||
.setName('id') | ||
.setDescription('The id of the recurring message to remove') | ||
.setRequired(true), | ||
), | ||
) | ||
.addSubcommand((subcommand) => | ||
subcommand.setName('list').setDescription('List recurring messages'), | ||
) | ||
.toJSON(), | ||
handler: { | ||
add: async (interaction) => { | ||
if (!hasPermission(interaction)) return; | ||
|
||
await addRecurringMessage(interaction); | ||
}, | ||
remove: async (interaction) => { | ||
if (!hasPermission(interaction)) return; | ||
|
||
await removeRecurringMessage(interaction); | ||
}, | ||
list: async (interaction) => { | ||
if (!hasPermission(interaction)) return; | ||
|
||
await listRecurringMessages(interaction); | ||
}, | ||
}, | ||
}, | ||
], | ||
eventHandlers: { | ||
// relaunch recurring messages on bot restart | ||
ready: relaunchRecurringMessages, | ||
}, | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.