Fixed and refactored. Now should work with v14

This commit is contained in:
Ladislav Hano 2023-02-28 23:48:15 +01:00
parent 6e385204d5
commit 74a8ae6e81
18 changed files with 537 additions and 330 deletions

View file

@ -1,16 +1,20 @@
const axios = require('axios').default;
const Discord = require('discord.js');
require('dotenv').config(); require('dotenv').config();
const client = require('./main');
const { bModel, eModel } = require('./database/schemas');
const gifs = require('./gifs');
module.exports = { module.exports = pingEvent;
debug: debug,
};
function debug(message) { async function pingEvent() {
if (message.content == "!detail" && message.reference != undefined) { const guildIds = [];
message.channel.messages.fetch(message.reference.messageId).then(msg=> { const sysChannelIds = [];
console.log(msg);
}) const todayBirthdays = await bModel.find().exec();
} const globalEventList = await eModel.find({ guild: 'global' }).exec();
client.channels.cache.get('770748282191740943').send(`It's **${globalEventList[3].name}** today!\n` + globalEventList[3].specialMessage);
const embed = await gifs.getGifEmbed(`https://g.tenor.com/v1/search?q=anime-hug&key=${process.env.TENOR}&limit=${5}`, 5);
embed.setDescription(`Happy Birthday <@${todayBirthdays[0].id}> !!!`);
client.channels.cache.get('770748282191740943').send({ embeds: [embed] });
} }

View file

