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();
const client = require('./main');
const { bModel, eModel } = require('./database/schemas');
const gifs = require('./gifs');
module.exports = {
debug: debug,
};
module.exports = pingEvent;
function debug(message) {
if (message.content == "!detail" && message.reference != undefined) {
message.channel.messages.fetch(message.reference.messageId).then(msg=> {
console.log(msg);
})
}
}
async function pingEvent() {
const guildIds = [];
const sysChannelIds = [];
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 { MessageEmbed } = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js');
const { bModel } = require('../database/schemas.js');
@ -119,7 +118,7 @@ async function addBirthday(options) {
name: nickname,
});
dbEntry.save();
error = await sortTable();
await sortTable();
}
catch (err) {
console.log(err);
@ -157,7 +156,7 @@ async function checkBirthday(interaction) {
else {
const probably = getProbably();
const personList = closest.join('\n');
const embed = new MessageEmbed()
const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${personList} \n will celebrate... ${probably}`)
.setColor(help.randomColor());
@ -170,7 +169,7 @@ async function checkBirthday(interaction) {
if (closest.length > 0) {
const probably = getProbably();
const personList = closest.join('\n');
const embed = new MessageEmbed()
const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${personList} \n will celebrate... ${probably}`)
.setColor(help.randomColor());
@ -193,7 +192,7 @@ async function checkBirthday(interaction) {
else {
const probably = getProbably();
closest.join('\n');
const embed = new MessageEmbed()
const embed = new EmbedBuilder()
.setTitle(`Closest birthday is ${closestD}. ${closestM}.`)
.setDescription(`${closest} \n will celebrate ${probably}`)
.setColor(help.randomColor());
@ -202,7 +201,7 @@ async function checkBirthday(interaction) {
}
// if noone from server is in the birthday list (and maybe something else)
const embed = new MessageEmbed()
const embed = new EmbedBuilder()
.setTitle('Oh no...')
.setDescription('There was an error');
return embed;

View file

@ -1,5 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js');
const { eModel } = require('../database/schemas');
@ -26,7 +25,7 @@ module.exports = {
option.setName('global')
.setDescription('Should this event display on all servers?'))
.addStringOption(option =>
option.setName('special-message')
option.setName('special message')
.setDescription('Special message to send in event announcement')))
.addSubcommand(subcommand =>
subcommand.setName('delete')
@ -55,17 +54,17 @@ module.exports = {
subcommand.setName('name')
.setDescription('Change name of an event')
.addStringOption(option =>
option.setName('new-name')
option.setName('new name')
.setDescription('New name of the event')
.setRequired(true))
.addIntegerOption(option => option.setName('id')
.setDescription('Id of the even you want to change')
.setRequired(true)))
.addSubcommand(subcommand =>
subcommand.setName('special-message')
.addSubcommand(subcommand =>
subcommand.setName('special message')
.setDescription('Change special message of an event')
.addStringOption(option =>
option.setName('new-message')
option.setName('new message')
.setDescription('New special message')
.setRequired(true))))
.addSubcommand(subcommand =>
@ -106,6 +105,9 @@ module.exports = {
case 'name':
await interaction.reply(await changeEventName(interaction));
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 id = (1000 * day) + (1000 * (ms % 1000)) + month;
let guildData = isGlobal ? 'guild' : interaction.guild.id
let eventType = isGlobal ? 'global' : 'guild';
const guildData = isGlobal ? 'guild' : interaction.guild.id;
const eventType = isGlobal ? 'global' : 'guild';
try {
const dbEntry = await eModel.create({
@ -174,12 +176,11 @@ async function addEvent(interaction) {
month: month,
});
dbEntry.save();
error = await sortTable();
await sortTable();
}
catch (err) {
error = 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}`;
@ -192,7 +193,7 @@ async function listEvents(interaction) {
query = eModel.find({ guild: interaction.guild.id });
const guildEvents = await query.exec();
const embed = new MessageEmbed()
const embed = new EmbedBuilder()
.setColor(help.randomColor())
.setTitle('Literally nothing here');
@ -200,39 +201,58 @@ async function listEvents(interaction) {
let eventNames = [];
let eventDates = [];
// 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 = [];
eventNames = [];
eventDates = [];
for (let i = 0; i < guildEvents.length; i++) {
eventIds.push(guildEvents[i].id);
eventNames.push(guildEvents[i].name);
eventDates.push(`${guildEvents[i].day}. ${guildEvents[i].month}.`);
if (globalEvents.length > 0) {
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}.`);
}
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) {
embed.addField('Guild events:', '\u200b');
embed.addField('Id: ', eventIds.join('\n'), true);
embed.addField('Name: ', eventNames.join('\n'), true);
embed.addField('Date: ', eventDates.join('\n'), true);
for (let i = 0; i < guildEvents.length; i++) {
eventIds.push(guildEvents[i].id);
eventNames.push(guildEvents[i].name);
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('');
}
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) {
const month = options.getInteger('month');
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 gifAmount = 50;
require('dotenv').config();
@ -23,10 +23,10 @@ async function getGifEmbed(options) {
const gifs = `https://g.tenor.com/v1/random?key=${process.env.TENOR}&limit=${gifAmount}&contentfilter=${rating}`;
return help.getGifEmbed(gifs, gifAmount);
}
const searchSplits = search.split(/[ ]+/);
const searchKey = searchSplits.join('-');
const gifs = `https://g.tenor.com/v1/search?q=${searchKey}&key=${process.env.TENOR}&limit=${gifAmount}&contentfilter=${rating}`;
return help.getGifEmbed(gifs, gifAmount);
}

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js');
require('dotenv').config();
@ -7,7 +7,7 @@ async function headpat(interaction) {
const searchKey = 'headpat-anime';
const gifAmount = 16;
const gifs = `https://g.tenor.com/v1/search?q=${searchKey}&key=${process.env.TENOR}&limit=${gifAmount}`;
return help.getGifWithMessage(interaction, gifs, gifAmount);
}

View file

@ -1,4 +1,4 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { SlashCommandBuilder } = require('discord.js');
const help = require('../helpFunctions.js');
require('dotenv').config();
@ -8,7 +8,7 @@ async function hug(interaction) {
const searchKey = 'hug-anime';
const gifAmount = 16;
const gifs = `https://g.tenor.com/v1/search?q=${searchKey}&key=${process.env.TENOR}&limit=${gifAmount}`;
return help.getGifWithMessage(interaction, gifs, gifAmount);
}

View file

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

View file

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

View file

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

16
gifs.js
View file

@ -1,12 +1,12 @@
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,
getGifEmbed: getGifEmbed,
getGifWithMessage: getGifWithMessage
})
getGifWithMessage: getGifWithMessage,
});
async function getGifs(gifs) {
@ -17,10 +17,10 @@ async function getGifs(gifs) {
async function getGifEmbed(gifQuery, gifAmount) {
const response = await getGifs(gifQuery);
const gif = response.data.results[RNG(gifAmount)].media[0].gif.url;
const gifEmbed = new Discord.MessageEmbed()
const gif = response.data.results[help.RNG(gifAmount)].media[0].gif.url;
const gifEmbed = new EmbedBuilder()
.setImage(gif)
.setColor(randomColor());
.setColor(help.randomColor());
return gifEmbed;
}

View file

@ -1,25 +1,24 @@
require('dotenv').config()
const http = require('http')
const crypto = require('crypto')
const exec = require('child_process').exec
require('dotenv').config();
const http = require('http');
const crypto = require('crypto');
const exec = require('child_process').exec;
const secret = `${process.env.GITHUB_WEBHOOK}`
const repo = "/home/moover/MOOver"
const secret = `${process.env.GITHUB_WEBHOOK}`;
const repo = '/home/moover/MOOver';
http.createServer(function (req, res) {
req.on('data', function (chunk) {
let sig = "sha1=" + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex')
if (req.headers["x-hub-signature"] == sig) {
console.log("updating moover...")
exec(`pm2 stop 'MOOver - main' && cd ${repo} && git pull && npm install && pm2 start 'MOOver - main'`)
console.log("Success!")
http.createServer(function(req, res) {
req.on('data', function(chunk) {
const sig = 'sha1=' + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex');
if (req.headers['x-hub-signature'] == sig) {
console.log('updating moover...');
exec(`pm2 stop 'MOOver - main' && cd ${repo} && git pull && npm install && pm2 start 'MOOver - main'`);
console.log('Success!');
}
})
});
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello World\n')
}).listen(5050, "127.0.0.1", () => {
console.log(`Server is running`)
})
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).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
https://discord.com/developers/docs/topics/gateway#privileged-intents
*/
require('dotenv').config()
require('dotenv').config();
var http = require('http')
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello World\n')
}).listen(5000, "127.0.0.1")
const http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(5000, '127.0.0.1');
const {
Client,
Collection,
GatewayIntentBits
} = require('discord.js')
GatewayIntentBits,
} = require('discord.js');
const client = new Client({
intents: [
@ -22,80 +22,83 @@ const client = new Client({
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
],
})
});
const fs = require('fs')
client.commands = new Collection()
const fs = require('fs');
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands')
.filter(file => !file.includes('WIP'))
.filter(file => !file.includes('WIP'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// 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() {
mongoose.connect(process.env.DBSRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to database')
console.log('Connected to database');
}).catch((err) => {
console.log(err)
})
console.log(err);
});
}
const help = require('./helpFunctions.js')
const cron = require('node-cron')
const help = require('./helpFunctions.js');
const cron = require('node-cron');
let gotMessage;
client.once('ready', async () => {
gotMessage = require('./messageHandler');
const ping = require('./ping')
if (client.user.username != 'MOOver Debug') {
const ping = require('./ping');
if (client.user.username != 'MOOver Debug' && process.env.DEBUG != 'ON') {
const turnOnMsg = ['AAAAAAAAAAAAA', 'Just turned on!',
'Just woke up!', 'May have crashed... sowwyyy >.<',
'Heyyyy!', 'I\'m baaaack', 'Whom\'st have summoned the ancient one?']
client.channels.cache.get('780439236867653635').send(turnOnMsg[help.RNG(turnOnMsg.length)]);
'Heyyyy!', 'I\'m baaaack', 'Whom\'st have summoned the ancient one?'];
const debugChannel = client.channels.cache.get('780439236867653635');
if (debugChannel) {
debugChannel.send(turnOnMsg[help.RNG(turnOnMsg.length)]);
}
}
cron.schedule('0 13 * * *', async function () {
ping()
})
cron.schedule('0 13 * * *', async function() {
ping();
});
await dbConnect();
const { eModel } = require('./database/schemas');
eModel.updateMany({}, { $set: { specialMessage: "" }}).exec()
console.log('Running!')
})
const a = require('./.debug.js');
a();
console.log('Running!');
});
client.on('messageCreate', (message) => {
gotMessage(message)
gotMessage(message);
});
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 {
await command.execute(interaction)
await command.execute(interaction);
}
catch (error) {
console.error(error)
console.error(error);
await interaction.reply({
content: 'There was an error while executing this command!',
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 help = require('./helpFunctions')
const moove = require('./moove');
const help = require('./helpFunctions');
function gotMessage(message) {
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
* must contain only one argument
* that argument mentions channel
*/
console.log(message.reference)
console.log(msgContentSplit.length)
console.log(message)
if (message.reference != null && msgContentSplit.length == 1 &&
message.mentions.channels.first() != undefined) {
console.log("aaaa")
moove(message, msgContentSplit[0])
if (message.reference != null) {
moove(message);
}
const msg = message.content.toLowerCase()
const msg = message.content.toLowerCase();
const chance = help.RNG(50000)
const chance = help.RNG(50000);
if (chance == 420) {
whoAsked(message)
whoAsked(message);
}
if (msg.includes('henlo')) {
henlo(message)
henlo(message);
}
else if (msg.includes('how ye')) {
mood(message)
mood(message);
}
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") {
const debugger_ = require('./.debug.js')
debugger_.debug(message)
if (process.env.DEBUG == 'ON') {
const debugger_ = require('./.debug.js');
debugger_.debug(message);
}
}
@ -64,7 +56,7 @@ async function whoAsked(message) {
const searchKey = 'who-asked';
const gifAmount = 20;
const gifs = `https://g.tenor.com/v1/search?q=${searchKey}&key=${process.env.TENOR}&limit=${gifAmount}`;
message.reply({ embeds: [await help.getGifEmbed(gifs, gifAmount)] });
}
}

View file

@ -1,65 +1,71 @@
const Discord = require('discord.js')
const help = require('./helpFunctions')
const client= require('./main')
const { EmbedBuilder } = require('discord.js');
const help = require('./helpFunctions');
const client = require('./main');
function moove(message, channelId) {
message.react('🐮')
function moove(message) {
message.react('🐮');
const originalChannel = message.channel
const msgToMooveId = message.reference.messageId
const mentionedChannelId = channelId.substring(2, channelId.length - 1)
const content = message.content.trim();
console.log(mentionedChannelId)
return;
if (content.search(/<#[0-9]*>$/g) != 0) {
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 => {
const sentBy = `Sent by ${msg.author}\nmooved ${message.author}\n`;
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) {
let attachmentsURL = ""
const originalMsgAttachments = msg.attachments.values()
const originalMsgAttachments = msg.attachments.values();
const attachmentsArr = [];
for (let i = 0; i < msg.attachments.size; i++) {
const currAttachment = originalMsgAttachments.next().value
attachmentsURL += `${currAttachment.url}\n`
attachmentsArr.push(originalMsgAttachments.next().value);
}
let messStr = ""
let messStr = '';
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) {
client.channels.cache.get(mentionedChannelId)
.send({ embeds: msg.embeds })
mentionedChannel.send({ embeds: msg.embeds });
}
}
else {
// ? Empty, Has embeds
if (msg.content == '') {
client.channels.cache.get(mentionedChannelId).send({
content: `Sent by ${msg.author}\nmooved ${message.author}\nMessage:\n${msg.content}`
})
// ? Empty, Has embeds
mentionedChannel.send({
content: sentBy + `Message:\n${msg.content}`,
});
}
// ? Has content, No embeds
else {
const embed = new Discord.MessageEmbed()
// ? Has content, No embeds
const embed = new EmbedBuilder()
.setColor(help.randomColor())
.addFields()
.addField('MOO', `Sent by ${msg.author}\nmooved ${message.author}`)
.addField('Message', msg.content)
client.channels.cache.get(mentionedChannelId).send({ embeds: [embed] })
.addFields(
{ name: 'MOO', value: sentBy },
{ name: 'Message', value: msg.content },
);
mentionedChannel.send({ embeds: [embed] });
}
}
setTimeout(() => msg.delete(), 3000)
})
setTimeout(() => message.delete(), 3000)
setTimeout(() => msg.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": "",
"license": "ISC",
"dependencies": {
"@discordjs/builders": "^0.12.0",
"@discordjs/rest": "^0.3.0",
"axios": "^0.25.0",
"discord-api-types": "^0.26.1",
"discord.js": "^14.7.1",
"dotenv": "^14.2.0",
"eslint": "^8.8.0",
"i": "^0.3.7",
"mongoose": "^6.2.1",
"node-cron": "^3.0.0",
"npm": "^8.5.0"
},
"devDependencies": {
"eslint": "^8.35.0"
}
}

56
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() {
const currentDay = new Date().getDate()
const currentMonth = new Date().getMonth() + 1
const currentDay = new Date().getDate();
const currentMonth = new Date().getMonth() + 1;
const guildIds = []
const sysChannelIds = []
const guildIds = [];
const sysChannelIds = [];
client.guilds.cache.forEach(element => {
sysChannelIds.push(element.channels.guild.systemChannelId)
guildIds.push(element.id)
})
const todayBirthdays = await bModel.find({ 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++) {
const guildEvents = await eModel.find({ guild: guildIds[i], day: currentDay, month: currentMonth }).exec()
sysChannelIds.push(element.channels.guild.systemChannelId);
guildIds.push(element.id);
});
const guild = client.guilds.cache.find((g) => g.id == guildIds[i])
for (let j = 0; j < birthdayList.length; j++) {
const userId = birthdayList[j].id
const todayBirthdays = await bModel.find({ 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++) {
const guildEvents = await eModel.find({ guild: guildIds[i], day: currentDay, month: currentMonth }).exec();
const guild = client.guilds.cache.find((g) => g.id == guildIds[i]);
for (let j = 0; j < todayBirthdays.length; j++) {
const userId = todayBirthdays[j].id;
if ((await guild.members.fetch()).find(user => user.id == userId) != undefined) {
const gifAmount = 12
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}> !!!`)
const gifAmount = 12;
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}> !!!`);
client.channels.cache.get(sysChannelIds[i])
.send({ embeds: [embed] })
.send({ embeds: [embed] });
}
}
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])
.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++) {
client.channels.cache.get(sysChannelIds[i])
.send(`It's **${guildEvents[j].name}** today!`)
.send(`It's **${guildEvents[j].name}** today!\n` + guildEvents[j].specialMessage);
}
}
}