Code refactoring, big changes

This commit is contained in:
Ladislav Hano 2023-02-25 13:42:21 +01:00
parent cfebbe67ad
commit 2cf15fbf2a
21 changed files with 1640 additions and 1339 deletions

80
commandBuilder.js Normal file
View file

@ -0,0 +1,80 @@
const cubcommand =
{
name: 'add',
desc: 'Adds new event to the database',
options: [
{
type: 'str',
name: 'name',
desc: 'Name of the event you want to add',
req: true
}
]
}
new SlashCommandBuilder()
.setName('event')
.setDescription('Adds events to celebrate!')
.addSubcommand(subcommand =>
subcommand.setName('add')
.setDescription('Adds new event to the database')
.addStringOption(option => option.setName('name')
.setDescription('Name of the event you want to add')
.setRequired(true))
.addIntegerOption(option =>
option.setName('day')
.setDescription('Day of event')
.setRequired(true))
.addIntegerOption(option =>
option.setName('month')
.setDescription('Month of event')
.setRequired(true))
.addBooleanOption(option =>
option.setName('global')
.setDescription('Should this event display on all servers?'))
.addStringOption(option =>
option.setName('special-message')
.setDescription('Special message to send in event announcement')))
.addSubcommand(subcommand =>
subcommand.setName('delete')
.setDescription('Deletes event from database')
.addIntegerOption(option => option.setName('id')
.setDescription('Id of the even you want to change')
.setRequired(true)))
.addSubcommandGroup(subcommandGroup =>
subcommandGroup.setName('change')
.setDescription('Change the event entry')
.addSubcommand(subcommand =>
subcommand.setName('date')
.setDescription('Change date of an event')
.addIntegerOption(option =>
option.setName('day')
.setDescription('New event day')
.setRequired(true))
.addIntegerOption(option =>
option.setName('month')
.setDescription('New event month')
.setRequired(true))
.addIntegerOption(option => option.setName('id')
.setDescription('Id of the even you want to change')
.setRequired(true)))
.addSubcommand(subcommand =>
subcommand.setName('name')
.setDescription('Change name of an event')
.addStringOption(option =>
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')
.setDescription('Change special message of an event')
.addStringOption(option =>
option.setName('new-message')
.setDescription('New special message')
.setRequired(true))))
.addSubcommand(subcommand =>
subcommand.setName('list')
.setDescription('List all events')),

View file

@ -1,7 +1,7 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const help = require('../helpFunctions.js');
const bModel = require('../database/birthdaySchema.js');
const { bModel } = require('../database/schemas.js');
module.exports = {
data: new SlashCommandBuilder()

View file

@ -1,7 +1,7 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const help = require('../helpFunctions.js');
const eModel = require('../database/eventSchema');
const { eModel } = require('../database/schemas');
module.exports = {
@ -24,7 +24,10 @@ module.exports = {
.setRequired(true))
.addBooleanOption(option =>
option.setName('global')
.setDescription('Should this event display on all servers?')))
.setDescription('Should this event display on all servers?'))
.addStringOption(option =>
option.setName('special-message')
.setDescription('Special message to send in event announcement')))
.addSubcommand(subcommand =>
subcommand.setName('delete')
.setDescription('Deletes event from database')
@ -57,6 +60,13 @@ module.exports = {
.setRequired(true))
.addIntegerOption(option => option.setName('id')
.setDescription('Id of the even you want to change')
.setRequired(true)))
.addSubcommand(subcommand =>
subcommand.setName('special-message')
.setDescription('Change special message of an event')
.addStringOption(option =>
option.setName('new-message')
.setDescription('New special message')
.setRequired(true))))
.addSubcommand(subcommand =>
subcommand.setName('list')
@ -152,50 +162,27 @@ async function addEvent(interaction) {
const ms = new Date().getMilliseconds();
const id = (1000 * day) + (1000 * (ms % 1000)) + month;
// TODO DEDUPLICATE!!!
let error = null;
if (isGlobal) {
try {
const dbEntry = await eModel.create({
guild: 'global',
id: id,
name: name,
day: day,
month: month,
});
dbEntry.save();
error = await sortTable();
}
catch (err) {
error = err;
console.log(err);
}
if (error != null) {
return 'There was an error \n(user is probably already on the birthday list)';
}
return `Successfuly added global event ${name}`;
let guildData = isGlobal ? 'guild' : interaction.guild.id
let eventType = isGlobal ? 'global' : 'guild';
try {
const dbEntry = await eModel.create({
guild: guildData,
id: id,
name: name,
day: day,
month: month,
});
dbEntry.save();
error = await sortTable();
}
else {
try {
const dbEntry = await eModel.create({
guild: interaction.guild.id,
id: id,
name: name,
day: day,
month: month,
});
dbEntry.save();
error = await sortTable();
}
catch (err) {
error = err;
console.log(err);
}
if (error != null) {
return 'There was an error \n(user is probably already on the birthday list)';
}
return `Successfuly added guild event ${name}`;
catch (err) {
error = err;
console.log(err);
return 'There was an error \n(user is probably already on the birthday list)'
}
return `Successfuly added ${eventType} event ${name}`;
}
async function listEvents(interaction) {

View file

@ -3,19 +3,6 @@ const help = require('../helpFunctions.js');
const gifAmount = 50;
require('dotenv').config();
module.exports = {
data: new SlashCommandBuilder()
.setName('gif')
.setDescription('Sends gif')
.addStringOption(option =>
option.setName('what')
.setDescription('What should I search for? (If this is empty I will give you something random!)'))
.addBooleanOption(option => option.setName('r-rated').setDescription('Should the gif be R-rated')),
async execute(interaction) {
const embed = await getGifEmbed(interaction.options);
await interaction.reply({ embeds: [embed] });
},
};
async function getGifEmbed(options) {
let rating = 'low';
@ -36,10 +23,24 @@ 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);
}
}
module.exports = {
data: new SlashCommandBuilder()
.setName('gif')
.setDescription('Sends gif')
.addStringOption(option =>
option.setName('what')
.setDescription('What should I search for? (If this is empty I will give you something random!)'))
.addBooleanOption(option => option.setName('r-rated').setDescription('Should the gif be R-rated')),
async execute(interaction) {
const embed = await getGifEmbed(interaction.options);
await interaction.reply({ embeds: [embed] });
},
};

View file

@ -3,23 +3,23 @@ const help = require('../helpFunctions.js');
require('dotenv').config();
module.exports = {
data: new SlashCommandBuilder()
.setName('headpat')
.setDescription('Headpat someone!')
.addMentionableOption(options =>
options.setName('who')
.setDescription('Is for me? c:')),
async execute(interaction) {
const embed = await headpat(interaction);
interaction.reply({ embeds: [embed] });
},
};
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);
}
}
module.exports = {
data: new SlashCommandBuilder()
.setName('headpat')
.setDescription('Headpat someone!')
.addMentionableOption(options =>
options.setName('who')
.setDescription('Is for me? c:')),
async execute(interaction) {
const embed = await headpat(interaction);
interaction.reply({ embeds: [embed] });
},
};