@ -1,5 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
const { MessageEmbed } = require('discord.js');
const help = require('../helpFunctions.js'); const help = require('../helpFunctions.js');
const { bModel } = require('../database/schemas.js'); const { bModel } = require('../database/schemas.js');
@ -119,7 +118,7 @@ async function addBirthday(options) {
name: nickname, name: nickname,
}); });
dbEntry.save(); dbEntry.save();
error = await sortTable(); await sortTable();
} }
catch (err) { catch (err) {
console.log(err); console.log(err);
@ -157,7 +156,7 @@ async function checkBirthday(interaction) {
else { else {
const probably = getProbably(); const probably = getProbably();
const personList = closest.join('\n'); const personList = closest.join('\n');
const embed = new MessageEmbed() const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`) .setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${personList} \n will celebrate... ${probably}`) .setDescription(`${personList} \n will celebrate... ${probably}`)
.setColor(help.randomColor()); .setColor(help.randomColor());
@ -170,7 +169,7 @@ async function checkBirthday(interaction) {
if (closest.length > 0) { if (closest.length > 0) {
const probably = getProbably(); const probably = getProbably();
const personList = closest.join('\n'); const personList = closest.join('\n');
const embed = new MessageEmbed() const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`) .setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${personList} \n will celebrate... ${probably}`) .setDescription(`${personList} \n will celebrate... ${probably}`)
.setColor(help.randomColor()); .setColor(help.randomColor());
@ -193,7 +192,7 @@ async function checkBirthday(interaction) {
else { else {
const probably = getProbably(); const probably = getProbably();
closest.join('\n'); closest.join('\n');
const embed = new MessageEmbed() const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`) .setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${closest} \n will celebrate ${probably}`) .setDescription(`${closest} \n will celebrate ${probably}`)
.setColor(help.randomColor()); .setColor(help.randomColor());
@ -202,7 +201,7 @@ async function checkBirthday(interaction) {
} }
// if noone from server is in the birthday list (and maybe something else) // if noone from server is in the birthday list (and maybe something else)
const embed = new MessageEmbed() const embed = new EmbedBuilder()
.setTitle('Oh no...') .setTitle('Oh no...')
.setDescription('There was an error'); .setDescription('There was an error');
return embed; return embed;

View file

@ -1,5 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
const { MessageEmbed } = require('discord.js');
const help = require('../helpFunctions.js'); const help = require('../helpFunctions.js');
const { eModel } = require('../database/schemas'); const { eModel } = require('../database/schemas');
@ -26,7 +25,7 @@ module.exports = {
option.setName('global') option.setName('global')
.setDescription('Should this event display on all servers?')) .setDescription('Should this event display on all servers?'))
.addStringOption(option => .addStringOption(option =>
option.setName('special-message') option.setName('special message')
.setDescription('Special message to send in event announcement'))) .setDescription('Special message to send in event announcement')))
.addSubcommand(subcommand => .addSubcommand(subcommand =>
subcommand.setName('delete') subcommand.setName('delete')
@ -55,17 +54,17 @@ module.exports = {
subcommand.setName('name') subcommand.setName('name')
.setDescription('Change name of an event') .setDescription('Change name of an event')
.addStringOption(option => .addStringOption(option =>
option.setName('new-name') option.setName('new name')
.setDescription('New name of the event') .setDescription('New name of the event')
.setRequired(true)) .setRequired(true))
.addIntegerOption(option => option.setName('id') .addIntegerOption(option => option.setName('id')
.setDescription('Id of the even you want to change') .setDescription('Id of the even you want to change')
.setRequired(true))) .setRequired(true)))
.addSubcommand(subcommand => .addSubcommand(subcommand =>
subcommand.setName('special-message') subcommand.setName('special message')
.setDescription('Change special message of an event') .setDescription('Change special message of an event')
.addStringOption(option => .addStringOption(option =>
option.setName('new-message') option.setName('new message')
.setDescription('New special message') .setDescription('New special message')
.setRequired(true)))) .setRequired(true))))
.addSubcommand(subcommand => .addSubcommand(subcommand =>
@ -106,6 +105,9 @@ module.exports = {
case 'name': case 'name':
await interaction.reply(await changeEventName(interaction)); await interaction.reply(await changeEventName(interaction));
break; break;
case 'special message':
await interaction.reply(await changeSpecialMessage(interaction));
break;
} }
} }
}, },
@ -162,8 +164,8 @@ async function addEvent(interaction) {
const ms = new Date().getMilliseconds(); const ms = new Date().getMilliseconds();
const id = (1000 * day) + (1000 * (ms % 1000)) + month; const id = (1000 * day) + (1000 * (ms % 1000)) + month;
let guildData = isGlobal ? 'guild' : interaction.guild.id const guildData = isGlobal ? 'guild' : interaction.guild.id;
let eventType = isGlobal ? 'global' : 'guild'; const eventType = isGlobal ? 'global' : 'guild';
try { try {
const dbEntry = await eModel.create({ const dbEntry = await eModel.create({
@ -174,12 +176,11 @@ async function addEvent(interaction) {
month: month, month: month,
}); });
dbEntry.save(); dbEntry.save();
error = await sortTable(); await sortTable();
} }
catch (err) { catch (err) {
error = err;
console.log(err); console.log(err);
return 'There was an error \n(user is probably already on the birthday list)' return 'There was an error \n(user is probably already on the birthday list)';
} }
return `Successfuly added ${eventType} event ${name}`; return `Successfuly added ${eventType} event ${name}`;
@ -192,7 +193,7 @@ async function listEvents(interaction) {
query = eModel.find({ guild: interaction.guild.id }); query = eModel.find({ guild: interaction.guild.id });
const guildEvents = await query.exec(); const guildEvents = await query.exec();
const embed = new MessageEmbed() const embed = new EmbedBuilder()
.setColor(help.randomColor()) .setColor(help.randomColor())
.setTitle('Literally nothing here'); .setTitle('Literally nothing here');
@ -200,39 +201,58 @@ async function listEvents(interaction) {
let eventNames = []; let eventNames = [];
let eventDates = []; let eventDates = [];
// TODO DEDUPLCIATE // TODO DEDUPLCIATE
for (let i = 0; i < globalEvents.length; i++) {
eventIds.push(globalEvents[i].id);
eventNames.push(globalEvents[i].name);
eventDates.push(`${globalEvents[i].day}. ${globalEvents[i].month}.`);
}
if (globalEvents.length > 0) {
embed.addField('Global Events: ', '\u200b');
embed.addField('Id: ', eventIds.join('\n'), true);
embed.addField('Name: ', eventNames.join('\n'), true);
embed.addField('Date: ', eventDates.join('\n'), true);
embed.addField('\u200b', '\u200b');
embed.setTitle('');
}
eventIds = []; if (globalEvents.length > 0) {
eventNames = []; for (let i = 0; i < globalEvents.length; i++) {
eventDates = []; eventIds.push(globalEvents[i].id);
for (let i = 0; i < guildEvents.length; i++) { eventNames.push(globalEvents[i].name);
eventIds.push(guildEvents[i].id); eventDates.push(`${globalEvents[i].day}. ${globalEvents[i].month}.`);
eventNames.push(guildEvents[i].name); }
eventDates.push(`${guildEvents[i].day}. ${guildEvents[i].month}.`); embed.addFields(
{ name: 'Global Events: ', value: '\u200b' },
{ name: 'Id: ', value: eventIds.join('\n'), intents: true },
{ name: 'Name: ', value: eventNames.join('\n'), intents: true },
{ name: 'Date: ', value: eventDates.join('\n'), intents: true },
{ name: '\u200b', value: '\u200b' },
);
embed.setTitle('');
eventIds = [];
eventNames = [];
eventDates = [];
} }
if (guildEvents.length > 0) { if (guildEvents.length > 0) {
embed.addField('Guild events:', '\u200b'); for (let i = 0; i < guildEvents.length; i++) {
embed.addField('Id: ', eventIds.join('\n'), true); eventIds.push(guildEvents[i].id);
embed.addField('Name: ', eventNames.join('\n'), true); eventNames.push(guildEvents[i].name);
embed.addField('Date: ', eventDates.join('\n'), true); eventDates.push(`${guildEvents[i].day}. ${guildEvents[i].month}.`);
}
embed.addFields(
{ name: 'Guild events:', value: '\u200b' },
{ name: 'Id: ', value: eventIds.join('\n'), intents: true },
{ name: 'Name: ', value: eventNames.join('\n'), intents: true },
{ name: 'Date: ', value: eventDates.join('\n'), intents: true },
{ name: '\u200b', value: '\u200b' },
);
embed.setTitle(''); embed.setTitle('');
} }
return embed; return embed;
} }
async function changeSpecialMessage(interaction) {
try {
await eModel.findOneAndUpdate(
{ id: interaction.options.getInteger('id') },
{ $set: { specialMessage: interaction.options.getString('special message') } },
);
}
catch {
return 'There was an error';
}
return 'Successfuly changed event message';
}
function catchErrors(options) { function catchErrors(options) {
const month = options.getInteger('month'); const month = options.getInteger('month');
const day = options.getInteger('day'); const day = options.getInteger('day');

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js'); const help = require('../helpFunctions.js');
const gifAmount = 50; const gifAmount = 50;
require('dotenv').config(); require('dotenv').config();

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js'); const help = require('../helpFunctions.js');
require('dotenv').config(); require('dotenv').config();

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js'); const help = require('../helpFunctions.js');
require('dotenv').config(); require('dotenv').config();

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders'); const { SlashCommandBuilder } = require('discord.js');
function say(interaction) { function say(interaction) {
const message = interaction.options.getString('what'); const message = interaction.options.getString('what');

View file

@ -25,12 +25,12 @@ const eventSchema = new mongoose.Schema({
name: String, name: String,
day: Number, day: Number,
month: Number, month: Number,
specialMessage: String specialMessage: String,
}); });
const emodel = mongoose.model('events', eventSchema) const emodel = mongoose.model('events', eventSchema);
module.exports = { module.exports = {
bModel: bdmodel, bModel: bdmodel,
eModel: emodel eModel: emodel,
}; };

View file

@ -2,12 +2,11 @@ const fs = require('fs');
const { REST, Routes } = require('discord.js'); const { REST, Routes } = require('discord.js');
require('dotenv').config(); require('dotenv').config();
const fd = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const commands = []; const commands = [];
const commandsPath = path.join(__dirname, 'commands') const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => !file.includes('WIP')); const commandFiles = fs.readdirSync(commandsPath).filter(file => !file.includes('WIP'));
for (const file of commandFiles) { for (const file of commandFiles) {
@ -25,7 +24,8 @@ const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
{ body: commands }, { body: commands },
); );
console.log(`Successfully reloaded ${data.length} application (/) commands.`); console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) { }
catch (error) {
console.error(error); console.error(error);
} }
})(); })();

