Compare commits
28 Commits
anniversar
...
5046fe91ba
| Author | SHA1 | Date | |
|---|---|---|---|
| 5046fe91ba | |||
| 2df9279c1b | |||
| 60097b9a1d | |||
| efedea8c45 | |||
| fb3f659831 | |||
| fceefcc667 | |||
| f17cdb12c0 | |||
| 1b3b498723 | |||
| 6fabb20a2c | |||
| 53c496422e | |||
| 7ca4b47ba9 | |||
| bbfb3bfae1 | |||
| 81c1ce886b | |||
| 2cc35f659e | |||
| 52f12ffac7 | |||
| 53ac0f4b79 | |||
| de9767f0bf | |||
| 745e709bef | |||
| e5933aacc2 | |||
| 333f3d94bf | |||
| 00210a03cf | |||
| 2e4147abec | |||
| fbdcef7bca | |||
| f29abd9df4 | |||
| f55bd3d98a | |||
| e957444000 | |||
| a1c22295f6 | |||
| 4e1ec14272 |
6
.dockerignore
Normal file
6
.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules
|
||||||
|
npm-debug.log
|
||||||
|
data/*.db
|
||||||
|
config.json
|
||||||
|
.git
|
||||||
|
.env
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ node_modules/
|
|||||||
config.json
|
config.json
|
||||||
old/
|
old/
|
||||||
bot.log
|
bot.log
|
||||||
|
data/
|
||||||
|
|||||||
30
Dockerfile
Normal file
30
Dockerfile
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Use Node.js 20 LTS as the base image
|
||||||
|
FROM node:20-slim
|
||||||
|
|
||||||
|
# Install dependencies needed for better-sqlite3 (if prebuilt binaries fail)
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
python3 \
|
||||||
|
make \
|
||||||
|
g++ \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Set the working directory
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm install --omit=dev
|
||||||
|
|
||||||
|
# Copy the rest of the application code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Create the data directory for the database
|
||||||
|
RUN mkdir -p data
|
||||||
|
|
||||||
|
# The bot uses config.json. In Docker, we'll likely mount this or use env vars,
|
||||||
|
# but for now, we ensure the structure is there.
|
||||||
|
|
||||||
|
# Command to run the bot
|
||||||
|
CMD [ "node", "main.js" ]
|
||||||
170
commands/receipts/receiptCommands.js
Normal file
170
commands/receipts/receiptCommands.js
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
category: 'utility',
|
||||||
|
global: true,
|
||||||
|
data: new SlashCommandBuilder()
|
||||||
|
.setName('budget')
|
||||||
|
.setDescription('The thing')
|
||||||
|
.addSubcommand(subcommand =>
|
||||||
|
subcommand
|
||||||
|
.setName('set')
|
||||||
|
.setDescription('Set weekly budget')
|
||||||
|
.addIntegerOption(option =>
|
||||||
|
option.setName('amount')
|
||||||
|
.setRequired(true)
|
||||||
|
.setDescription('Amount as int'))
|
||||||
|
.addBooleanOption(option =>
|
||||||
|
option.setName('override')
|
||||||
|
.setRequired(false)
|
||||||
|
.setDescription('Override budget of current period'))
|
||||||
|
)
|
||||||
|
.addSubcommand(subcommand =>
|
||||||
|
subcommand
|
||||||
|
.setName('view')
|
||||||
|
.setDescription('View your grocery spendings for the current or previous week')
|
||||||
|
.addUserOption(option =>
|
||||||
|
option.setName('user')
|
||||||
|
.setRequired(false)
|
||||||
|
.setDescription('User to view budget for'))
|
||||||
|
.addBooleanOption(option =>
|
||||||
|
option
|
||||||
|
.setName('lastweek')
|
||||||
|
.setDescription('Show spendings from the previous budget cycle instead of the current one')
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.addSubcommand(subcommand =>
|
||||||
|
subcommand
|
||||||
|
.setName('stats')
|
||||||
|
.setDescription('View detailed spending and savings statistics')
|
||||||
|
.addUserOption(option =>
|
||||||
|
option.setName('user')
|
||||||
|
.setRequired(false)
|
||||||
|
.setDescription('User to view stats for'))
|
||||||
|
),
|
||||||
|
async execute(interaction) {
|
||||||
|
console.log('budget command entrypoint');
|
||||||
|
let db = await interaction.client.localDB;
|
||||||
|
let targetUser = interaction.options.getUser('user') ?? interaction.user;
|
||||||
|
let discordId = interaction.member.id;
|
||||||
|
console.log(db, discordId);
|
||||||
|
let allowed = ['372115788498468864', '222457277708369928'].includes(discordId);
|
||||||
|
console.log(allowed);
|
||||||
|
if (!allowed) {
|
||||||
|
console.log('budget command denied');
|
||||||
|
await interaction.reply('This command may only be invoked by Miffy!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(`Switcching on sub ${interaction.options.getSubcommand()}`);
|
||||||
|
switch (interaction.options.getSubcommand()) {
|
||||||
|
case 'set':
|
||||||
|
console.log('budget command set');
|
||||||
|
let override = interaction.options.getBoolean('override') ?? false;
|
||||||
|
let budget = interaction.options.get('amount').value;
|
||||||
|
db.prepare(`INSERT OR REPLACE INTO bot_config (id, weekly_budget) VALUES (1, ?)`).run(budget);
|
||||||
|
if (override) {
|
||||||
|
db.prepare(`
|
||||||
|
UPDATE weekly_budgets
|
||||||
|
SET budget_amount = ?
|
||||||
|
WHERE id = (
|
||||||
|
SELECT id FROM weekly_budgets
|
||||||
|
WHERE date('now', 'localtime') BETWEEN start_date AND end_date
|
||||||
|
ORDER BY id DESC
|
||||||
|
LIMIT 1
|
||||||
|
)`).run(budget);
|
||||||
|
|
||||||
|
}
|
||||||
|
await interaction.reply(`Budget set for ${targetUser.username} to ${Number(budget).toFixed(2)}.`);
|
||||||
|
break;
|
||||||
|
case 'view':
|
||||||
|
const lastWeek = interaction.options.getBoolean('lastweek') ?? false;
|
||||||
|
const currentBudget = db.prepare(`
|
||||||
|
SELECT id, budget_amount, exchange_rate, start_date, end_date
|
||||||
|
FROM weekly_budgets
|
||||||
|
WHERE ${lastWeek ? "start_date < date('now', 'localtime')" : "date('now', 'localtime') BETWEEN start_date AND end_date"}
|
||||||
|
ORDER BY start_date DESC
|
||||||
|
LIMIT 1
|
||||||
|
`).get();
|
||||||
|
|
||||||
|
if (!currentBudget) {
|
||||||
|
await interaction.reply("No budget period found.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userSpendings = db.prepare(`
|
||||||
|
SELECT amount, message_raw
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE budget_id = ? AND discord_id = ?
|
||||||
|
`).all(currentBudget.id, targetUser.id);
|
||||||
|
|
||||||
|
const totalSpentEur = userSpendings.reduce((acc, s) => {
|
||||||
|
return acc + s.amount;
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
const remainingEur = currentBudget.budget_amount - totalSpentEur;
|
||||||
|
const remainingSek = remainingEur * currentBudget.exchange_rate;
|
||||||
|
|
||||||
|
const todayTimestamp = Math.floor(Date.now() / 1000);
|
||||||
|
const endTimestamp = Math.floor(new Date(`${currentBudget.end_date}T23:59:59`).getTime() / 1000);
|
||||||
|
|
||||||
|
const budgetEmbed = new EmbedBuilder()
|
||||||
|
.setColor(remainingEur > 0 ? 0x00ff00 : 0xff0000)
|
||||||
|
.setTitle(`${targetUser.globalName ?? targetUser.username} Budget as of <t:${todayTimestamp}:F>`)
|
||||||
|
.setDescription(`Period: \`${currentBudget.start_date}\` to \`${currentBudget.end_date}\`\nReset <t:${endTimestamp}:R>`)
|
||||||
|
.addFields(
|
||||||
|
{ name: 'Spent', value: `${totalSpentEur.toFixed(2)} €\n${(totalSpentEur * currentBudget.exchange_rate).toFixed(2)} kr`, inline: true },
|
||||||
|
{ name: 'Remaining', value: `${remainingEur.toFixed(2)} €\n${remainingSek.toFixed(2)} kr`, inline: true },
|
||||||
|
)
|
||||||
|
.setFooter({ text: `Exchange rate this week: 1 € = ${currentBudget.exchange_rate.toFixed(2)} kr` })
|
||||||
|
.setTimestamp();
|
||||||
|
|
||||||
|
await interaction.reply({ embeds: [budgetEmbed] });
|
||||||
|
break
|
||||||
|
case 'stats':
|
||||||
|
const allBudgets = db.prepare(`
|
||||||
|
SELECT id, budget_amount, exchange_rate, start_date, end_date
|
||||||
|
FROM weekly_budgets
|
||||||
|
ORDER BY start_date DESC
|
||||||
|
LIMIT 4
|
||||||
|
`).all();
|
||||||
|
|
||||||
|
let statsDescription = "";
|
||||||
|
let cumulativeSavingsEur = 0;
|
||||||
|
|
||||||
|
for (const budgetPeriod of allBudgets) {
|
||||||
|
const periodSpendings = db.prepare(`
|
||||||
|
SELECT amount
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE budget_id = ? AND discord_id = ?
|
||||||
|
`).all(budgetPeriod.id, targetUser.id);
|
||||||
|
|
||||||
|
const totalSpentInPeriodEur = periodSpendings.reduce((acc, s) => acc + s.amount, 0);
|
||||||
|
const savedInPeriodEur = budgetPeriod.budget_amount - totalSpentInPeriodEur;
|
||||||
|
cumulativeSavingsEur += savedInPeriodEur;
|
||||||
|
|
||||||
|
statsDescription += `**Period: ${budgetPeriod.start_date} - ${budgetPeriod.end_date}**\n`;
|
||||||
|
statsDescription += `Budget: ${budgetPeriod.budget_amount.toFixed(2)}€\n`;
|
||||||
|
statsDescription += `Spent: ${totalSpentInPeriodEur.toFixed(2)}€ (${(totalSpentInPeriodEur * budgetPeriod.exchange_rate).toFixed(2)} kr)\n`;
|
||||||
|
statsDescription += `Saved: ${savedInPeriodEur.toFixed(2)}€ (${(savedInPeriodEur * budgetPeriod.exchange_rate).toFixed(2)} kr)\n`;
|
||||||
|
statsDescription += `Cumulative: ${cumulativeSavingsEur.toFixed(2)}€\n\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allBudgets.length === 0) {
|
||||||
|
statsDescription = "No budget periods on record.";
|
||||||
|
}
|
||||||
|
|
||||||
|
const statsEmbed = new EmbedBuilder()
|
||||||
|
.setColor(0x0099ff)
|
||||||
|
.setTitle(`${targetUser.globalName ?? targetUser.username}'s Budget Statistics`)
|
||||||
|
.setDescription(statsDescription)
|
||||||
|
.setTimestamp();
|
||||||
|
|
||||||
|
await interaction.reply({ embeds: [statsEmbed] });
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
await interaction.reply(`Sub mismatch. Switching on ${interaction.options.getSubcommand()}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -63,7 +63,7 @@ module.exports = {
|
|||||||
|
|
||||||
collector.on('collect', m => {
|
collector.on('collect', m => {
|
||||||
m.stickers.forEach(sticker => {
|
m.stickers.forEach(sticker => {
|
||||||
stickers.push(`https://media.discordapp.net/stickers/${sticker.id}.png`);
|
stickers.push(`https://media.discordapp.net/stickers/${sticker.id}.png?size=1024`);
|
||||||
collector.stop();
|
collector.stop();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -41,10 +41,6 @@ module.exports = {
|
|||||||
option.setName('songname')
|
option.setName('songname')
|
||||||
.setDescription('Override song name, otherwise uses name from Spotify')
|
.setDescription('Override song name, otherwise uses name from Spotify')
|
||||||
.setRequired(false))
|
.setRequired(false))
|
||||||
.addStringOption(option =>
|
|
||||||
option.setName('footer_override')
|
|
||||||
.setDescription('Custom footer')
|
|
||||||
.setRequired(false))
|
|
||||||
.addAttachmentOption(option =>
|
.addAttachmentOption(option =>
|
||||||
option.setName('cover_override')
|
option.setName('cover_override')
|
||||||
.setDescription('Uses this image instead of Spotofy metadata')
|
.setDescription('Uses this image instead of Spotofy metadata')
|
||||||
@@ -54,6 +50,7 @@ module.exports = {
|
|||||||
clientSecret: spotify.clientSecret,
|
clientSecret: spotify.clientSecret,
|
||||||
}),
|
}),
|
||||||
async execute(interaction) {
|
async execute(interaction) {
|
||||||
|
try {
|
||||||
let token = await this.spotifyAPI.clientCredentialsGrant().then(
|
let token = await this.spotifyAPI.clientCredentialsGrant().then(
|
||||||
function(data) {
|
function(data) {
|
||||||
return data.body['access_token'];
|
return data.body['access_token'];
|
||||||
@@ -97,12 +94,20 @@ module.exports = {
|
|||||||
links.push(`[<:ytbm:1224704771248750622> Youtube ](${url})`);
|
links.push(`[<:ytbm:1224704771248750622> Youtube ](${url})`);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (url.startsWith('https://jelly.')) {
|
||||||
|
links.push(`[<:jelly:1225931843279519905> Jellyfin (${url.split('.')[1]}) ](${url})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (url.startsWith('https://soundcloud.com/') || url.startsWith('https://m.soundcloud.com/')) {
|
||||||
|
links.push(`[<:soundcld:1225702702135119902> Soundcloud ](${url})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if(spotifyID) {
|
if(spotifyID) {
|
||||||
let spotifyTrack = await this.spotifyAPI.getTrack(spotifyID);
|
let spotifyTrack = await this.spotifyAPI.getTrack(spotifyID);
|
||||||
trackEmbed.setImage(spotifyTrack['body'].album.images[0].url);
|
trackEmbed.setThumbnail(spotifyTrack['body'].album.images[0].url);
|
||||||
songName = spotifyTrack['body'].name;
|
songName = spotifyTrack['body'].name;
|
||||||
mainArtist = spotifyTrack['body'].artists[0].name;
|
mainArtist = spotifyTrack['body'].artists[0].name;
|
||||||
artists = spotifyTrack['body'].artists.map(a => a.name).join(', ');
|
artists = spotifyTrack['body'].artists.map(a => a.name).join(', ');
|
||||||
@@ -111,7 +116,7 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(interaction.options.getAttachment('cover_override')) {
|
if(interaction.options.getAttachment('cover_override')) {
|
||||||
trackEmbed.setImage(interaction.options.getAttachment('cover_override').url);
|
trackEmbed.setThumbnail(interaction.options.getAttachment('cover_override').url);
|
||||||
}
|
}
|
||||||
songName = interaction.options.getString('songname', false) ?? songName;
|
songName = interaction.options.getString('songname', false) ?? songName;
|
||||||
artists = interaction.options.getString('artist', false) ?? artists;
|
artists = interaction.options.getString('artist', false) ?? artists;
|
||||||
@@ -122,12 +127,11 @@ module.exports = {
|
|||||||
trackEmbed.setTitle(`${title}`);
|
trackEmbed.setTitle(`${title}`);
|
||||||
|
|
||||||
let submitterName = interaction.member.displayName;
|
let submitterName = interaction.member.displayName;
|
||||||
let footer = interaction.options.getString('footer_override', false) ?? `Submitted by ${submitterName}`;
|
let footer = `Submitted by ${submitterName} `;
|
||||||
trackEmbed.setFooter({text: footer });
|
|
||||||
|
|
||||||
if(interaction.options.getString('rating', false)) {
|
if(interaction.options.getString('rating', false)) {
|
||||||
trackEmbed.addFields(
|
trackEmbed.addFields(
|
||||||
{ name: `${submitterName} rated this`, value: `${interaction.options.getString('rating', false)} out of 10`, inline: true },
|
{ name: `${submitterName} rated this`, value: `${interaction.options.getString('rating', false)} out of **10**`, inline: true },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +142,7 @@ module.exports = {
|
|||||||
|
|
||||||
if(interaction.options.getInteger('scrobbles', false) || lfmData.data['track']?.['userplaycount'] > 0) {
|
if(interaction.options.getInteger('scrobbles', false) || lfmData.data['track']?.['userplaycount'] > 0) {
|
||||||
trackEmbed.addFields(
|
trackEmbed.addFields(
|
||||||
{ name: `${submitterName} scrobbled this`, value: `${interaction.options.getInteger('scrobbles', false) ?? lfmData.data['track']['userplaycount']} times so far`, inline: true },
|
{ name: `${submitterName} scrobbled this`, value: `**${interaction.options.getInteger('scrobbles', false) ?? lfmData.data['track']['userplaycount']}** times so far`, inline: true },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,28 +152,23 @@ module.exports = {
|
|||||||
console.log(tags);
|
console.log(tags);
|
||||||
let listeners = this.numToHumanReadable(lfmData.data['track']['listeners']);
|
let listeners = this.numToHumanReadable(lfmData.data['track']['listeners']);
|
||||||
let globalScrobbles = this.numToHumanReadable(lfmData.data['track']['playcount']);
|
let globalScrobbles = this.numToHumanReadable(lfmData.data['track']['playcount']);
|
||||||
|
footer += `∘ Listeners: ${listeners} • Scrobbles: ${globalScrobbles}`;
|
||||||
|
|
||||||
trackEmbed.addFields(
|
let tagContent = '';
|
||||||
{ name: `LFM Global`, value: `Listeners: ${listeners} • Scrobbles: ${globalScrobbles}\n`, inline: false },
|
|
||||||
)
|
|
||||||
|
|
||||||
let tagHeader = 'Tags';
|
|
||||||
if(tags.length === 0) {
|
if(tags.length === 0) {
|
||||||
//artist tag fallback
|
//artist tag fallback
|
||||||
let lfmArtistTags = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=artist.getTopTags&api_key=${lfmKey}&artist=${mainArtist}&format=json`);
|
let lfmArtistTags = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=artist.getTopTags&api_key=${lfmKey}&artist=${mainArtist}&format=json`);
|
||||||
console.log(lfmArtistTags);
|
console.log(lfmArtistTags);
|
||||||
tags = lfmArtistTags.data['toptags']['tag'].map(a => a.name);
|
tags = lfmArtistTags.data['toptags']['tag'].map(a => a.name);
|
||||||
tagHeader = `Artist ${tagHeader}`;
|
|
||||||
}
|
}
|
||||||
if(tags) {
|
if(tags.length > 1) {
|
||||||
tags = this.joinLineBreak(tags, ', ', 4);
|
tags = this.joinLineBreak(tags, ', ', 3);
|
||||||
trackEmbed.addFields(
|
trackEmbed.addFields(
|
||||||
{ name: `${tagHeader}`, value: `${tags.substr(0,60)}${tags.length > 60 ? '...' : ''}`, inline: true },
|
{ name: `Tags`, value: `${tags.substr(0,60)}${tags.length > 60 ? '...' : ''}`, inline: true },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
description = `${description}\n${this.joinLineBreak(links, ' ∘ ', 3)}`
|
}
|
||||||
|
|
||||||
if(!description) {
|
if(!description) {
|
||||||
await interaction.reply({content: 'Sorry, no valid link has bee supplied.', ephemeral: true });
|
await interaction.reply({content: 'Sorry, no valid link has bee supplied.', ephemeral: true });
|
||||||
@@ -177,11 +176,20 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
trackEmbed.setDescription(description);
|
trackEmbed.setDescription(description);
|
||||||
|
trackEmbed.addFields(
|
||||||
|
{ name: 'Links', value: `${this.joinLineBreak(links, ' ∘ ', 4)}` }
|
||||||
|
);
|
||||||
|
|
||||||
|
trackEmbed.setFooter({text: footer });
|
||||||
|
|
||||||
interaction.channel.send({ embeds: [trackEmbed] });
|
interaction.channel.send({ embeds: [trackEmbed] });
|
||||||
|
|
||||||
let response = await interaction.reply({content: 'done', ephemeral: true});
|
let response = await interaction.reply({content: 'done', ephemeral: true});
|
||||||
await response.delete();
|
await response.delete();
|
||||||
|
} catch (error) {
|
||||||
|
await interaction.reply(`# FUCK \n ${JSON.stringify(error)}`.substring(0,200));
|
||||||
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
numToHumanReadable: function(num) {
|
numToHumanReadable: function(num) {
|
||||||
if (num > 1000000 ) {
|
if (num > 1000000 ) {
|
||||||
|
|||||||
56
core/db.js
56
core/db.js
@@ -1,39 +1,33 @@
|
|||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const sqlite3 = require("sqlite3").verbose();
|
const Database = require("better-sqlite3");
|
||||||
const { open } = require('sqlite');
|
const path = require("path");
|
||||||
|
const { Umzug, JSONStorage } = require('umzug');
|
||||||
const filepath = "./data/minzbot.db";
|
const filepath = "./data/minzbot.db";
|
||||||
|
|
||||||
async function createDbConnection() {
|
async function createDbConnection() {
|
||||||
if (fs.existsSync(filepath)) {
|
const dir = path.dirname(filepath);
|
||||||
//new sqlite3.Database(filepath);
|
if (!fs.existsSync(dir)) {
|
||||||
const db = await open({filename: filepath, driver: sqlite3.Database});
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
await initDB(db);
|
|
||||||
return db;
|
|
||||||
} else {
|
|
||||||
const db = await open({filename: filepath, driver: sqlite3.Database});
|
|
||||||
await initDB(db);
|
|
||||||
console.log("[DATABASE] Connection with SQLite has been established");
|
|
||||||
return db;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function initDB(db) {
|
const db = new Database(filepath, { verbose: console.log });
|
||||||
await db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS anniversaries (
|
await runMigrations(db);
|
||||||
ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name VARCHAR(50) NOT NULL,
|
console.log("[DATABASE] Connection with better-sqlite3 established");
|
||||||
guild_id TEXT NOT NULL,
|
return db;
|
||||||
discord_id VARCHAR(50) NOT NULL,
|
|
||||||
last_anniversary_notification TEXT
|
|
||||||
);
|
|
||||||
`);
|
|
||||||
await db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS lastfm (
|
|
||||||
discord_id TEXT PRIMARY KEY NOT NULL,
|
|
||||||
lastfm_name TEXT
|
|
||||||
);
|
|
||||||
`);
|
|
||||||
console.log('[DATABASE] Created new DB table');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = createDbConnection();
|
async function runMigrations(db) {
|
||||||
|
const umzug = new Umzug({
|
||||||
|
migrations: { glob: 'migrations/*.js' },
|
||||||
|
context: db,
|
||||||
|
storage: new JSONStorage({ path: './data/migrations.json' }),
|
||||||
|
logger: console,
|
||||||
|
});
|
||||||
|
|
||||||
|
await umzug.up();
|
||||||
|
console.log('[DATABASE] Migrations applied successfully');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = createDbConnection;
|
||||||
8
core/utils.js
Normal file
8
core/utils.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
module.exports = {
|
||||||
|
formatDate (date) {
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(date.getDate()).padStart(2, '0');
|
||||||
|
return `${year}-${month}-${day}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,14 +36,14 @@ const rest = new REST().setToken(token);
|
|||||||
// and deploy your commands!
|
// and deploy your commands!
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
console.log(`[GUILD] Started refreshing ${guildCommands.length} application (/) commands.`);
|
console.log(`[GUILD] Started refreshing ${guildCommands.length} Guild (/) commands.`);
|
||||||
|
|
||||||
let data = await rest.put(
|
let data = await rest.put(
|
||||||
Routes.applicationGuildCommands(clientId, guildId),
|
Routes.applicationGuildCommands(clientId, guildId),
|
||||||
{ body: guildCommands },
|
{ body: guildCommands },
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(`[GUILD] Successfully reloaded ${data.length} application (/) commands.`);
|
console.log(`[GUILD] Successfully reloaded ${data.length} Guild (/) commands.`);
|
||||||
|
|
||||||
console.log(`[GLOBAL] Started refreshing ${globalCommands.length} application (/) commands.`);
|
console.log(`[GLOBAL] Started refreshing ${globalCommands.length} application (/) commands.`);
|
||||||
|
|
||||||
|
|||||||
10
docker-compose.yml
Normal file
10
docker-compose.yml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
services:
|
||||||
|
minzbot:
|
||||||
|
build: .
|
||||||
|
container_name: minzbot
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./config.json:/usr/src/app/config.json:ro
|
||||||
|
- ./data:/usr/src/app/data
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
105
events/receiptsMessageCreate.js
Normal file
105
events/receiptsMessageCreate.js
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
const { Events, channelLink, discordSort } = require('discord.js');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
name: Events.MessageCreate,
|
||||||
|
async execute(message) {
|
||||||
|
if (message.author.bot) return;
|
||||||
|
|
||||||
|
const receiptsChannelId = process.env.NODE_ENV === 'development' ? '1468186493251227658' : '1462060674766344370';
|
||||||
|
if(message.channel.id === receiptsChannelId) {
|
||||||
|
const CURRENCY_MAP = {
|
||||||
|
"222457277708369928": "EUR", // Minz
|
||||||
|
"372115788498468864": "SEK", // Miffy
|
||||||
|
};
|
||||||
|
|
||||||
|
let reply = "";
|
||||||
|
let db = await message.client.localDB;
|
||||||
|
const receiptsChannel = message.channel;
|
||||||
|
const authorId = message.author.id;
|
||||||
|
|
||||||
|
|
||||||
|
const currentBudget = db.prepare(`
|
||||||
|
SELECT id, exchange_rate, budget_amount FROM weekly_budgets
|
||||||
|
WHERE date('now', 'localtime') BETWEEN start_date AND end_date
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
`).get();
|
||||||
|
|
||||||
|
if (message.content === "fuck") {
|
||||||
|
|
||||||
|
let lastSpend = db.prepare(`
|
||||||
|
SELECT id, amount, message_raw, created_at
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE discord_id = ? AND budget_id = ?
|
||||||
|
ORDER BY created_at DESC, id DESC
|
||||||
|
LIMIT 1
|
||||||
|
`).get(authorId, currentBudget.id);
|
||||||
|
if (lastSpend) {
|
||||||
|
db.prepare(`DELETE FROM grocery_spendings WHERE id = ?`).run(lastSpend.id);
|
||||||
|
await message.reply(`Your last spending of ${lastSpend.amount.toFixed(2)}€ has been deleted.`);
|
||||||
|
} else {
|
||||||
|
await message.reply("You don't have any entries within the current budgeting period!");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let matches = [];
|
||||||
|
let lines = message.content.split("\n");
|
||||||
|
let additionalSpent = 0.0;
|
||||||
|
lines.forEach(line => {0
|
||||||
|
if (line.startsWith('-')) {
|
||||||
|
console.log(`Matching on line ${line}`);
|
||||||
|
const regex = /-(?=[0-9])([0-9]*[.,]?[0-9]*)/m;
|
||||||
|
let match = regex.exec(line)
|
||||||
|
console.log(match);
|
||||||
|
if (match) {
|
||||||
|
additionalSpent = additionalSpent + parseFloat(match[1].replace(',', '.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
if (additionalSpent > 0) {
|
||||||
|
|
||||||
|
|
||||||
|
const currency = CURRENCY_MAP[authorId] || "EUR"
|
||||||
|
switch (currency) {
|
||||||
|
case "SEK":
|
||||||
|
additionalSpent = additionalSpent / currentBudget.exchange_rate;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare(`
|
||||||
|
INSERT INTO grocery_spendings (
|
||||||
|
discord_id,
|
||||||
|
message_id,
|
||||||
|
message_raw,
|
||||||
|
amount,
|
||||||
|
budget_id
|
||||||
|
) VALUES (?, ?, ?, ?, ?)
|
||||||
|
`).run(
|
||||||
|
authorId,
|
||||||
|
message.id,
|
||||||
|
message.content,
|
||||||
|
additionalSpent,
|
||||||
|
currentBudget.id
|
||||||
|
);
|
||||||
|
|
||||||
|
const allSpendings = db.prepare(`
|
||||||
|
SELECT amount
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE budget_id = ? AND discord_id = ?
|
||||||
|
`).all(currentBudget.id, authorId);
|
||||||
|
|
||||||
|
const totalSpent = allSpendings.reduce((acc, entry) => {
|
||||||
|
return acc + entry.amount;
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
reply = `${message.author.globalName} spent ${additionalSpent.toFixed(2)}€ / ${(additionalSpent * currentBudget.exchange_rate).toFixed(2)} kr of their budget.\nThey have ${(currentBudget.budget_amount - totalSpent).toFixed(2)}€ / ${((currentBudget.budget_amount - totalSpent) * currentBudget.exchange_rate).toFixed(2)} kr remaining.`;
|
||||||
|
await message.reply(reply);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
8
main.js
8
main.js
@@ -2,8 +2,11 @@ const fs = require('node:fs');
|
|||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { Client, Collection, Events, GatewayIntentBits, Options, Partials } = require('discord.js');
|
const { Client, Collection, Events, GatewayIntentBits, Options, Partials } = require('discord.js');
|
||||||
const { token } = require('./config.json');
|
const { token } = require('./config.json');
|
||||||
|
const createDbConnection = require('./core/db.js');
|
||||||
|
|
||||||
const localDB = require('./core/db');
|
|
||||||
|
async function entrypoint() {
|
||||||
|
const localDB = await createDbConnection();
|
||||||
|
|
||||||
const client = new Client({
|
const client = new Client({
|
||||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessageReactions],
|
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessageReactions],
|
||||||
@@ -64,3 +67,6 @@ client.on(Events.ClientReady, () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
client.login(token);
|
client.login(token);
|
||||||
|
};
|
||||||
|
|
||||||
|
entrypoint();
|
||||||
|
|||||||
61
migrations/00_initial_schema.js
Normal file
61
migrations/00_initial_schema.js
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
module.exports = {
|
||||||
|
up: async ({ context: db }) => {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS anniversaries (
|
||||||
|
ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name VARCHAR(50) NOT NULL,
|
||||||
|
guild_id TEXT NOT NULL,
|
||||||
|
discord_id VARCHAR(50) NOT NULL,
|
||||||
|
last_anniversary_notification TEXT
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS lastfm (
|
||||||
|
discord_id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
lastfm_name TEXT
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS bot_config (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
weekly_budget REAL DEFAULT 0,
|
||||||
|
last_date_msg_receipts DATE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS weekly_budgets (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
start_date DATE NOT NULL,
|
||||||
|
end_date DATE NOT NULL,
|
||||||
|
budget_amount DECIMAL(10, 2) NOT NULL,
|
||||||
|
exchange_rate DECIMAL(10, 6) NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT date_check CHECK (end_date > start_date)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_budget_dates ON weekly_budgets (start_date, end_date);`);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS grocery_spendings (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
discord_id VARCHAR(50) NOT NULL,
|
||||||
|
message_id VARCHAR(50) NOT NULL,
|
||||||
|
message_raw TEXT DEFAULT "-",
|
||||||
|
amount DECIMAL(10, 2) NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
budget_id INTEGER,
|
||||||
|
FOREIGN KEY (budget_id) REFERENCES weekly_budgets(id)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`
|
||||||
|
INSERT OR IGNORE INTO bot_config (id, weekly_budget)
|
||||||
|
VALUES (1, 10);
|
||||||
|
`);
|
||||||
|
},
|
||||||
|
down: async ({ context: db }) => {
|
||||||
|
db.exec(`DROP TABLE IF EXISTS grocery_spendings;`);
|
||||||
|
db.exec(`DROP TABLE IF EXISTS weekly_budgets;`);
|
||||||
|
db.exec(`DROP TABLE IF EXISTS bot_config;`);
|
||||||
|
db.exec(`DROP TABLE IF EXISTS lastfm;`);
|
||||||
|
db.exec(`DROP TABLE IF EXISTS anniversaries;`);
|
||||||
|
}
|
||||||
|
};
|
||||||
1400
package-lock.json
generated
1400
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,20 @@
|
|||||||
{
|
{
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.6.8",
|
"axios": "^1.6.8",
|
||||||
|
"better-sqlite3": "^12.6.2",
|
||||||
"discord.js": "^14.13.0",
|
"discord.js": "^14.13.0",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"spotify-web-api-node": "^5.0.2",
|
"spotify-web-api-node": "^5.0.2",
|
||||||
"sqlite": "^5.1.1",
|
"sqlite": "^5.1.1",
|
||||||
"sqlite3": "^5.1.7"
|
"umzug": "^3.8.2"
|
||||||
},
|
},
|
||||||
"name": "minzbot",
|
"name": "minzbot",
|
||||||
"description": "Successor of the Discord.py implementation",
|
"description": "Successor of the Discord.py implementation",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
|
"backup": "node scripts/backup.js"
|
||||||
},
|
},
|
||||||
"author": "Minz💕",
|
"author": "Minz💕",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
|
|||||||
25
scripts/backup.js
Normal file
25
scripts/backup.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const dbPath = path.join(__dirname, '../data/minzbot.db');
|
||||||
|
const backupDir = path.join(__dirname, '../data/backups');
|
||||||
|
|
||||||
|
if (!fs.existsSync(backupDir)) {
|
||||||
|
fs.mkdirSync(backupDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
|
const backupPath = path.join(backupDir, `${timestamp}_minzbot.db`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(dbPath)) {
|
||||||
|
fs.copyFileSync(dbPath, backupPath);
|
||||||
|
console.log(`Backup successful: ${backupPath}`);
|
||||||
|
} else {
|
||||||
|
console.error(`Database file not found at ${dbPath}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Backup failed:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ module.exports = {
|
|||||||
animeList: ["K-On!", "Spice and Wolf", "Bakemonogatari", "Your Lie in April", "Noragami", "Puella Magi Madoka Magica", "Akame ga Kill!", "Steins;Gate", "\u3086\u308b\u30ad\u30e3\u30f3\u25b3"]
|
animeList: ["K-On!", "Spice and Wolf", "Bakemonogatari", "Your Lie in April", "Noragami", "Puella Magi Madoka Magica", "Akame ga Kill!", "Steins;Gate", "\u3086\u308b\u30ad\u30e3\u30f3\u25b3"]
|
||||||
},
|
},
|
||||||
async tick(client, timer) {
|
async tick(client, timer) {
|
||||||
|
return;
|
||||||
client.user.setActivity(timer.data.animeList[timer.data.statusIndex], { type: ActivityType.Watching });
|
client.user.setActivity(timer.data.animeList[timer.data.statusIndex], { type: ActivityType.Watching });
|
||||||
timer.data.statusIndex = (timer.data.statusIndex + 1) % timer.data.animeList.length
|
timer.data.statusIndex = (timer.data.statusIndex + 1) % timer.data.animeList.length
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,9 +8,6 @@ module.exports = {
|
|||||||
const keepMessageEmoteId = '1214140438265724980';
|
const keepMessageEmoteId = '1214140438265724980';
|
||||||
const channelConfigs = [
|
const channelConfigs = [
|
||||||
{ channelId: '1214134516247957504', keepTimeMinutes: 2, keepAttachment: true }, //toho-test/mnzbot-test
|
{ channelId: '1214134516247957504', keepTimeMinutes: 2, keepAttachment: true }, //toho-test/mnzbot-test
|
||||||
{ channelId: '1111054421091155978', keepTimeMinutes: 2880 }, //cotr/Spam
|
|
||||||
{ channelId: '1170190197384814762', keepTimeMinutes: 2880, keepAttachment: true }, //cotr/Red
|
|
||||||
{ channelId: '1101703550070947920', keepTimeMinutes: 2880, keepAttachment: true }, //cotr/Memes
|
|
||||||
];
|
];
|
||||||
function isMessageLocked(message) {
|
function isMessageLocked(message) {
|
||||||
for (const [id, reaction] of message.reactions.cache) {
|
for (const [id, reaction] of message.reactions.cache) {
|
||||||
@@ -22,7 +19,9 @@ module.exports = {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
for (let i = 0; i < channelConfigs.length; i++) {
|
for (let i = 0; i < channelConfigs.length; i++) {
|
||||||
|
try {
|
||||||
const config = channelConfigs[i];
|
const config = channelConfigs[i];
|
||||||
const channel = await client.channels.fetch(config.channelId);
|
const channel = await client.channels.fetch(config.channelId);
|
||||||
|
|
||||||
@@ -50,6 +49,9 @@ module.exports = {
|
|||||||
message.delete();
|
message.delete();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`[CLEANUP] Failed for ${channelConfigs[i].channelId}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
131
timers/receiptTimer.js
Normal file
131
timers/receiptTimer.js
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
const { formatDate } = require('../core/utils.js');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
timeout: 10000,
|
||||||
|
immediate: true,
|
||||||
|
name: 'Receipt Day Announcements',
|
||||||
|
data: {
|
||||||
|
channelId: process.env.NODE_ENV === 'development' ? '1468186493251227658' : '1462060674766344370',
|
||||||
|
targetHour: 0,
|
||||||
|
targetMinute: 1
|
||||||
|
},
|
||||||
|
async tick(client, timer) {
|
||||||
|
|
||||||
|
//format date because isostring is utc duh
|
||||||
|
try {
|
||||||
|
const today = new Date();
|
||||||
|
const lastMonday = new Date(today);
|
||||||
|
lastMonday.setDate(today.getDate() - ((today.getDay() === 0) ? 6 : today.getDay() - 1));
|
||||||
|
const startDate = formatDate(lastMonday);
|
||||||
|
|
||||||
|
const nextSunday = new Date(lastMonday);
|
||||||
|
nextSunday.setDate(lastMonday.getDate() + 6);
|
||||||
|
const endDate = formatDate(nextSunday);
|
||||||
|
// 0 1 2 3 4 5 6
|
||||||
|
// S M T W T F S
|
||||||
|
let db = await client.localDB;
|
||||||
|
const channel = await client.channels.fetch(timer.data.channelId);
|
||||||
|
|
||||||
|
const config = await (await db.prepare(`SELECT weekly_budget, last_date_msg_receipts FROM bot_config`).get());
|
||||||
|
const existingBudget = db.prepare(`SELECT id FROM weekly_budgets WHERE start_date = ?`).get(startDate);
|
||||||
|
|
||||||
|
if (!existingBudget) {
|
||||||
|
await channel.send(`Format date last monday ${lastMonday} as startDate Format date next sunday ${nextSunday} as endDate`);
|
||||||
|
await channel.send(`\`\`\`SELECT id FROM weekly_budgets WHERE start_date = ${startDate}\`\`\`
|
||||||
|
${JSON.stringify(existingBudget)}`);
|
||||||
|
console.log(`No budget found for week starting ${startDate}.`);
|
||||||
|
const response = await fetch(`https://api.frankfurter.dev/v1/latest?amount=1&from=EUR&to=SEK`);
|
||||||
|
|
||||||
|
|
||||||
|
if (!response.ok) await channel.send(`Failed to fetch exchange rate:\n${response.statusText}`);
|
||||||
|
const data = await response.json();
|
||||||
|
//await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`);
|
||||||
|
await channel.send(`Reset weekly budget to ${config.weekly_budget.toFixed(2)}€ / ${(config.weekly_budget * data.rates.SEK).toFixed(2)} kr`);
|
||||||
|
|
||||||
|
|
||||||
|
db.prepare(`
|
||||||
|
INSERT INTO weekly_budgets (start_date, end_date, budget_amount, exchange_rate)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
`).run(startDate, endDate, config.weekly_budget, data.rates.SEK);
|
||||||
|
|
||||||
|
await channel.send(`\`\`\`INSERT INTO weekly_budgets (start_date, end_date, budget_amount, exchange_rate)
|
||||||
|
VALUES (${startDate}, ${endDate}, ${config.weekly_budget}, ${data.rates.SEK})\`\`\``);
|
||||||
|
} else {
|
||||||
|
console.log(`budget found for week starting ${startDate}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const notification = db.prepare(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM bot_config
|
||||||
|
WHERE date(last_date_msg_receipts, 'localtime') = date('now', 'localtime')
|
||||||
|
) as was_sent_today
|
||||||
|
`).get();
|
||||||
|
|
||||||
|
const debug = db.prepare(`
|
||||||
|
SELECT
|
||||||
|
date(last_date_msg_receipts, 'localtime') AS last_date,
|
||||||
|
datetime('now', 'localtime') AS current_time_full,
|
||||||
|
(date(last_date_msg_receipts, 'localtime') = date('now', 'localtime')) AS was_sent_today
|
||||||
|
FROM bot_config
|
||||||
|
LIMIT 1;
|
||||||
|
`).get();
|
||||||
|
|
||||||
|
|
||||||
|
if (!notification.was_sent_today) {
|
||||||
|
await channel.send(`\`\`\`SELECT
|
||||||
|
date(last_date_msg_receipts, 'localtime') AS last_date,
|
||||||
|
datetime('now', 'localtime') AS current_time_full,
|
||||||
|
(date(last_date_msg_receipts, 'localtime') = date('now', 'localtime')) AS was_sent_today
|
||||||
|
FROM bot_config
|
||||||
|
LIMIT 1;\`\`\`
|
||||||
|
|
||||||
|
${JSON.stringify(debug)}`);
|
||||||
|
const currentDate = new Date().toLocaleDateString('en-GB', {
|
||||||
|
weekday: 'long',
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric'
|
||||||
|
});
|
||||||
|
await channel.send(`${currentDate}`);
|
||||||
|
console.log("No notification today, sending...");
|
||||||
|
db.prepare(`
|
||||||
|
UPDATE bot_config
|
||||||
|
SET last_date_msg_receipts = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = 1
|
||||||
|
`).run();
|
||||||
|
} else {
|
||||||
|
console.log("Notification already sent");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[TIMER] Error:', error);
|
||||||
|
} finally {
|
||||||
|
// 2. Schedule the NEXT tick manually
|
||||||
|
await this.scheduleNext(client, timer);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async scheduleNext(client, timer) {
|
||||||
|
const now = new Date();
|
||||||
|
const next = new Date();
|
||||||
|
|
||||||
|
next.setHours(timer.data.targetHour, timer.data.targetMinute, 0, 0);
|
||||||
|
|
||||||
|
if (next <= now) {
|
||||||
|
next.setDate(next.getDate() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const delay = next.getTime() - now.getTime();
|
||||||
|
|
||||||
|
if (timer.instance) clearTimeout(timer.instance);
|
||||||
|
|
||||||
|
timer.instance = setTimeout(() => {
|
||||||
|
this.tick(client, timer);
|
||||||
|
}, delay);
|
||||||
|
|
||||||
|
const channel = await client.channels.fetch(timer.data.channelId);
|
||||||
|
//if (channel) await channel.send(`Next message scheduled for: ${next.toLocaleString()} with ms delta of ${delay} / ${delay/3600000}`);
|
||||||
|
console.log(`[TIMER] Next message scheduled for: ${next.toLocaleString()}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user