View file

@ -3,23 +3,24 @@ const help = require('../helpFunctions.js');
require('dotenv').config();
module.exports = {
data: new SlashCommandBuilder()
.setName('hug')
.setDescription('Hug all your friends!')
.addMentionableOption(options =>
options.setName('who')
.setDescription('It\'s not me.. is it? :c')),
async execute(interaction) {
const embed = await hug(interaction);
interaction.reply({ embeds: [embed] });
},
};
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);
}
}
module.exports = {
data: new SlashCommandBuilder()
.setName('hug')
.setDescription('Hug all your friends!')
.addMentionableOption(options =>
options.setName('who')
.setDescription('It\'s not me.. is it? :c')),
async execute(interaction) {
const embed = await hug(interaction);
interaction.reply({ embeds: [embed] });
},
};

View file

@ -1,5 +1,11 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
function say(interaction) {
const message = interaction.options.getString('what');
message.trim();
interaction.channel.send(message);
}
module.exports = {
data: new SlashCommandBuilder()
.setName('say')
@ -12,10 +18,4 @@ module.exports = {
await say(interaction);
await interaction.reply({ content: 'Said and done', ephemeral: true });
},
};
function say(interaction) {
const message = interaction.options.getString('what');
message.trim();
interaction.channel.send(message);
}
};