16
gifs.js
View file

@ -1,12 +1,12 @@
const axios = require('axios').default; const axios = require('axios').default;
const Discord = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const help = require('./helpFunctions');
module.exports = ({
module.exports({
getGifs: getGifs, getGifs: getGifs,
getGifEmbed: getGifEmbed, getGifEmbed: getGifEmbed,
getGifWithMessage: getGifWithMessage getGifWithMessage: getGifWithMessage,
}) });
async function getGifs(gifs) { async function getGifs(gifs) {
@ -17,10 +17,10 @@ async function getGifs(gifs) {
async function getGifEmbed(gifQuery, gifAmount) { async function getGifEmbed(gifQuery, gifAmount) {
const response = await getGifs(gifQuery); const response = await getGifs(gifQuery);
const gif = response.data.results[RNG(gifAmount)].media[0].gif.url; const gif = response.data.results[help.RNG(gifAmount)].media[0].gif.url;
const gifEmbed = new Discord.MessageEmbed() const gifEmbed = new EmbedBuilder()
.setImage(gif) .setImage(gif)
.setColor(randomColor()); .setColor(help.randomColor());
return gifEmbed; return gifEmbed;
} }

View file

@ -1,25 +1,24 @@
require('dotenv').config() require('dotenv').config();
const http = require('http') const http = require('http');
const crypto = require('crypto') const crypto = require('crypto');
const exec = require('child_process').exec const exec = require('child_process').exec;
const secret = `${process.env.GITHUB_WEBHOOK}` const secret = `${process.env.GITHUB_WEBHOOK}`;
const repo = "/home/moover/MOOver" const repo = '/home/moover/MOOver';
http.createServer(function (req, res) { http.createServer(function(req, res) {
req.on('data', function (chunk) { req.on('data', function(chunk) {
let sig = "sha1=" + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex') const sig = 'sha1=' + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex');
if (req.headers["x-hub-signature"] == sig) { if (req.headers['x-hub-signature'] == sig) {
console.log("updating moover...") console.log('updating moover...');
exec(`pm2 stop 'MOOver - main' && cd ${repo} && git pull && npm install && pm2 start 'MOOver - main'`) exec(`pm2 stop 'MOOver - main' && cd ${repo} && git pull && npm install && pm2 start 'MOOver - main'`);
console.log("Success!") console.log('Success!');
} }
}) });
res.writeHead(200, { 'Content-Type': 'text/plain' }) res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n') res.end('Hello World\n');
}).listen(5050, "127.0.0.1", () => {
console.log(`Server is running`)
})
}).listen(5050, '127.0.0.1', () => {
console.log('Server is running');
});

View file

@ -1,15 +0,0 @@
h(1)
h(2)
h(3)
h(0)
function h(n) {
console.log(7*(5**n)+9+g(n))
}
function g(n) {
if (n == 0) {
return 0
}
return 9*7*(5**(n-1))+g(n-1)
}

87
main.js
View file

@ -2,19 +2,19 @@
List of intents List of intents
https://discord.com/developers/docs/topics/gateway#privileged-intents https://discord.com/developers/docs/topics/gateway#privileged-intents
*/ */
require('dotenv').config() require('dotenv').config();
var http = require('http') const http = require('http');
http.createServer(function (req, res) { http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' }) res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n') res.end('Hello World\n');
}).listen(5000, "127.0.0.1") }).listen(5000, '127.0.0.1');
const { const {
Client, Client,
Collection, Collection,
GatewayIntentBits GatewayIntentBits,
} = require('discord.js') } = require('discord.js');
const client = new Client({ const client = new Client({
intents: [ intents: [
@ -22,80 +22,83 @@ const client = new Client({
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
], ],
}) });
const fs = require('fs') const fs = require('fs');
client.commands = new Collection() client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands') const commandFiles = fs.readdirSync('./commands')
.filter(file => !file.includes('WIP')) .filter(file => !file.includes('WIP'));
for (const file of commandFiles) { for (const file of commandFiles) {
const command = require(`./commands/${file}`) const command = require(`./commands/${file}`);
// Set a new item in the Collection // Set a new item in the Collection
// With the key as the command name and the value as the exported module // With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command) client.commands.set(command.data.name, command);
} }
const mongoose = require('mongoose') const mongoose = require('mongoose');
async function dbConnect() { async function dbConnect() {
mongoose.connect(process.env.DBSRV, { mongoose.connect(process.env.DBSRV, {
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
}).then(() => { }).then(() => {
console.log('Connected to database') console.log('Connected to database');
}).catch((err) => { }).catch((err) => {
console.log(err) console.log(err);
}) });
} }
const help = require('./helpFunctions.js') const help = require('./helpFunctions.js');
const cron = require('node-cron') const cron = require('node-cron');
let gotMessage; let gotMessage;
client.once('ready', async () => { client.once('ready', async () => {
gotMessage = require('./messageHandler'); gotMessage = require('./messageHandler');
const ping = require('./ping') const ping = require('./ping');
if (client.user.username != 'MOOver Debug') { if (client.user.username != 'MOOver Debug' && process.env.DEBUG != 'ON') {
const turnOnMsg = ['AAAAAAAAAAAAA', 'Just turned on!', const turnOnMsg = ['AAAAAAAAAAAAA', 'Just turned on!',
'Just woke up!', 'May have crashed... sowwyyy >.<', 'Just woke up!', 'May have crashed... sowwyyy >.<',
'Heyyyy!', 'I\'m baaaack', 'Whom\'st have summoned the ancient one?'] 'Heyyyy!', 'I\'m baaaack', 'Whom\'st have summoned the ancient one?'];
client.channels.cache.get('780439236867653635').send(turnOnMsg[help.RNG(turnOnMsg.length)]); const debugChannel = client.channels.cache.get('780439236867653635');
if (debugChannel) {
debugChannel.send(turnOnMsg[help.RNG(turnOnMsg.length)]);
}
} }
cron.schedule('0 13 * * *', async function () { cron.schedule('0 13 * * *', async function() {
ping() ping();
}) });
await dbConnect(); await dbConnect();
const { eModel } = require('./database/schemas'); const a = require('./.debug.js');
a();
eModel.updateMany({}, { $set: { specialMessage: "" }}).exec() console.log('Running!');
console.log('Running!') });
})
client.on('messageCreate', (message) => { client.on('messageCreate', (message) => {
gotMessage(message) gotMessage(message);
}); });
client.on('interactionCreate', async interaction => { client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName) const command = client.commands.get(interaction.commandName);
if (!command) return if (!command) return;
try { try {
await command.execute(interaction) await command.execute(interaction);
} }
catch (error) { catch (error) {
console.error(error) console.error(error);
await interaction.reply({ await interaction.reply({
content: 'There was an error while executing this command!', content: 'There was an error while executing this command!',
ephemeral: true, ephemeral: true,
}) });
} }
}) });
client.login(process.env.TOKEN) client.login(process.env.TOKEN);
module.exports = client module.exports = client;

