-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
268 lines (238 loc) · 8.89 KB
/
index.js
File metadata and controls
268 lines (238 loc) · 8.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import {
Client,
GatewayIntentBits,
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
Collection,
SlashCommandBuilder
} from 'discord.js';
import { MessageFlags } from 'discord-api-types/v10';
import { setTimeout as wait } from 'timers/promises';
import fs from 'fs/promises';
import dotenv from 'dotenv';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import winston from 'winston';
dotenv.config();
// Logger setup with Winston
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => `${timestamp} [${level.toUpperCase()}] ${message}`)
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'bot.log' })
]
});
if (!process.env.DISCORD_TOKEN) {
logger.error('❌ Discord token is missing. Check your .env file.');
process.exit(1);
}
// Read config once
const config = JSON.parse(
await fs.readFile(new URL('./config.json', import.meta.url))
);
// Database initialization
let db;
async function initDb() {
db = await open({
filename: './data/reminders.sqlite',
driver: sqlite3.Database
});
await db.exec(`
CREATE TABLE IF NOT EXISTS reminder (
id INTEGER PRIMARY KEY CHECK (id = 1),
next_timestamp INTEGER
)
`);
}
// Minimal required intents
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers
]
});
client.commands = new Collection();
let reminderController = null;
let nextReminderTimestamp = null;
// Slash command setup
const taskCommand = new SlashCommandBuilder()
.setName('task')
.setDescription('Manage the bump reminder task')
.addStringOption(option =>
option
.setName('action')
.setDescription('What should happen?')
.setRequired(true)
.addChoices(
{ name: 'status', value: 'status' },
{ name: 'cancel', value: 'cancel' },
{ name: 'test (1 min)', value: 'test' }
)
);
client.commands.set(taskCommand.name, {
data: taskCommand,
async execute(interaction) {
const lang = config.language?.toLowerCase() || interaction.locale?.toLowerCase() || 'en';
const texts = config[`texts_${lang}`] || config.texts_en;
if (interaction.user.id !== config.ownerId) {
return interaction.reply({ content: texts.taskNoPermission, flags: MessageFlags.Ephemeral });
}
const action = interaction.options.getString('action');
if (action === 'status') {
if (!nextReminderTimestamp) {
return interaction.reply({ content: texts.taskStatusNone, flags: MessageFlags.Ephemeral });
}
const msLeft = nextReminderTimestamp - Date.now();
const minutes = Math.floor(msLeft / 60000);
const seconds = Math.floor((msLeft % 60000) / 1000);
const message = texts.taskStatusText
.replace('{minutes}', minutes)
.replace('{seconds}', seconds);
return interaction.reply({ content: message, flags: MessageFlags.Ephemeral });
}
if (action === 'cancel') {
if (cancelReminder()) {
return interaction.reply({ content: texts.taskCanceled, flags: MessageFlags.Ephemeral });
} else {
return interaction.reply({ content: texts.taskAlreadyCanceled, flags: MessageFlags.Ephemeral });
}
}
if (action === 'test') {
await interaction.reply({ content: texts.taskTestStart, flags: MessageFlags.Ephemeral });
scheduleReminder(1, texts);
}
}
});
client.once('ready', async () => {
logger.info(`✅ Logged in as ${client.user.tag}`);
// Register slash commands
const { REST, Routes } = await import('discord.js');
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
await rest.put(
Routes.applicationGuildCommands(config.clientId, config.guildId),
{ body: [taskCommand.toJSON()] }
);
logger.info('📎 Slash command /task registered');
// Initialize DB and resume any pending reminder
await initDb();
const row = await db.get('SELECT next_timestamp FROM reminder WHERE id = 1');
if (row?.next_timestamp && row.next_timestamp > Date.now()) {
const minutesLeft = Math.ceil((row.next_timestamp - Date.now()) / 60000);
const lang = config.language?.toLowerCase() || 'en';
const texts = config[`texts_${lang}`] || config.texts_en;
logger.info(`🔄 Resuming reminder in ${minutesLeft} minute(s)`);
scheduleReminder(minutesLeft, texts);
}
});
// Rate limit handling
client.on('rateLimit', (info) => {
logger.warn(`Rate limited: ${JSON.stringify(info)}`);
});
client.on('messageCreate', async (message) => {
if (
message.author.bot &&
(!Array.isArray(config.allowedBotIds) || config.allowedBotIds.includes(message.author.id)) &&
message.interaction?.commandName === 'bump' &&
(!config.allowedChannelId || message.channelId === config.allowedChannelId)
) {
if (!reminderController) {
logger.info(`/bump detected from ${message.author.tag}`);
const lang = config.language?.toLowerCase() || message.interaction.locale?.toLowerCase() || 'en';
const texts = config[`texts_${lang}`] || config.texts_en;
scheduleReminder(120, texts);
} else {
logger.info('⏳ Reminder already running – ignored.');
}
}
});
client.on('interactionCreate', async interaction => {
const lang = config.language?.toLowerCase() || interaction.locale?.toLowerCase() || 'en';
const texts = config[`texts_${lang}`] || config.texts_en;
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (command) await command.execute(interaction);
}
if (interaction.isButton() && interaction.customId === 'toggleReminderRole') {
if (!config.mentionRole) return interaction.reply({ content: texts.roleDisabled, flags: MessageFlags.Ephemeral });
const member = await interaction.guild.members.fetch(interaction.user.id);
const role = interaction.guild.roles.cache.get(config.roleId);
if (!role) return interaction.reply({ content: texts.roleNotFound, flags: MessageFlags.Ephemeral });
try {
if (member.roles.cache.has(role.id)) {
await member.roles.remove(role);
await interaction.reply({ content: texts.roleRemoved, flags: MessageFlags.Ephemeral });
} else {
await member.roles.add(role);
await interaction.reply({ content: texts.roleAdded, flags: MessageFlags.Ephemeral });
}
} catch (err) {
logger.error(`Role change error: ${err}`);
await interaction.reply({ content: texts.roleChangeError, flags: MessageFlags.Ephemeral });
}
}
});
async function scheduleReminder(minutes = 120, texts) {
if (reminderController) return;
const controller = new AbortController();
reminderController = controller;
nextReminderTimestamp = Date.now() + minutes * 60000;
// Persist to DB
await db.run(
'INSERT INTO reminder (id, next_timestamp) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET next_timestamp=excluded.next_timestamp',
nextReminderTimestamp
);
logger.info(`⏳ Reminder scheduled in ${minutes} minute(s)`);
try {
await wait(minutes * 60000, null, { signal: controller.signal });
const channel = await client.channels.fetch(config.channelId);
const roleMention = config.mentionRole ? `<@&${config.roleId}>` : '';
const embed = new EmbedBuilder()
.setTitle(texts.embedTitle)
.setDescription(texts.embedDescription)
.setColor(0x00AEFF)
.setTimestamp();
const components = config.showButton
? [new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('toggleReminderRole')
.setLabel(texts.buttonLabel)
.setStyle(ButtonStyle.Primary)
)]
: [];
await channel.send({ content: roleMention, embeds: [embed], components });
logger.info('📤 Reminder sent');
} catch (err) {
if (err.name === 'AbortError') logger.info('❌ Reminder canceled');
else logger.error(`❌ Error in reminder schedule: ${err}`);
} finally {
reminderController = null;
nextReminderTimestamp = null;
await db.run('DELETE FROM reminder WHERE id = 1');
}
}
function cancelReminder() {
if (reminderController) {
reminderController.abort();
return true;
}
return false;
}
// Graceful shutdown
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down...`);
if (reminderController) cancelReminder();
await db.close();
client.destroy();
process.exit(0);
}
client.login(process.env.DISCORD_TOKEN);