View file

@ -1,17 +0,0 @@
const mongoose = require('mongoose');
const birthdaySchema = new mongoose.Schema({
id: {
type: String,
unique: true,
},
day: Number,
month: Number,
nickname: {
type: String,
default: '',
},
});
module.exports=mongoose.model('birthdays', birthdaySchema);

View file

@ -1,35 +0,0 @@
module.exports = {
addToDB: addToDB,
updateDB: updateDB,
deleteEntry: deleteEntry,
findById: findById,
};
async function addToDB(option, data) {
const model = require(`./${data.name}Schema`);
try {
const dbEntry = await model.create({
guild: 'global',
name: 'Valentine\'s Day',
day: 14,
month: 2,
});
dbEntry.save();
}
catch (err) {
return err;
}
return null;
}
async function updateDB(query) {
}
async function deleteEntry(query) {
}
async function findById(id) {
}
async function findByName(name) {
}

View file

@ -1,17 +0,0 @@
const mongoose = require('mongoose');
const Events = new mongoose.Schema({
guild: String,
id: {
type: Number,
index: true,
unique: true,
},
name: String,
day: Number,
month: Number,
});
const eventsModule = mongoose.model('events', Events);
module.exports = eventsModule;

36
database/schemas.js Normal file
View file

@ -0,0 +1,36 @@
const mongoose = require('mongoose');
const birthdaySchema = new mongoose.Schema({
id: {
type: String,
unique: true,
},
day: Number,
month: Number,
nickname: {
type: String,
default: '',
},
});
const bdmodel = mongoose.model('birthdays', birthdaySchema);
const eventSchema = new mongoose.Schema({
guild: String,
id: {
type: Number,
index: true,
unique: true,
},
name: String,
day: Number,
month: Number,
specialMessage: String
});
const emodel = mongoose.model('events', eventSchema)
module.exports = {
bModel: bdmodel,
eModel: emodel
};

View file