View file

@ -1,49 +1,41 @@
const moove = require("./moove") const moove = require('./moove');
const help = require('./helpFunctions') const help = require('./helpFunctions');
function gotMessage(message) { function gotMessage(message) {
if (message.author.bot) { if (message.author.bot) {
return return;
} }
const content = message.content.trim()
const msgContentSplit = content.split(/[ ]+/)
/** /**
* reference can't be null => must be a reply to message * reference can't be null => must be a reply to message
* must contain only one argument * must contain only one argument
* that argument mentions channel * that argument mentions channel
*/ */
console.log(message.reference) if (message.reference != null) {
console.log(msgContentSplit.length) moove(message);
console.log(message)
if (message.reference != null && msgContentSplit.length == 1 &&
message.mentions.channels.first() != undefined) {
console.log("aaaa")
moove(message, msgContentSplit[0])
} }
const msg = message.content.toLowerCase() const msg = message.content.toLowerCase();
const chance = help.RNG(50000) const chance = help.RNG(50000);
if (chance == 420) { if (chance == 420) {
whoAsked(message) whoAsked(message);
} }
if (msg.includes('henlo')) { if (msg.includes('henlo')) {
henlo(message) henlo(message);
} }
else if (msg.includes('how ye')) { else if (msg.includes('how ye')) {
mood(message) mood(message);
} }
else if (msg.includes('tylko jedno')) { else if (msg.includes('tylko jedno')) {
message.reply('Koksu pięć gram odlecieć sam') message.reply('Koksu pięć gram odlecieć sam');
} }
if (process.env.DEBUG == "ON") { if (process.env.DEBUG == 'ON') {
const debugger_ = require('./.debug.js') const debugger_ = require('./.debug.js');
debugger_.debug(message) debugger_.debug(message);
} }
} }

