Compare commits
10 Commits
anniversar
...
e5933aacc2
| Author | SHA1 | Date | |
|---|---|---|---|
| e5933aacc2 | |||
| 333f3d94bf | |||
| 00210a03cf | |||
| 2e4147abec | |||
| fbdcef7bca | |||
| f29abd9df4 | |||
| f55bd3d98a | |||
| e957444000 | |||
| a1c22295f6 | |||
| 4e1ec14272 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ node_modules/
|
|||||||
config.json
|
config.json
|
||||||
old/
|
old/
|
||||||
bot.log
|
bot.log
|
||||||
|
data/
|
||||||
|
|||||||
@@ -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,134 +50,146 @@ module.exports = {
|
|||||||
clientSecret: spotify.clientSecret,
|
clientSecret: spotify.clientSecret,
|
||||||
}),
|
}),
|
||||||
async execute(interaction) {
|
async execute(interaction) {
|
||||||
let token = await this.spotifyAPI.clientCredentialsGrant().then(
|
try {
|
||||||
function(data) {
|
let token = await this.spotifyAPI.clientCredentialsGrant().then(
|
||||||
return data.body['access_token'];
|
function(data) {
|
||||||
});
|
return data.body['access_token'];
|
||||||
await this.spotifyAPI.setAccessToken(token);
|
});
|
||||||
|
await this.spotifyAPI.setAccessToken(token);
|
||||||
let urls = interaction.options.getString('links', true).split(" ");
|
|
||||||
|
let urls = interaction.options.getString('links', true).split(" ");
|
||||||
let title = ' ';
|
|
||||||
let description = ' ';
|
let title = ' ';
|
||||||
let spotifyID = null;
|
let description = ' ';
|
||||||
let artists = '';
|
let spotifyID = null;
|
||||||
let songName = '';
|
let artists = '';
|
||||||
let mainArtist = '';
|
let songName = '';
|
||||||
|
let mainArtist = '';
|
||||||
const trackEmbed = new EmbedBuilder()
|
|
||||||
.setColor(Math.floor(Math.random() * 16777214) + 1)
|
const trackEmbed = new EmbedBuilder()
|
||||||
.setDescription(`asdasdasda`)
|
.setColor(Math.floor(Math.random() * 16777214) + 1)
|
||||||
.setTimestamp();
|
.setDescription(`asdasdasda`)
|
||||||
|
.setTimestamp();
|
||||||
let links = [];
|
|
||||||
for (let index = 0; index < urls.length; index++) {
|
let links = [];
|
||||||
let url = urls[index];
|
for (let index = 0; index < urls.length; index++) {
|
||||||
|
let url = urls[index];
|
||||||
if (url.startsWith('https://listen.minzkraut.com/')) {
|
|
||||||
links.push(`[<:drmoe:1220702607836839956> Navidrome ](${url})`);
|
if (url.startsWith('https://listen.minzkraut.com/')) {
|
||||||
continue;
|
links.push(`[<:drmoe:1220702607836839956> Navidrome ](${url})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (url.startsWith('https://open.spotify.com/')) {
|
||||||
|
url = url.split('?')[0];
|
||||||
|
links.push(`[<:sptfy:1224677302109995078> Spotify ](${url})`);
|
||||||
|
//https://open.spotify.com/track/4FuOHRPC3ZIQ7VQd7KMbds?si=cadd634ea5a14689
|
||||||
|
spotifyID = url.split('/').pop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (url.startsWith('https://listen.tidal.com/')) {
|
||||||
|
links.push(`[<:tidal:1221732946525032498> Tidal ](${url})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (url.startsWith('https://www.youtube.com/')) {
|
||||||
|
links.push(`[<:ytbm:1224704771248750622> Youtube ](${url})`);
|
||||||
|
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 (url.startsWith('https://open.spotify.com/')) {
|
|
||||||
url = url.split('?')[0];
|
|
||||||
links.push(`[<:sptfy:1224677302109995078> Spotify ](${url})`);
|
if(spotifyID) {
|
||||||
//https://open.spotify.com/track/4FuOHRPC3ZIQ7VQd7KMbds?si=cadd634ea5a14689
|
let spotifyTrack = await this.spotifyAPI.getTrack(spotifyID);
|
||||||
spotifyID = url.split('/').pop();
|
trackEmbed.setThumbnail(spotifyTrack['body'].album.images[0].url);
|
||||||
continue;
|
songName = spotifyTrack['body'].name;
|
||||||
|
mainArtist = spotifyTrack['body'].artists[0].name;
|
||||||
|
artists = spotifyTrack['body'].artists.map(a => a.name).join(', ');
|
||||||
|
let releaseDate = new Date(spotifyTrack['body'].album.release_date).toDateString();
|
||||||
|
description = `From the album **${spotifyTrack['body'].album.name}**\nReleased **${releaseDate}**\n\n` + description;
|
||||||
}
|
}
|
||||||
if (url.startsWith('https://listen.tidal.com/')) {
|
|
||||||
links.push(`[<:tidal:1221732946525032498> Tidal ](${url})`);
|
if(interaction.options.getAttachment('cover_override')) {
|
||||||
continue;
|
trackEmbed.setThumbnail(interaction.options.getAttachment('cover_override').url);
|
||||||
}
|
}
|
||||||
if (url.startsWith('https://www.youtube.com/')) {
|
songName = interaction.options.getString('songname', false) ?? songName;
|
||||||
links.push(`[<:ytbm:1224704771248750622> Youtube ](${url})`);
|
artists = interaction.options.getString('artist', false) ?? artists;
|
||||||
continue;
|
mainArtist = interaction.options.getString('artist', false) ?? mainArtist;
|
||||||
}
|
|
||||||
}
|
title = `${songName} - ${artists}`;
|
||||||
|
|
||||||
|
trackEmbed.setTitle(`${title}`);
|
||||||
if(spotifyID) {
|
|
||||||
let spotifyTrack = await this.spotifyAPI.getTrack(spotifyID);
|
let submitterName = interaction.member.displayName;
|
||||||
trackEmbed.setImage(spotifyTrack['body'].album.images[0].url);
|
let footer = `Submitted by ${submitterName} `;
|
||||||
songName = spotifyTrack['body'].name;
|
|
||||||
mainArtist = spotifyTrack['body'].artists[0].name;
|
if(interaction.options.getString('rating', false)) {
|
||||||
artists = spotifyTrack['body'].artists.map(a => a.name).join(', ');
|
|
||||||
let releaseDate = new Date(spotifyTrack['body'].album.release_date).toDateString();
|
|
||||||
description = `From the album **${spotifyTrack['body'].album.name}**\nReleased **${releaseDate}**\n\n` + description;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(interaction.options.getAttachment('cover_override')) {
|
|
||||||
trackEmbed.setImage(interaction.options.getAttachment('cover_override').url);
|
|
||||||
}
|
|
||||||
songName = interaction.options.getString('songname', false) ?? songName;
|
|
||||||
artists = interaction.options.getString('artist', false) ?? artists;
|
|
||||||
mainArtist = interaction.options.getString('artist', false) ?? mainArtist;
|
|
||||||
|
|
||||||
title = `${songName} - ${artists}`;
|
|
||||||
|
|
||||||
trackEmbed.setTitle(`${title}`);
|
|
||||||
|
|
||||||
let submitterName = interaction.member.displayName;
|
|
||||||
let footer = interaction.options.getString('footer_override', false) ?? `Submitted by ${submitterName}`;
|
|
||||||
trackEmbed.setFooter({text: footer });
|
|
||||||
|
|
||||||
if(interaction.options.getString('rating', false)) {
|
|
||||||
trackEmbed.addFields(
|
|
||||||
{ name: `${submitterName} rated this`, value: `${interaction.options.getString('rating', false)} out of 10`, inline: true },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let db = await interaction.client.localDB;
|
|
||||||
let dbResult = await db.get(`SELECT * FROM lastfm WHERE discord_id = ?`,[interaction.member.id]);
|
|
||||||
let lfmUsername = dbResult?.['lastfm_name'];
|
|
||||||
let lfmData = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=${lfmKey}&artist=${mainArtist}&track=${songName}&format=json&user=${lfmUsername}`);
|
|
||||||
|
|
||||||
if(interaction.options.getInteger('scrobbles', false) || lfmData.data['track']?.['userplaycount'] > 0) {
|
|
||||||
trackEmbed.addFields(
|
|
||||||
{ name: `${submitterName} scrobbled this`, value: `${interaction.options.getInteger('scrobbles', false) ?? lfmData.data['track']['userplaycount']} times so far`, inline: true },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if(lfmData.data['track']) {
|
|
||||||
links.push(`<:lfm:1225099203039203338> [View on LFM](${lfmData.data['track']['url']})`);
|
|
||||||
let tags = lfmData.data['track']['toptags']['tag'].map(a => a.name).filter(tag => tag.length >= 2);
|
|
||||||
console.log(tags);
|
|
||||||
let listeners = this.numToHumanReadable(lfmData.data['track']['listeners']);
|
|
||||||
let globalScrobbles = this.numToHumanReadable(lfmData.data['track']['playcount']);
|
|
||||||
|
|
||||||
trackEmbed.addFields(
|
|
||||||
{ name: `LFM Global`, value: `Listeners: ${listeners} • Scrobbles: ${globalScrobbles}\n`, inline: false },
|
|
||||||
)
|
|
||||||
|
|
||||||
let tagHeader = 'Tags';
|
|
||||||
if(tags.length === 0) {
|
|
||||||
//artist tag fallback
|
|
||||||
let lfmArtistTags = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=artist.getTopTags&api_key=${lfmKey}&artist=${mainArtist}&format=json`);
|
|
||||||
console.log(lfmArtistTags);
|
|
||||||
tags = lfmArtistTags.data['toptags']['tag'].map(a => a.name);
|
|
||||||
tagHeader = `Artist ${tagHeader}`;
|
|
||||||
}
|
|
||||||
if(tags) {
|
|
||||||
tags = this.joinLineBreak(tags, ', ', 4);
|
|
||||||
trackEmbed.addFields(
|
trackEmbed.addFields(
|
||||||
{ name: `${tagHeader}`, value: `${tags.substr(0,60)}${tags.length > 60 ? '...' : ''}`, inline: true },
|
{ name: `${submitterName} rated this`, value: `${interaction.options.getString('rating', false)} out of **10**`, inline: true },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let db = await interaction.client.localDB;
|
||||||
|
let dbResult = await db.get(`SELECT * FROM lastfm WHERE discord_id = ?`,[interaction.member.id]);
|
||||||
|
let lfmUsername = dbResult?.['lastfm_name'];
|
||||||
|
let lfmData = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=${lfmKey}&artist=${mainArtist}&track=${songName}&format=json&user=${lfmUsername}`);
|
||||||
|
|
||||||
|
if(interaction.options.getInteger('scrobbles', false) || lfmData.data['track']?.['userplaycount'] > 0) {
|
||||||
|
trackEmbed.addFields(
|
||||||
|
{ name: `${submitterName} scrobbled this`, value: `**${interaction.options.getInteger('scrobbles', false) ?? lfmData.data['track']['userplaycount']}** times so far`, inline: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if(lfmData.data['track']) {
|
||||||
|
links.push(`<:lfm:1225099203039203338> [View on LFM](${lfmData.data['track']['url']})`);
|
||||||
|
let tags = lfmData.data['track']['toptags']['tag'].map(a => a.name).filter(tag => tag.length >= 2);
|
||||||
|
console.log(tags);
|
||||||
|
let listeners = this.numToHumanReadable(lfmData.data['track']['listeners']);
|
||||||
|
let globalScrobbles = this.numToHumanReadable(lfmData.data['track']['playcount']);
|
||||||
|
footer += `∘ Listeners: ${listeners} • Scrobbles: ${globalScrobbles}`;
|
||||||
|
|
||||||
|
let tagContent = '';
|
||||||
|
if(tags.length === 0) {
|
||||||
|
//artist tag fallback
|
||||||
|
let lfmArtistTags = await axios.get(`https://ws.audioscrobbler.com/2.0/?method=artist.getTopTags&api_key=${lfmKey}&artist=${mainArtist}&format=json`);
|
||||||
|
console.log(lfmArtistTags);
|
||||||
|
tags = lfmArtistTags.data['toptags']['tag'].map(a => a.name);
|
||||||
|
}
|
||||||
|
if(tags.length > 1) {
|
||||||
|
tags = this.joinLineBreak(tags, ', ', 3);
|
||||||
|
trackEmbed.addFields(
|
||||||
|
{ name: `Tags`, value: `${tags.substr(0,60)}${tags.length > 60 ? '...' : ''}`, inline: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!description) {
|
||||||
|
await interaction.reply({content: 'Sorry, no valid link has bee supplied.', ephemeral: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
trackEmbed.setDescription(description);
|
||||||
|
trackEmbed.addFields(
|
||||||
|
{ name: 'Links', value: `${this.joinLineBreak(links, ' ∘ ', 4)}` }
|
||||||
|
);
|
||||||
|
|
||||||
|
trackEmbed.setFooter({text: footer });
|
||||||
|
|
||||||
|
interaction.channel.send({ embeds: [trackEmbed] });
|
||||||
|
|
||||||
|
let response = await interaction.reply({content: 'done', ephemeral: true});
|
||||||
|
await response.delete();
|
||||||
|
} catch (error) {
|
||||||
|
await interaction.reply(`# FUCK \n ${JSON.stringify(error)}`.substring(0,200));
|
||||||
}
|
}
|
||||||
|
|
||||||
description = `${description}\n${this.joinLineBreak(links, ' ∘ ', 3)}`
|
|
||||||
|
|
||||||
if(!description) {
|
|
||||||
await interaction.reply({content: 'Sorry, no valid link has bee supplied.', ephemeral: true });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
trackEmbed.setDescription(description);
|
|
||||||
|
|
||||||
interaction.channel.send({ embeds: [trackEmbed] });
|
|
||||||
|
|
||||||
let response = await interaction.reply({content: 'done', ephemeral: true});
|
|
||||||
await response.delete();
|
|
||||||
},
|
},
|
||||||
numToHumanReadable: function(num) {
|
numToHumanReadable: function(num) {
|
||||||
if (num > 1000000 ) {
|
if (num > 1000000 ) {
|
||||||
@@ -200,4 +208,4 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
return groupedArray.join('\n');
|
return groupedArray.join('\n');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
52
commands/utility/receiptCommands.js
Normal file
52
commands/utility/receiptCommands.js
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
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'))
|
||||||
|
)
|
||||||
|
.addSubcommand(subcommand =>
|
||||||
|
subcommand
|
||||||
|
.setName('show')
|
||||||
|
.setDescription('not implemented')
|
||||||
|
),
|
||||||
|
async execute(interaction) {
|
||||||
|
console.log('budget command entrypoint');
|
||||||
|
let db = await interaction.client.localDB;
|
||||||
|
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 budget = interaction.options.get('amount').value
|
||||||
|
db.prepare(`INSERT OR REPLACE INTO bot_config (id, weekly_budget) VALUES (1, ?)`).run(budget);
|
||||||
|
await interaction.reply(`Budget set to ${budget}`);
|
||||||
|
break;
|
||||||
|
case 'show':
|
||||||
|
console.log('budget command show');
|
||||||
|
await interaction.reply('Not implemented');
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
await interaction.reply(`Sub mismatch. Switching on ${interaction.options.getSubcommand()}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
47
core/db.js
47
core/db.js
@@ -1,20 +1,21 @@
|
|||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const sqlite3 = require("sqlite3").verbose();
|
const Database = require("better-sqlite3");
|
||||||
|
const path = require("path");
|
||||||
const { open } = require('sqlite');
|
const { open } = require('sqlite');
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const db = new Database(filepath, { verbose: console.log });
|
||||||
|
|
||||||
|
initDB(db);
|
||||||
|
|
||||||
|
console.log("[DATABASE] Connection with better-sqlite3 established");
|
||||||
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function initDB(db) {
|
async function initDB(db) {
|
||||||
@@ -33,7 +34,29 @@ async function initDB(db) {
|
|||||||
lastfm_name TEXT
|
lastfm_name TEXT
|
||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
|
await db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS bot_config (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
weekly_budget REAL DEFAULT 0,
|
||||||
|
exchange_rate_eur_kr REAL DEFAULT 0,
|
||||||
|
last_budget_notification_date TEXT
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
await db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS grocery_budgets (
|
||||||
|
ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
discord_id VARCHAR(50) NOT NULL,
|
||||||
|
budget_spent REAL,
|
||||||
|
total_spent REAL
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Optional: Initialize the row if it doesn't exist yet
|
||||||
|
await db.exec(`
|
||||||
|
INSERT OR IGNORE INTO bot_config (id, weekly_budget, last_budget_notification_date)
|
||||||
|
VALUES (1, 0, NULL);
|
||||||
|
`);
|
||||||
console.log('[DATABASE] Created new DB table');
|
console.log('[DATABASE] Created new DB table');
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = createDbConnection();
|
module.exports = createDbConnection;
|
||||||
@@ -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.`);
|
||||||
|
|
||||||
|
|||||||
46
events/receiptsMessageCreate.js
Normal file
46
events/receiptsMessageCreate.js
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
const { Events, channelLink, discordSort } = require('discord.js');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
name: Events.MessageCreate,
|
||||||
|
async execute(message) {
|
||||||
|
if (message.author.bot) return;
|
||||||
|
|
||||||
|
if(message.channel.id === '1462060674766344370') {
|
||||||
|
|
||||||
|
let reply = "";
|
||||||
|
let db = await message.client.localDB;
|
||||||
|
const receiptsChannel = message.channel;
|
||||||
|
const authorId = message.author.id;
|
||||||
|
|
||||||
|
let budgets = await db.prepare(`SELECT * FROM grocery_budgets WHERE discord_id = ?`).get(authorId);
|
||||||
|
let weeklyBudget = await (await db.prepare(`SELECT weekly_budget FROM bot_config`).get()).weekly_budget;
|
||||||
|
|
||||||
|
console.log(weeklyBudget, budgets);
|
||||||
|
if (budgets === undefined) {
|
||||||
|
console.log(`No budget row in db for ${authorId}`);
|
||||||
|
db.prepare(`INSERT OR REPLACE INTO grocery_budgets (discord_id, budget_spent, total_spent) VALUES (?,0,0)`).run(authorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
additionalSpent = additionalSpent + parseFloat(match[1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (additionalSpent > 0) {
|
||||||
|
db.prepare(`UPDATE grocery_budgets SET budget_spent = ?, total_spent = ? WHERE discord_id = ?`).run(budgets.budget_spent + additionalSpent, budgets.total_spent + additionalSpent, authorId);
|
||||||
|
let remainingBudget = weeklyBudget - (budgets.budget_spent + additionalSpent);
|
||||||
|
|
||||||
|
reply = `${message.author.globalName} spent ${additionalSpent} of their budget.\nThey have ${remainingBudget} remaining.`;
|
||||||
|
await receiptsChannel.send(reply);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
108
main.js
108
main.js
@@ -2,65 +2,71 @@ 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');
|
|
||||||
|
|
||||||
const client = new Client({
|
async function entrypoint() {
|
||||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessageReactions],
|
const localDB = await createDbConnection();
|
||||||
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
|
|
||||||
sweepers: {
|
const client = new Client({
|
||||||
...Options.DefaultSweeperSettings,
|
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessageReactions],
|
||||||
reactions: { interval: 300, filter: () => () => { return true } }
|
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
|
||||||
}
|
sweepers: {
|
||||||
});
|
...Options.DefaultSweeperSettings,
|
||||||
|
reactions: { interval: 300, filter: () => () => { return true } }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
client.localDB = localDB;
|
client.localDB = localDB;
|
||||||
client.commands = new Collection();
|
client.commands = new Collection();
|
||||||
const foldersPath = path.join(__dirname, 'commands');
|
const foldersPath = path.join(__dirname, 'commands');
|
||||||
const commandFolders = fs.readdirSync(foldersPath);
|
const commandFolders = fs.readdirSync(foldersPath);
|
||||||
|
|
||||||
for (const folder of commandFolders) {
|
for (const folder of commandFolders) {
|
||||||
const commandsPath = path.join(foldersPath, folder);
|
const commandsPath = path.join(foldersPath, folder);
|
||||||
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
|
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
|
||||||
for (const file of commandFiles) {
|
for (const file of commandFiles) {
|
||||||
const filePath = path.join(commandsPath, file);
|
const filePath = path.join(commandsPath, file);
|
||||||
const command = require(filePath);
|
const command = require(filePath);
|
||||||
if ('data' in command && 'execute' in command) {
|
if ('data' in command && 'execute' in command) {
|
||||||
client.commands.set(command.data.name, command);
|
client.commands.set(command.data.name, command);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const eventsPath = path.join(__dirname, 'events');
|
const eventsPath = path.join(__dirname, 'events');
|
||||||
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
|
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
|
||||||
|
|
||||||
for (const file of eventFiles) {
|
for (const file of eventFiles) {
|
||||||
const filePath = path.join(eventsPath, file);
|
const filePath = path.join(eventsPath, file);
|
||||||
const event = require(filePath);
|
const event = require(filePath);
|
||||||
if (event.once) {
|
if (event.once) {
|
||||||
client.once(event.name, (...args) => event.execute(...args));
|
client.once(event.name, (...args) => event.execute(...args));
|
||||||
} else {
|
} else {
|
||||||
console.log(`Registered event ${event.name} ${file}`);
|
console.log(`Registered event ${event.name} ${file}`);
|
||||||
client.on(event.name, (...args) => event.execute(...args));
|
client.on(event.name, (...args) => event.execute(...args));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
client.on(Events.ClientReady, () => {
|
client.on(Events.ClientReady, () => {
|
||||||
//setup timers
|
//setup timers
|
||||||
const timersPath = path.join(__dirname, 'timers');
|
const timersPath = path.join(__dirname, 'timers');
|
||||||
const timerFiles = fs.readdirSync(timersPath).filter(file => file.endsWith('.js'));
|
const timerFiles = fs.readdirSync(timersPath).filter(file => file.endsWith('.js'));
|
||||||
for (const file of timerFiles) {
|
for (const file of timerFiles) {
|
||||||
const filePath = path.join(timersPath, file);
|
const filePath = path.join(timersPath, file);
|
||||||
const timer = require(filePath);
|
const timer = require(filePath);
|
||||||
console.log(`Started Timer ${timer.name}`);
|
console.log(`Started Timer ${timer.name}`);
|
||||||
let timerInstance = setInterval(() => {
|
let timerInstance = setInterval(() => {
|
||||||
timer.tick(client, timer);
|
timer.tick(client, timer);
|
||||||
}, timer.timeout);
|
}, timer.timeout);
|
||||||
timer.instance = timerInstance;
|
timer.instance = timerInstance;
|
||||||
if (timer.immediate) { timer.tick(client, timer) }
|
if (timer.immediate) { timer.tick(client, timer) }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
client.login(token);
|
client.login(token);
|
||||||
|
};
|
||||||
|
|
||||||
|
entrypoint();
|
||||||
|
|||||||
1007
package-lock.json
generated
1007
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"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"
|
|
||||||
},
|
},
|
||||||
"name": "minzbot",
|
"name": "minzbot",
|
||||||
"description": "Successor of the Discord.py implementation",
|
"description": "Successor of the Discord.py implementation",
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
const { MessageActivityType } = require("discord.js");
|
const { MessageActivityType } = require("discord.js");
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
timeout: 60000,
|
timeout: 60000,
|
||||||
immediate: true,
|
immediate: true,
|
||||||
name: 'Cleanup tasks',
|
name: 'Cleanup tasks',
|
||||||
async tick(client, timer) {
|
async tick(client, timer) {
|
||||||
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
|
||||||
@@ -13,8 +13,8 @@ module.exports = {
|
|||||||
{ channelId: '1101703550070947920', keepTimeMinutes: 2880, keepAttachment: true }, //cotr/Memes
|
{ 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) {
|
||||||
if(id === keepMessageEmoteId) {
|
if (id === keepMessageEmoteId) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,34 +22,39 @@ module.exports = {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < channelConfigs.length; i++) {
|
|
||||||
const config = channelConfigs[i];
|
|
||||||
const channel = await client.channels.fetch(config.channelId);
|
|
||||||
|
|
||||||
console.log(`[TIMER] Running cleanup task for ${channel.guild.name}/${channel.name}`);
|
|
||||||
channel.messages.fetch({ limit: 100 }).then(messages => {
|
|
||||||
messages.forEach(message => {
|
|
||||||
if(isMessageLocked(message)) {
|
|
||||||
//skip if message has mnzboKeepMessage reaction
|
|
||||||
console.log(`[LOCKED] [${message.guild.name}/${message.channel.name}] | ${message.author.globalName}: ${message.content}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(message.attachments.size > 0 && config.keepAttachment) {
|
for (let i = 0; i < channelConfigs.length; i++) {
|
||||||
//Skip messages with attachment
|
try {
|
||||||
return;
|
const config = channelConfigs[i];
|
||||||
}
|
const channel = await client.channels.fetch(config.channelId);
|
||||||
|
|
||||||
let ageInMinutes = Math.ceil((Date.now() - message.createdTimestamp) / 1000 / 60);
|
console.log(`[TIMER] Running cleanup task for ${channel.guild.name}/${channel.name}`);
|
||||||
if(ageInMinutes < config.keepTimeMinutes) {
|
channel.messages.fetch({ limit: 100 }).then(messages => {
|
||||||
//Skip messages posted within last 48 Hours
|
messages.forEach(message => {
|
||||||
return;
|
if (isMessageLocked(message)) {
|
||||||
}
|
//skip if message has mnzboKeepMessage reaction
|
||||||
|
console.log(`[LOCKED] [${message.guild.name}/${message.channel.name}] | ${message.author.globalName}: ${message.content}`);
|
||||||
console.log(`[CLEANUP] [${message.guild.name}/${message.channel.name}] | ${message.author.globalName}: ${message.content}`);
|
return;
|
||||||
message.delete();
|
}
|
||||||
|
|
||||||
|
if (message.attachments.size > 0 && config.keepAttachment) {
|
||||||
|
//Skip messages with attachment
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ageInMinutes = Math.ceil((Date.now() - message.createdTimestamp) / 1000 / 60);
|
||||||
|
if (ageInMinutes < config.keepTimeMinutes) {
|
||||||
|
//Skip messages posted within last 48 Hours
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[CLEANUP] [${message.guild.name}/${message.channel.name}] | ${message.author.globalName}: ${message.content}`);
|
||||||
|
message.delete();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
} catch (error) {
|
||||||
|
console.log(`[CLEANUP] Failed for ${channelConfigs[i].channelId}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
64
timers/receiptTimer.js
Normal file
64
timers/receiptTimer.js
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
module.exports = {
|
||||||
|
timeout: 1000,
|
||||||
|
immediate: false,
|
||||||
|
name: 'Receipt Day Announcements',
|
||||||
|
data: {
|
||||||
|
channelId: '1462060674766344370',
|
||||||
|
targetHour: 0,
|
||||||
|
targetMinute: 1
|
||||||
|
},
|
||||||
|
async tick(client, timer) {
|
||||||
|
try {
|
||||||
|
// 1. Send the message
|
||||||
|
const currentDate = new Date().toLocaleDateString('en-GB', {
|
||||||
|
weekday: 'long',
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric'
|
||||||
|
});
|
||||||
|
const channel = await client.channels.fetch(timer.data.channelId);
|
||||||
|
await channel.send(`${currentDate}`);
|
||||||
|
if (currentDate.startsWith('Sunday')) {
|
||||||
|
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}`);
|
||||||
|
let db = await client.localDB;
|
||||||
|
const data = await response.json();
|
||||||
|
db.prepare(`UPDATE bot_config SET exchange_rate_eur_kr = ? WHERE id = 1`).run(data.rates.SEK);
|
||||||
|
let weeklyBudget = await (await db.prepare(`SELECT weekly_budget FROM bot_config`).get()).weekly_budget;
|
||||||
|
await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`);
|
||||||
|
db.prepare(`UPDATE grocery_budgets SET budget_spent = 0`).run();
|
||||||
|
await channel.send(`Reset weekly budget to ${weeklyBudget}EUR / ${weeklyBudget*data.rates.SEK}SEK`);
|
||||||
|
}
|
||||||
|
|
||||||
|
} 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