Implement /unnag

This commit is contained in:
2025-07-05 18:10:24 -04:00
parent 88679d2eda
commit 8c2e889f2a
6 changed files with 505 additions and 472 deletions

View File

@@ -1,19 +1,19 @@
import {
type ChatInputCommandInteraction,
SlashCommandBuilder,
} from "discord.js";
} from 'discord.js';
import type { Settings } from "./service";
import type {Settings} from './service';
import { Nag, CheckIn } from "./service";
import {Nag, CheckIn} from './service';
const data = new SlashCommandBuilder()
.setName("checkin")
.setDescription("Check-in for your daily nag")
.addStringOption((option) =>
.setName('checkin')
.setDescription('Check-in for your daily nag')
.addStringOption(option =>
option
.setName("text")
.setDescription("Optional description of what you have achieved"),
.setName('text')
.setDescription('Optional description of what you have achieved'),
);
async function initialize(settings: Settings) {}
@@ -36,13 +36,15 @@ async function execute(interaction: ChatInputCommandInteraction) {
nagId: nag.id,
lastCheckIn: new Date(Date.now()),
});
await interaction.reply("Thanks for checking in!");
await interaction.reply('Thanks for checking in!');
break;
}
}
export default function () {
export default function (settings: Settings) {
return {
data,
initialize: async () => initialize(settings),
execute: execute,
};
}

View File

@@ -1,36 +1,37 @@
import {
type ChatInputCommandInteraction,
SlashCommandBuilder,
} from "discord.js";
} from 'discord.js';
import { Nag, CheckIn, type Settings } from "./service";
import { Chrono } from "chrono-node";
import {Nag, CheckIn, type Settings} from './service';
import {Chrono} from 'chrono-node';
const data = new SlashCommandBuilder()
.setName("nag")
.setDescription("Let Blitzcrank nag you every day about something")
.addStringOption((option) =>
.setName('nag')
.setDescription('Let Blitzcrank nag you every day about something')
.addStringOption(option =>
option
.setRequired(true)
.setName("text")
.setDescription("What you have to do every day"),
.setName('text')
.setDescription('What you have to do every day'),
)
.addStringOption((option) =>
.addStringOption(option =>
option
.setName("failText")
.setDescription("Custom message to be broadcast on failure"),
.setName('failtext')
.setDescription('Custom message to be broadcast on failure')
.setRequired(false),
)
.addBooleanOption((option) =>
.addBooleanOption(option =>
option
.setName("mentionHere")
.setDescription("Whether to DM you or @ a channel")
.setName('mentionhere')
.setDescription('Whether to DM you or @ this channel')
.setRequired(false),
);
async function initialize(settings: Settings) {}
async function execute(interaction: ChatInputCommandInteraction) {
const text = interaction.options.getString("text");
const text = interaction.options.getString('text');
if (text === null || text === undefined) {
await interaction.reply("Nag can't have a blank `text`, try again.");
return;
@@ -38,14 +39,17 @@ async function execute(interaction: ChatInputCommandInteraction) {
// Check if we already have an existing nag. In theory, this should be supported entirely, however
// I want to keep things simple for now.
const existingNags = await Nag.findAll({
where: { userId: interaction.user.id },
order: [["createdAt", "ASC"]],
where: {
userId: interaction.user.id,
},
// order: [["createdAt", "ASC"]],
});
console.log('Successfully looked for checkIns');
if (existingNags && existingNags.length > 0) {
// TODO: Hmm... For now, I guess we can just update the database.
for (const nag of existingNags) {
nag.text = text;
nag.failText = interaction.options.getString("failText") ?? undefined;
nag.failText = interaction.options.getString('failtext') ?? undefined;
await nag.save();
break;
}
@@ -61,21 +65,23 @@ async function execute(interaction: ChatInputCommandInteraction) {
channelId: interaction.channel?.id,
messageId: interaction.id,
text: text,
failText: interaction.options.getString("failText"),
mentionHere: interaction.options.getBoolean("mentionHere") ?? false,
failText: interaction.options.getString('failtext'),
mentionHere: interaction.options.getBoolean('mentionhere') ?? false,
});
await nag.save();
const chrono = new Chrono();
const checkIn = chrono.parseDate("today at 9AM");
const checkIn = chrono.parseDate('today at 9AM');
if (!checkIn) {
await interaction.reply(
"Internal error while saving your nag. Tell Drew the bot is broken!!!",
'Internal error while saving your nag. Tell Drew the bot is broken!!!',
);
return;
}
await CheckIn.create({
nagId: nag.id,
checkIn: checkIn,
nag: {
id: nag.id,
},
lastCheckIn: new Date(Date.now()),
});
await interaction.reply(
`I'll check every day at 9AM if you've completed '${text}'. If not, I'll nag you! Use /checkin to prevent a shameful callout, and /unnag to cancel.`,

View File

@@ -1,4 +1,4 @@
import { expect, test, vi, it, describe, beforeEach, afterEach } from "vitest";
import {expect, test, vi, it, describe, beforeEach, afterEach} from 'vitest';
import {
nextCheckInDate,
initAndSyncTables,
@@ -6,17 +6,17 @@ import {
CheckIn,
findGuiltyNags,
getCheckIn,
} from "./service";
import { Sequelize, literal, Op } from "sequelize";
} from './service';
import {Sequelize, literal, Op} from 'sequelize';
describe("nextCheckInDate", () => {
describe('nextCheckInDate', () => {
beforeEach(() => {
vi.useFakeTimers(); // Tell vitest to use fake timers
});
afterEach(() => {
vi.useRealTimers(); // Reset date after test runs
});
it("Returns 9AM if called before 9AM that day", () => {
it('Returns 9AM if called before 9AM that day', () => {
const now = new Date(Date.now());
let at9AM = new Date(
now.getFullYear(),
@@ -30,7 +30,7 @@ describe("nextCheckInDate", () => {
);
expect(nextCheckInDate()).toEqual(at9AM);
});
it("Returns 9AM tomorrow if called after 9AM", () => {
it('Returns 9AM tomorrow if called after 9AM', () => {
const dayInMS = 24 * 60 * 60 * 1000;
const now = new Date(Date.now());
const tomorrow = new Date(Date.now() + dayInMS);
@@ -48,14 +48,14 @@ describe("nextCheckInDate", () => {
});
});
describe("Finding nags without check-ins", async () => {
const sequelize = new Sequelize("sqlite://:memory:");
describe('Finding nags without check-ins', async () => {
const sequelize = new Sequelize('sqlite://:memory:');
const exampleNag = {
userId: "1234",
guildId: "1234",
channelId: "1234",
messageId: "1234",
text: "Example nag 1",
userId: '1234',
guildId: '1234',
channelId: '1234',
messageId: '1234',
text: 'Example nag 1',
mentionHere: false,
};
@@ -71,17 +71,17 @@ describe("Finding nags without check-ins", async () => {
vi.useRealTimers();
});
it("Finds nags without any check-ins", async () => {
it('Finds nags without any check-ins', async () => {
const now = new Date();
vi.setSystemTime(
new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9),
);
await Nag.create(exampleNag);
const results = await findGuiltyNags();
expect(results.map((nag) => nag.userId)).toEqual(["1234"]);
expect(results.map(nag => nag.userId)).toEqual(['1234']);
});
it("Ignores nags with a recent check-in", async () => {
it('Ignores nags with a recent check-in', async () => {
const newNag = await Nag.create(exampleNag);
newNag.save();
const currentCheckInTime = getCheckIn(9, 0);
@@ -92,6 +92,6 @@ describe("Finding nags without check-ins", async () => {
});
newCheckIn.save();
const results = await findGuiltyNags();
expect(results.map((nag) => nag.userId)).toEqual([]);
expect(results.map(nag => nag.userId)).toEqual([]);
});
});

View File

@@ -1,4 +1,4 @@
import { type Client, TextChannel } from "discord.js";
import {type Client, TextChannel} from 'discord.js';
import {
type Sequelize,
Model,
@@ -8,7 +8,7 @@ import {
DATE,
literal,
Op,
} from "sequelize";
} from 'sequelize';
export interface Settings {
client: Client; // Main Discord client object
@@ -36,7 +36,6 @@ export class Nag extends Model {
}
export class CheckIn extends Model {
declare nagId: string;
// Date of the last time user ran /checkin
declare lastCheckIn: Date;
}
@@ -68,10 +67,6 @@ export async function initAndSyncTables(sequelize: Sequelize) {
);
CheckIn.init(
{
nagId: {
type: INTEGER,
allowNull: false,
},
lastCheckIn: {
type: DATE,
allowNull: false,
@@ -79,7 +74,8 @@ export async function initAndSyncTables(sequelize: Sequelize) {
},
{sequelize},
);
CheckIn.hasOne(Nag, { foreignKey: "nagId" });
Nag.hasMany(CheckIn);
CheckIn.belongsTo(Nag);
await Nag.sync();
await CheckIn.sync();
}
@@ -103,13 +99,13 @@ export function getCheckIn(hour: number, offset: number = 0) {
}
export async function findGuiltyNags() {
const results = await Nag.findAll({ where: {} });
const results = await Nag.findAll();
const guiltyNags: Nag[] = [];
const prevCheckIn = getCheckIn(9, -1);
const currentCheckIn = getCheckIn(9, 0);
for (const nag of results) {
console.log("Checking nag: ", nag.id);
console.log('Checking nag: ', nag.id);
const checkInResults = await CheckIn.findAll({
where: {
nagId: nag.id,
@@ -144,7 +140,7 @@ function nextCheckInMs() {
const delayMs = nextCheckInDate().getTime() - Date.now();
if (delayMs <= 0) {
// The value of nextCheckInDate is guaranteed to be in the future; if not, that's a bug in the program.
throw Error("Invalid value for nextCheckInDate");
throw Error('Invalid value for nextCheckInDate');
}
return delayMs;
}
@@ -163,6 +159,7 @@ export class Manager {
constructor(settings: Settings) {
this.settings = settings;
initAndSyncTables(this.settings.db);
}
start() {
@@ -194,11 +191,11 @@ export class Manager {
const failText =
nag.failText ??
`<@${nag.userId}> didn't complete "${nag.text}". Shame shame!`;
const mentionHere = nag.mentionHere ? "<@here> " : "";
const mentionHere = nag.mentionHere ? '<@here> ' : '';
const msg = `${mentionHere}${failText}`;
await channel.send(msg);
} catch (error) {
console.log("Error while creating Nag:", error); // TODO
console.log('Error while creating Nag:', error); // TODO
}
}
@@ -208,7 +205,7 @@ export class Manager {
// that isn't running anymore.
this.interval = undefined;
console.debug("nag.js main loop");
console.debug('nag.js main loop');
const guiltyNags = await findGuiltyNags();
for (const nag of guiltyNags) {
await this.triggerNag(nag);

View File

@@ -1,13 +1,13 @@
import {
type ChatInputCommandInteraction,
SlashCommandBuilder,
} from "discord.js";
} from 'discord.js';
import { type Settings, Nag } from "./service";
import {type Settings, Nag} from './service';
const data = new SlashCommandBuilder()
.setName("unnag")
.setDescription("Remove a nag");
.setName('unnag')
.setDescription('Remove a nag');
async function initialize(settings: Settings) {}

View File

@@ -1,11 +1,11 @@
import type { Interaction } from "discord.js";
import { Client, Events, GatewayIntentBits, MessageFlags } from "discord.js";
import type {Interaction} from 'discord.js';
import {Client, Events, GatewayIntentBits, MessageFlags} from 'discord.js';
import type {
SlashCommandBuilder,
SlashCommandOptionsOnlyBuilder,
} from "discord.js";
} from 'discord.js';
import { sql, GuildSetting, initDb } from "./database";
import {sql, GuildSetting, initDb} from './database';
const BLITZCRANK_BANNER = `
****++++++++++*+++
@@ -71,9 +71,9 @@ const client = new Client({
],
});
import { Routes } from "discord.js";
import { guildId, appId, token, remindersChannelId } from "./config.json";
import { REST } from "discord.js";
import {Routes} from 'discord.js';
import {guildId, appId, token, remindersChannelId} from './config.json';
import {REST} from 'discord.js';
const rest = new REST();
rest.setToken(token);
@@ -84,29 +84,57 @@ interface Command {
initialize: (any) => Promise<void>;
}
import { Collection } from "discord.js";
import {Collection} from 'discord.js';
const commands = new Collection<string, Command>();
import PingCommand from "./commands/calendar/ping";
import RemindCommand from "./commands/calendar/remind";
import QuoteCommand from "./commands/quotes/quote";
import NagCommand from "./commands/calendar/nag/nag";
import UnnagCommand from "./commands/calendar/nag/unnag";
import CheckinCommand from "./commands/calendar/nag/checkin";
import PingCommand from './commands/calendar/ping';
import RemindCommand from './commands/calendar/remind';
import QuoteCommand from './commands/quotes/quote';
import NagCommand from './commands/calendar/nag/nag';
import UnnagCommand from './commands/calendar/nag/unnag';
import CheckinCommand from './commands/calendar/nag/checkin';
import {Manager} from './commands/calendar/nag/service';
const nagManager = new Manager({
client: client,
db: sql,
});
nagManager.start();
console.debug(`${remindersChannelId}`);
commands.set("ping", PingCommand({ client: client, db: sql }));
commands.set('ping', PingCommand({client: client, db: sql}));
commands.set(
"remind",
'remind',
RemindCommand({
client: client,
db: sql,
publicChannel: remindersChannelId,
responseMode: "public",
responseMode: 'public',
}),
);
commands.set('quote', QuoteCommand({}));
commands.set(
'nag',
NagCommand({
client: client,
db: sql,
}),
);
commands.set(
'unnag',
UnnagCommand({
client: client,
db: sql,
}),
);
commands.set(
'checkin',
CheckinCommand({
client: client,
db: sql,
}),
);
commands.set("quote", QuoteCommand({}));
async function syncCommands() {
try {
@@ -114,7 +142,7 @@ async function syncCommands() {
const _data = await rest.put(
Routes.applicationGuildCommands(appId, guildId),
{
body: commands.mapValues((cmd) => cmd.data.toJSON()),
body: commands.mapValues(cmd => cmd.data.toJSON()),
},
);
console.log(`Successfully reloaded slash commands`);
@@ -138,7 +166,7 @@ client.on(Events.InteractionCreate, async (interaction: Interaction) => {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: "There was an error while executing this command",
content: 'There was an error while executing this command',
flags: MessageFlags.Ephemeral,
});
}
@@ -146,7 +174,7 @@ client.on(Events.InteractionCreate, async (interaction: Interaction) => {
// TODO
});
client.once(Events.ClientReady, async (readyClient) => {
client.once(Events.ClientReady, async readyClient => {
await syncCommands();
initDb(); // TODO
GuildSetting.sync(); // TODO
@@ -158,7 +186,7 @@ client.once(Events.ClientReady, async (readyClient) => {
});
}
// Print banner
for (const ln of BLITZCRANK_BANNER.split("\n")) {
for (const ln of BLITZCRANK_BANNER.split('\n')) {
console.log(ln);
}
console.log(`Logged in as ${readyClient.user.tag}`);