View file

@ -1,65 +1,71 @@
const Discord = require('discord.js') const { EmbedBuilder } = require('discord.js');
const help = require('./helpFunctions') const help = require('./helpFunctions');
const client= require('./main') const client = require('./main');
function moove(message, channelId) { function moove(message) {
message.react('🐮') message.react('🐮');
const originalChannel = message.channel const content = message.content.trim();
const msgToMooveId = message.reference.messageId
const mentionedChannelId = channelId.substring(2, channelId.length - 1)
console.log(mentionedChannelId) if (content.search(/<#[0-9]*>$/g) != 0) {
return; return;
}
const originalChannel = message.channel;
const msgToMooveId = message.reference.messageId;
const mentionedChannel = client.channels.cache.get(content.substring(2, content.length - 1));
if (mentionedChannel == undefined) {
return;
}
originalChannel.messages.fetch(msgToMooveId).then(msg => { originalChannel.messages.fetch(msgToMooveId).then(msg => {
const sentBy = `Sent by ${msg.author}\nmooved ${message.author}\n`;
if (msg.embeds.length > 0 && msg.content == '' && msg.attachments.size == 0) { if (msg.embeds.length > 0 && msg.content == '' && msg.attachments.size == 0) {
client.getChannel(mentionedChannelId).send({ embeds: msg.embeds }) mentionedChannel.send({ embeds: msg.embeds });
} }
else if (msg.attachments.size > 0) { else if (msg.attachments.size > 0) {
let attachmentsURL = "" const originalMsgAttachments = msg.attachments.values();
const originalMsgAttachments = msg.attachments.values()
const attachmentsArr = [];
for (let i = 0; i < msg.attachments.size; i++) { for (let i = 0; i < msg.attachments.size; i++) {
const currAttachment = originalMsgAttachments.next().value attachmentsArr.push(originalMsgAttachments.next().value);
attachmentsURL += `${currAttachment.url}\n`
} }
let messStr = "" let messStr = '';
if (msg.content != '') { if (msg.content != '') {
messStr = "\nMessage:\n" messStr = '\nMessage:\n' + msg.content;
} }
newContent = `Sent by ${msg.author}\nmooved ${message.author}\n${messStr}${msg.content}\nAttachments:\n${attachmentsURL}` mentionedChannel.send({ content: sentBy + messStr, files: attachmentsArr });
client.channels.cache.get(mentionedChannelId).send({ content: newContent })
if (msg.embeds.length > 0) { if (msg.embeds.length > 0) {
client.channels.cache.get(mentionedChannelId) mentionedChannel.send({ embeds: msg.embeds });
.send({ embeds: msg.embeds })
} }
} }
else { else {
// ? Empty, Has embeds
if (msg.content == '') { if (msg.content == '') {
client.channels.cache.get(mentionedChannelId).send({ // ? Empty, Has embeds
content: `Sent by ${msg.author}\nmooved ${message.author}\nMessage:\n${msg.content}` mentionedChannel.send({
}) content: sentBy + `Message:\n${msg.content}`,
});
} }
// ? Has content, No embeds
else { else {
const embed = new Discord.MessageEmbed() // ? Has content, No embeds
const embed = new EmbedBuilder()
.setColor(help.randomColor()) .setColor(help.randomColor())
.addFields() .addFields(
.addField('MOO', `Sent by ${msg.author}\nmooved ${message.author}`) { name: 'MOO', value: sentBy },
.addField('Message', msg.content) { name: 'Message', value: msg.content },
client.channels.cache.get(mentionedChannelId).send({ embeds: [embed] }) );
mentionedChannel.send({ embeds: [embed] });
} }
} }
setTimeout(() => msg.delete(), 3000) setTimeout(() => msg.delete(), 3000);
}) });
setTimeout(() => message.delete(), 3000) setTimeout(() => message.delete(), 3000);
} }
module.exports = moove module.exports = moove;

368
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -10,16 +10,15 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@discordjs/builders": "^0.12.0",
"@discordjs/rest": "^0.3.0",
"axios": "^0.25.0", "axios": "^0.25.0",
"discord-api-types": "^0.26.1",
"discord.js": "^14.7.1", "discord.js": "^14.7.1",
"dotenv": "^14.2.0", "dotenv": "^14.2.0",
"eslint": "^8.8.0",
"i": "^0.3.7", "i": "^0.3.7",
"mongoose": "^6.2.1", "mongoose": "^6.2.1",
"node-cron": "^3.0.0", "node-cron": "^3.0.0",
"npm": "^8.5.0" "npm": "^8.5.0"
},
"devDependencies": {
"eslint": "^8.35.0"
} }
} }