@ -1,19 +1,31 @@
const fs = require('fs');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { REST, Routes } = require('discord.js');
require('dotenv').config();
const fd = require('node:fs');
const path = require('node:path');
const commands = [];
const commandFiles = fs.readdirSync('./commands')
.filter(file => !file.includes('WIP'));
const commandsPath = path.join(__dirname, 'commands')
const commandFiles = fs.readdirSync(commandsPath).filter(file => !file.includes('WIP'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(process.env.MOOTOKEN);
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
rest.put(Routes.applicationCommands(process.env.mooverId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(process.env.debugId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();

37
gifs.js Normal file
View file

@ -0,0 +1,37 @@
const axios = require('axios').default;
const Discord = require('discord.js');
module.exports({
getGifs: getGifs,
getGifEmbed: getGifEmbed,
getGifWithMessage: getGifWithMessage
})
async function getGifs(gifs) {
return new Promise((resolve) => {
resolve(axios.get(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()
.setImage(gif)
.setColor(randomColor());
return gifEmbed;
}
async function getGifWithMessage(interaction, gifQuery, gifAmount) {
const gifEmbed = await getGifEmbed(gifQuery, gifAmount);
const who = interaction.options.getMentionable('who');
if (who == null) {
return gifEmbed;
}
gifEmbed.setDescription(interaction.user.username
+ ` ${interaction.commandName}s ` + `${who}`);
return gifEmbed;
}

View file

@ -1,14 +1,8 @@
const axios = require('axios').default;
const Discord = require('discord.js');
require('dotenv').config();
module.exports = {
randomColor: randomColor,
RNG: RNG,
getGifs: getGifs,
getGifEmbed: getGifEmbed,
getGifWithMessage: getGifWithMessage,
returnPromiseString: returnPromiseString,
};
@ -26,33 +20,6 @@ function RNG(max) {
return Math.floor(Math.random() * max);
}
async function getGifs(gifs) {
return new Promise((resolve) => {
resolve(axios.get(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()
.setImage(gif)
.setColor(randomColor());
return gifEmbed;
}
async function getGifWithMessage(interaction, gifQuery, gifAmount) {
const gifEmbed = await getGifEmbed(gifQuery, gifAmount);
const who = interaction.options.getMentionable('who');
if (who == null) {
return gifEmbed;
}
gifEmbed.setDescription(interaction.user.username
+ ` ${interaction.commandName}s ` + `${who}`);
return gifEmbed;
}
async function returnPromiseString(guildMembers) {
return new Promise(() => {
guildMembers.fetch();

204
main.js
View file

@ -2,6 +2,7 @@
List of intents
https://discord.com/developers/docs/topics/gateway#privileged-intents
*/
require('dotenv').config()
var http = require('http')
http.createServer(function (req, res) {
@ -9,19 +10,18 @@ http.createServer(function (req, res) {
res.end('Hello World\n')
}).listen(5000, "127.0.0.1")
const Discord = require('discord.js')
const {
Client,
Collection,
Intents,
MessageAttachment,
GatewayIntentBits
} = require('discord.js')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_MEMBERS,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
],
})
@ -37,30 +37,25 @@ for (const file of commandFiles) {
client.commands.set(command.data.name, command)
}
require('dotenv').config()
const help = require('./helpFunctions.js')
const resp = require('./responses.js')
const bModel = require('./database/birthdaySchema')
const eModel = require('./database/eventSchema')
const mongoose = require('mongoose')
async function dbConnect() {
mongoose.connect(process.env.DBSRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to database')
}).catch((err) => {
console.log(err)
}).then(() => {
console.log('Connected to database')
}).catch((err) => {
console.log(err)
})
}
const help = require('./helpFunctions.js')
const cron = require('node-cron')
let gotMessage;
client.once('ready', async () => {
let specialMessage = '\n Don\'t forget I love you all with all my hart 🥺'
gotMessage = require('./messageHandler');
const ping = require('./ping')
if (client.user.username != 'MOOver Debug') {
const turnOnMsg = ['AAAAAAAAAAAAA', 'Just turned on!',
'Just woke up!', 'May have crashed... sowwyyy >.<',
@ -68,13 +63,19 @@ client.once('ready', async () => {
client.channels.cache.get('780439236867653635').send(turnOnMsg[help.RNG(turnOnMsg.length)]);
}
cron.schedule('0 13 * * *', async function () {
pingEvent()
ping()
})
await dbConnect();
const { eModel } = require('./database/schemas');
eModel.updateMany({}, { $set: { specialMessage: "" }}).exec()
console.log('Running!')
})
client.on('messageCreate', gotMessage)
client.on('messageCreate', (message) => {
gotMessage(message)
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return
@ -95,159 +96,6 @@ client.on('interactionCreate', async interaction => {
}
})
function gotMessage(message) {
if (process.env.DEBUG == "ON") {
const debugger_ = require('./.debug.js')
debugger_.debug(message)
}
const chance = help.RNG(50000)
if (chance == 420) {
resp.whoAsked(message)
}
const msg = message.content.toLowerCase()
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
*/
if (message.reference != null && msgContentSplit.length == 1 &&
message.mentions.channels.first() != undefined) {
moveMessage(message, msgContentSplit[0])
}
const isBot = message.author.bot
if (!isBot) {
if (msg.includes('henlo')) {
resp.henlo(message)
}
else if (msg.includes('how ye')) {
resp.mood(message)
}
else if (msg.includes('tylko jedno')) {
message.reply('Koksu pięć gram odlecieć sam')
}
}
}
function moveMessage(message, channelId) {
message.react('🐮')
const originalChannel = message.channel
const msgToMooveId = message.reference.messageId
const mentionedChannelId = channelId.substring(2, channelId.length - 1)
originalChannel.messages.fetch(msgToMooveId).then(msg => {
if (msg.embeds.length > 0 && msg.content == '' && msg.attachments.size == 0) {
client.channels.cache.get(mentionedChannelId).send({ embeds: msg.embeds })
}
else if (msg.attachments.size > 0) {
let attachmentsURL = ""
const originalMsgAttachments = msg.attachments.values()
for (let i = 0; i < msg.attachments.size; i++) {
const currAttachment = originalMsgAttachments.next().value
attachmentsURL += `${currAttachment.url}\n`
}
let messStr = ""
if (msg.content != '') {
messStr = "\nMessage:\n"
}
newContent = `Sent by ${msg.author}\nmooved ${message.author}\n${messStr}${msg.content}\nAttachments:\n${attachmentsURL}`
client.channels.cache.get(mentionedChannelId).send({ content: newContent })
if (msg.embeds.length > 0) {
client.channels.cache.get(mentionedChannelId)
.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}`
})
}
// ? Has content, No embeds
else {
const embed = new Discord.MessageEmbed()
.setColor(help.randomColor())
.addField('MOO', `Sent by ${msg.author}\nmooved ${message.author}`)
.addField('Message', msg.content)
client.channels.cache.get(mentionedChannelId).send({ embeds: [embed] })
}
}
setTimeout(() => msg.delete(), 3000)
})
setTimeout(() => message.delete(), 3000)
}
async function pingEvent() {
const currentDay = new Date().getDate()
const currentMonth = new Date().getMonth() + 1
let query = bModel.find({ day: currentDay, month: currentMonth })
const birthdayList = await query.exec()
query = eModel.find({ guild: 'global', day: currentDay, month: currentMonth })
const globalEventList = await query.exec()
const guildIds = []
const sysChannelIds = []
client.guilds.cache.forEach(element => {
sysChannelIds.push(element.channels.guild.systemChannelId)
guildIds.push(element.id)
})
// TODO deduplicate
const todayBirthdays = []
if (todayBirthdays != []) {
for (let i = 0; i < guildIds.length; i++) {
const guildId = guildIds[i]
const sysChannelId = sysChannelIds[i]
const guild = client.guilds.cache.find((g) => g.id == guildId)
for (let j = 0; j < birthdayList.length; j++) {
const userId = birthdayList[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}> !!!`)
client.channels.cache.get(sysChannelId)
.send({ embeds: [embed] })
}
}
}
}
for (let i = 0; i < guildIds.length; i++) {
const guildId = guildIds[i]
const sysChannelId = sysChannelIds[i]
query = eModel.find({ guild: guildId, day: currentDay, month: currentMonth })
const guildEvents = await query.exec()
for (let j = 0; j < globalEventList.length; j++) {
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(sysChannelId)
.send(`It's **${globalEventList[j].name}** today!` + specialMessage)
}
for (let j = 0; j < guildEvents.length; j++) {
client.channels.cache.get(sysChannelId)
.send(`It's **${guildEvents[j].name}** today!`)
}
}
}
client.login(process.env.TOKEN)
module.exports = client

67
messageHandler.js Normal file
View file

@ -0,0 +1,67 @@
const moove = require("./moove")
function gotMessage(message) {
if (message.author.bot) {
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
*/
if (message.reference != null && msgContentSplit.length == 1 &&
message.mentions.channels.first() != undefined) {
moove(message, msgContentSplit[0])
}
const msg = message.content.toLowerCase()
const chance = help.RNG(50000)
if (chance == 420) {
whoAsked(message)
}
if (msg.includes('henlo')) {
henlo(message)
}
else if (msg.includes('how ye')) {
mood(message)
}
else if (msg.includes('tylko jedno')) {
message.reply('Koksu pięć gram odlecieć sam')
}
if (process.env.DEBUG == "ON") {
const debugger_ = require('./.debug.js')
debugger_.debug(message)
}
}
function henlo(message) {
const emojis = ['🥰', '🐄', '🐮', '❤️', '👋', '🤠', '😊'];
const randomNum = help.RNG(emojis.length);
message.reply('Henlooo ' + message.author.username + ' ' + emojis[randomNum]);
}
function mood(message) {
const responses = ['Not bad, how yee?', 'MOOdy', 'A bit sad 😢', 'Good, how yee?', 'I\'m fine, how yee?'];
const randomNum = help.RNG(responses.length);
message.reply(responses[randomNum]);
}
async function whoAsked(message) {
if (message.embeds.length == 0 && message.attachments.size == 0 && message.content != '') {
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)] });
}
}
module.exports = gotMessage;

65
moove.js Normal file
View file

@ -0,0 +1,65 @@
const Discord = require('discord.js')
const help = require('./helpFunctions')
const client= require('./main')
function moove(message, channelId) {
message.react('🐮')
const originalChannel = message.channel
const msgToMooveId = message.reference.messageId
const mentionedChannelId = channelId.substring(2, channelId.length - 1)
console.log(mentionedChannelId)
return;
originalChannel.messages.fetch(msgToMooveId).then(msg => {
if (msg.embeds.length > 0 && msg.content == '' && msg.attachments.size == 0) {
client.getChannel(mentionedChannelId).send({ embeds: msg.embeds })
}
else if (msg.attachments.size > 0) {
let attachmentsURL = ""
const originalMsgAttachments = msg.attachments.values()
for (let i = 0; i < msg.attachments.size; i++) {
const currAttachment = originalMsgAttachments.next().value
attachmentsURL += `${currAttachment.url}\n`
}
let messStr = ""
if (msg.content != '') {
messStr = "\nMessage:\n"
}
newContent = `Sent by ${msg.author}\nmooved ${message.author}\n${messStr}${msg.content}\nAttachments:\n${attachmentsURL}`
client.channels.cache.get(mentionedChannelId).send({ content: newContent })
if (msg.embeds.length > 0) {
client.channels.cache.get(mentionedChannelId)
.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}`
})
}
// ? Has content, No embeds
else {
const embed = new Discord.MessageEmbed()
.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] })
}
}
setTimeout(() => msg.delete(), 3000)
})
setTimeout(() => message.delete(), 3000)
}
module.exports = moove

2093
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -7,9 +7,6 @@
"webhook": "node git_webhook.js",
"moover": "node main.js"
},
"engines": {
"node": "16.x"
},
"author": "",
"license": "ISC",
"dependencies": {
@ -17,7 +14,7 @@
"@discordjs/rest": "^0.3.0",
"axios": "^0.25.0",
"discord-api-types": "^0.26.1",
"discord.js": "^13.6.0",
"discord.js": "^14.7.1",
"dotenv": "^14.2.0",
"eslint": "^8.8.0",
"i": "^0.3.7",
@ -25,4 +22,4 @@
"node-cron": "^3.0.0",
"npm": "^8.5.0"
}
}
}

48
ping.js Normal file
View file

@ -0,0 +1,48 @@
require('dotenv').config()
module.exports = pingEvent
async function pingEvent() {
const currentDay = new Date().getDate()
const currentMonth = new Date().getMonth() + 1
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()
const guild = client.guilds.cache.find((g) => g.id == guildIds[i])
for (let j = 0; j < birthdayList.length; j++) {
const userId = birthdayList[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}> !!!`)
client.channels.cache.get(sysChannelIds[i])
.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)
}
for (let j = 0; j < guildEvents.length; j++) {
client.channels.cache.get(sysChannelIds[i])
.send(`It's **${guildEvents[j].name}** today!`)
}
}
}

View file

@ -1,29 +0,0 @@
const help = require('./helpFunctions');
module.exports = {
henlo: henlo,
mood: mood,
whoAsked: whoAsked,
};
function henlo(message) {
const emojis = ['🥰', '🐄', '🐮', '❤️', '👋', '🤠', '😊'];
const randomNum = help.RNG(emojis.length);
message.reply('Henlooo ' + message.author.username + ' ' + emojis[randomNum]);
}
function mood(message) {
const responses = ['Not bad, how yee?', 'MOOdy', 'A bit sad 😢', 'Good, how yee?', 'I\'m fine, how yee?'];
const randomNum = help.RNG(responses.length);
message.reply(responses[randomNum]);
}
async function whoAsked(message) {
if (message.embeds.length == 0 && message.attachments.size == 0 && message.content != '') {
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)] });
}
}