50
ping.js
View file

@ -1,48 +1,46 @@
require('dotenv').config() require('dotenv').config();
const { client } = require('./main');
const { bModel, eModel } = require('./database/schemas');
const help = require('./helpFunctions');
module.exports = pingEvent module.exports = pingEvent;
async function pingEvent() { async function pingEvent() {
const currentDay = new Date().getDate() const currentDay = new Date().getDate();
const currentMonth = new Date().getMonth() + 1 const currentMonth = new Date().getMonth() + 1;
const guildIds = [] const guildIds = [];
const sysChannelIds = [] const sysChannelIds = [];
client.guilds.cache.forEach(element => { client.guilds.cache.forEach(element => {
sysChannelIds.push(element.channels.guild.systemChannelId) sysChannelIds.push(element.channels.guild.systemChannelId);
guildIds.push(element.id) guildIds.push(element.id);
}) });
const todayBirthdays = await bModel.find({ day: currentDay, month: currentMonth }).exec() const todayBirthdays = await bModel.find({ day: currentDay, month: currentMonth }).exec();
const globalEventList = await eModel.find({ guild: 'global', day: currentDay, month: currentMonth }).exec() const globalEventList = await eModel.find({ guild: 'global', day: currentDay, month: currentMonth }).exec();
for (let i = 0; i < guildIds.length; i++) { for (let i = 0; i < guildIds.length; i++) {
const guildEvents = await eModel.find({ guild: guildIds[i], day: currentDay, month: currentMonth }).exec() const guildEvents = await eModel.find({ guild: guildIds[i], day: currentDay, month: currentMonth }).exec();
const guild = client.guilds.cache.find((g) => g.id == guildIds[i]) const guild = client.guilds.cache.find((g) => g.id == guildIds[i]);
for (let j = 0; j < birthdayList.length; j++) { for (let j = 0; j < todayBirthdays.length; j++) {
const userId = birthdayList[j].id const userId = todayBirthdays[j].id;
if ((await guild.members.fetch()).find(user => user.id == userId) != undefined) { if ((await guild.members.fetch()).find(user => user.id == userId) != undefined) {
const gifAmount = 12 const gifAmount = 12;
const embed = await help.getGifEmbed(`https://g.tenor.com/v1/search?q=anime-hug&key=${process.env.TENOR}&limit=${gifAmount}`, gifAmount) const embed = await help.getGifEmbed(`https://g.tenor.com/v1/search?q=anime-hug&key=${process.env.TENOR}&limit=${gifAmount}`, gifAmount);
embed.setDescription(`Happy Birthday <@${userId}> !!!`) embed.setDescription(`Happy Birthday <@${userId}> !!!`);
client.channels.cache.get(sysChannelIds[i]) client.channels.cache.get(sysChannelIds[i])
.send({ embeds: [embed] }) .send({ embeds: [embed] });
} }
} }
for (let j = 0; j < globalEventList.length; j++) { for (let j = 0; j < globalEventList.length; j++) {
// TODO add special message to database
let specialMessage = ''
if (globalEventList[j].name == 'Valentine\'s Day') {
specialMessage = '\n Don\'t forget I love you all with all my hart 🥺'
}
client.channels.cache.get(sysChannelIds[i]) client.channels.cache.get(sysChannelIds[i])
.send(`It's **${globalEventList[j].name}** today!` + specialMessage) .send(`It's **${globalEventList[j].name}** today!\n` + globalEventList[j].specialMessage);
} }
for (let j = 0; j < guildEvents.length; j++) { for (let j = 0; j < guildEvents.length; j++) {
client.channels.cache.get(sysChannelIds[i]) client.channels.cache.get(sysChannelIds[i])
.send(`It's **${guildEvents[j].name}** today!`) .send(`It's **${guildEvents[j].name}** today!\n` + guildEvents[j].specialMessage);
} }
} }
} }