I have been trying to fix this for a few days and I can't fix it. The problem is my "boosted guild on" part of my userinfo is showing up as a date even for people who haven't boosted the server. Please help. For more information, or to see the problem in depth, contact me on discord via Disown .#7397.
const Discord = require('discord.js');
const moment = require('moment');
const { color } = require("../../config.json");
const { verifiedBotDev } = require("../../emojis.json");
const { bugHunter } = require("../../emojis.json");
const { bugHunterPlus } = require("../../emojis.json");
const { discordPartner } = require("../../emojis.json");
const { discordStaff } = require("../../emojis.json");
const { hypeSquad } = require("../../emojis.json");
const { hypeSquadBravery } = require("../../emojis.json");
const { hypeSquadBril } = require("../../emojis.json");
const { hypeSquadBal } = require("../../emojis.json");
const { verifiedBot } = require("../../emojis.json");
const { earlySupporter } = require("../../emojis.json");
const { discordnitro } = require("../../emojis.json");
const flags = {
DISCORD_EMPLOYEE: `${discordStaff}`,
DISCORD_PARTNER: `${discordPartner}`,
BUGHUNTER_LEVEL_1: `${bugHunter}`,
BUGHUNTER_LEVEL_2: `${bugHunterPlus}`,
HYPESQUAD_EVENTS: `${hypeSquad}`,
HOUSE_BRAVERY: `${hypeSquadBravery}`,
HOUSE_BRILLIANCE: `${hypeSquadBril}`,
HOUSE_BALANCE: `${hypeSquadBal}`,
EARLY_SUPPORTER: `${earlySupporter}`,
VERIFIED_BOT: `${verifiedBot}`,
VERIFIED_DEVELOPER: `${verifiedBotDev}`,
Discord_Nitro : `${discordnitro}`
};
module.exports = {
name: "uitest",
aliases: ["uit", "uinfo", "info"],
run: async (client, message, args) => {
let mentionedMember = await message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args.join(' ').toLocaleLowerCase()) || message.guild.members.cache.find(r => r.displayName.toLowerCase() === args.join(' ').toLocaleLowerCase()) || args[0] || message.member;
const user = await client.users.fetch(client.users.resolveID(mentionedMember)).catch(() => null);
if (!user) user = message.author;
const userFlags = user.flags.toArray();
let nickname = user.nickname
if (nickname) {
nickname = `∙ ${user.nickname}`;
} else {
nickname = ''
}
let flags2 = user.flags2
if (flags) {
flags2 = `∙ ${userFlags.length ? userFlags.map(flag => flags[flag]).join(' ') : ' '}`;
} else {
flags2 = ''
}
let bot;
if (user.bot === true) {
bot = "Discord Bot";
} else {
bot = "N/A";
}
const userPos = message.guild.members.cache
.sort((a, b) => a.joinedTimestamp - b.joinedTimestamp)
.array();
const position = new Promise((fui) => {
for (let i = 1; i < userPos.length + 1; i++) {
if (userPos[i - 1].id === user.id) fui(i);
}
});
const activities = [];
let customStatus;
for (const activity of user.presence.activities.values()) {
switch (activity.type) {
case 'LISTENING':
if (user.bot) activities.push(`Listening to **${activity.name}**`);
else activities.push(`Listening to [**${activity.details}**](https://open.spotify.com//) by **${activity.state}**`);
break;
case 'CUSTOM_STATUS':
customStatus = activity.state;
break;
}
}
const embed = new Discord.MessageEmbed()
.setColor(mentionedMember.displayHexColor || color)
.setThumbnail(user.displayAvatarURL({ format: "png", dynamic: true, size: 2048 }))
.setAuthor(message.author.username, message.author.avatarURL({
dynamic: true
}))
.setTitle(`${user.tag} ${nickname} ${flags2}`)
.setDescription(`${activities.join('\n')}\n\`\`${user.id}\`\` ∙ Join position:`)
.setFooter(`${bot}`)
.setTimestamp()
.addFields(
{
name: "**Joined Discord On**",
value: `${moment(user.createdAt).format("dddd, MMMM Do YYYY, h:mm A")}`,
inline: true
},
{
name: "**Joined Guild On**",
value: `${user.joinedAt === 0
? `N/A`
: `${moment.utc(message.member.joinedAt).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true
},
{
name: '**Boosted Guild On**',
value: `${user.premiumSinceTimestamp === 0
? `N/A`
: `${moment(user.premiumSince).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true,
},
{
name: `**Role List [${mentionedMember.roles.size || ""}]**`,
value: `${mentionedMember.roles.cache
.filter(r => r.id !== message.guild.id).map(roles => `<#&${roles.id}>`)
.join(", ") || "N/A"}`,
inline: true
})
message.channel.send(embed)
}
}
premiumSinceTimestamp returns null if the member never boosted the guild and null is not the same as 0.
When you check if user.premiumSinceTimestamp === 0 it will always return false because it's either a timestamp or null. You only need to check if the value of premiumSinceTimestamp is truthy like this:
{
name: '**Boosted Guild On**',
value: user.premiumSinceTimestamp
? moment(user.premiumSince).format('dddd, MMMM Do YYYY, h:mm A')
: 'N/A',
inline: true,
};
You currently did the following:
{
name: '**Boosted Guild On**',
value: `${user.premiumSinceTimestamp === 0 ? `N/A` : `${moment(user.premiumSince).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true,
},
While the syntax is:
<condition> ? <if condition is true> : <if condition is false>
You used the function the other way around, you should simply change the order of N/A and ${moment(user.....
Related
I am creating a Discord command handler using discord.js version 14.4.0 but I keep getting this error, here is my code:
const settings = require(`${process.cwd()}/config/settings.json`);
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const Discord = require("discord.js");
module.exports = {
name: "hello",
description: "say hello!",
cooldown: settings.cooldown,
memberpermissions: [],
requiredroles: [],
alloweduserids: [],
type: Discord.ApplicationCommandType.ChatInput,
options: [],
run: async (client, interaction) => {
try {
interaction.reply({ content: `${client.word.hello}` });
} catch (error) {
console.log(colors.red(error));
let somethingWrong = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| Something wrong!")
.setDescription(`❌| Sorry, I failed setting up...!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [somethingWrong], ephemeral: true });
}
}
};
The error I get when running that command:
interaction.reply({ content: `${client.word.hello}` });
and this my index.js file:
const lang_db = require("./dataBases/db");
const dotenv = require("dotenv"); dotenv.config();
const colors = require("colors");
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [32767],
partials: [
Discord.Partials.GuildScheduledEvent,
Discord.Partials.ThreadMember,
Discord.Partials.GuildMember,
Discord.Partials.Reaction,
Discord.Partials.Channel,
Discord.Partials.Message,
Discord.Partials.User,
],
});
client.slashCommands = new Discord.Collection();
module.exports = client;
fs.readdirSync("./handlers").forEach((handler) => {
require(`./handlers/${handler}`)(client);
});
client.on("interactionCreate", async (interaction) => {
let lang = await lang_db.get(`language_${interaction.guild.id}`);
if(lang == null) {
lang = "en";
} else if(lang == "ar") {
lang = "ar"
}
let word = require(`./languages/${lang}.json`);
client.word = word;
});
client.login(process.env.TOKEN).catch((error) => {
console.log(colors.red(error));
});
TypeError: Cannot read properties of undefined (reading 'hello')
handlers/slashCommand.js
const colors = require("colors");
const fs = require("fs");
const AsciiTable = require("ascii-table");
const table = new AsciiTable().setHeading("Slash Commands", "Stats").setBorder("|", "=", "0", "0");
const { Routes } = require("discord-api-types/v9");
const { REST } = require("#discordjs/rest");
const Discord = require("discord.js");
const APPLICATION_ID = process.env.APPLICATION_ID;
const TOKEN = process.env.TOKEN;
const rest = new REST({ version: "10" }).setToken(TOKEN);
module.exports = (client) => {
const slashCommands = [];
fs.readdirSync("./slashCommands/").forEach(async (dir) => {
const files = fs.readdirSync(`./slashCommands/${dir}/`).filter((file) => file.endsWith(".js"));
for (const file of files) {
const slashCommand = require(`../slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
type: slashCommand.type,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? Discord.PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null,
});
if (slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split(".js")[0], "✅");
} else {
table.addRow(file.split(".js")[0], "⛔");
}
}
});
console.log(colors.green(table.toString()));
(async () => {
try {
const data = await rest.put(process.env.GUILD_ID ? Routes.applicationGuildCommands(APPLICATION_ID, process.env.GUILD_ID) : Routes.applicationCommands(APPLICATION_ID), { body: slashCommands });
console.log(colors.green(`Started refreshing ${slashCommands.length} application (/) commands.`));
console.log(colors.green(`Successfully reloaded ${data.length} application (/) commands.`));
} catch (error) {
console.log(colors.red(error));
}
})();
};
events/guid/interactionCreate.js
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const ms = require("ms");
const Discord = require("discord.js");
const client = require("../..");
const delay = new Discord.Collection();
client.on("interactionCreate", async (interaction) => {
const slashCommand = client.slashCommands.get(interaction.commandName);
if (interaction.type == 4) {
if (slashCommand.autocomplete) {
const choices = [];
await slashCommand.autocomplete(interaction, choices);
}
}
if (!interaction.type == 2) return;
if (!slashCommand)
return client.slashCommands.delete(interaction.commandName);
try {
if (slashCommand.cooldown) {
if (delay.has(`${slashCommand.name}-${interaction.user.id}`)) {
let time = ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true }).includes("ms") ? "0 second" : ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true });
let timeLeft = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| Please wait **${time}** before reusing the \`${slashCommand.name}\` command!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [timeLeft], ephemeral: true });
}
}
if (slashCommand.memberpermissions && slashCommand.memberpermissions.length > 0 && !interaction.member.permissions.has(slashCommand.memberpermissions)) {
let memberPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need these Permission(s): \`${slashCommand.memberpermissions}\``)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [memberPerms], ephemeral: true });
}
if (slashCommand.requiredroles && slashCommand.requiredroles.length > 0 && interaction.member.roles.cache.size > 0 && !interaction.member.roles.cache.some(r => slashCommand.requiredroles.includes(r.id))) {
let rolesPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to have one of the Following Roles: <#&${slashCommand.requiredroles}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [rolesPerms], ephemeral: true });
}
if (slashCommand.alloweduserids && slashCommand.alloweduserids.length > 0 && !slashCommand.alloweduserids.includes(interaction.member.id)) {
let userPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to be one of the Following Users: <#!${slashCommand.alloweduserids}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [userPerms], ephemeral: true });
}
await slashCommand.run(client, interaction);
delay.set(`${slashCommand.name}-${interaction.user.id}`, Date.now() + slashCommand.cooldown * 1000);
setTimeout(() => {
delay.delete(`${slashCommand.name}-${interaction.user.id}`);
}, slashCommand.cooldown * 1000);
} catch (error) {
console.log(colors.red(error));
}
});
I don't know why this is happening, please could someone help me?
const { Client, Message, MessageEmbed, Intents } = require("discord.js");
module.exports = {
name: "sbfeedback",
/**
* #parom {Client} client
* #parom {Message} message
* #parom {String[]} args
*/
async execute(client, message, args) {
const questions = [
"What feedback would you like to give?",
"Anything else you would like to add?"
];
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++]);
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
message.delete({timeout: 100})
collector.on("collect", () => {
if (collectCounter < questions.length) {
channel.send(questions[collectCounter++]);
} else {
channel.send("Thank you for your feedback! If you would like to suggest anything else please do so with `-sbfeedback`.");
collector.stop("fulfilled");
}
});
const appsChannel = client.channels.cache.get("886099865094983691");
collector.on("end", (collected, reason) =>{
if (reason === "fulfilled") {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join("\n\n");
appsChannel.send(
new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
.setTitle("!")
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp()
);
message.react('👍').then(() => message.react('👎'));
}
});
},
appsChannel.send returns a Promise and once it's resolved, you can grab the sent message, so you can add your reactions:
collector.on('end', (collected, reason) => {
if (reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join('\n\n');
appsChannel
.send(
new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: true }),
)
.setTitle('!')
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp(),
)
.then((sent) => {
sent.react('👍');
sent.react('👎');
});
}
});
I'm trying to make a horse race command for my discord bot (TypeScript).
The code itself works fine, but I have to update an embed which contains the race and the participants. The thing is that for it to properly update, I have to set its description every time that collector.on("collect") fires. I want to ask if there's a better, more efficient and cleaner way to update it. Thank you! code:
const bet = interaction.options.get("bet").value;
class Horse {
name: string;
owner: User;
speed: number;
position: Array<string>;
constructor(name: string) {
this.name = name;
this.owner = null;
this.speed = 0;
this.position = ["🐴"];
}
}
const horses = [
new Horse(aimless.pick(names, { remove: true })),
new Horse(aimless.pick(names, { remove: true })),
new Horse(aimless.pick(names, { remove: true })),
new Horse(aimless.pick(names, { remove: false })),
];
const hasJoined: Array<Horse["owner"]> = [];
const row = new MessageActionRow();
for (const horse of horses) {
row.addComponents(
new MessageButton()
.setCustomId(horse.name)
.setLabel(horse.name)
.setStyle("SECONDARY")
);
}
const embed = new MessageEmbed()
.setTitle("Place your bets!")
.setDescription(
`**${horses[0].name} - ${
horses[0].owner !== null ? horses[0].owner.username : "Nobody"
}
${horses[0].position}
${horses[1].name} - ${
horses[1].owner !== null ? horses[1].owner.username : "Nobody"
}
${horses[1].position}
${horses[2].name} - ${
horses[2].owner !== null ? horses[2].owner.username : "Nobody"
}
${horses[2].position}
${horses[3].name} - ${
horses[3].owner !== null ? horses[3].owner.username : "Nobody"
}
${horses[3].position}**`
);
await interaction.editReply({
embeds: [embed],
components: [row],
});
const filter = async (i: MessageComponentInteraction) => {
let profile: any;
try {
profile = await profileModel.findOne({ userID: i.user.id });
if (!profile) {
await profileModel.create({
userID: i.user.id,
serverID: i.guild?.id,
username: i.user.username,
bananas: 100,
deposit: 0,
});
profile.save();
}
} catch (e) {
await i.editReply("Something went wrong! :( Please retry.");
} finally {
if (hasJoined.includes(i.user)) {
return false;
}
if (profile.bananas < bet) {
interaction.editReply(`${i.user} you don't have enough bananas!`);
}
return profile.bananas >= bet;
}
};
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 60000,
});
collector.on("collect", async (int) => {
await int.deferUpdate();
for (const btn of row.components) {
if (btn.customId === (int.component as MessageButton).customId) {
(btn as MessageButton).setDisabled(true).setStyle("SUCCESS");
hasJoined.push(int.user);
horses.find((h) => h.name === btn.customId).owner = int.user;
console.log(horses);
}
}
embed.setDescription(
`**${horses[0].name} - ${
horses[0].owner !== null ? horses[0].owner.username : "Nobody"
}
${horses[0].position}
${horses[1].name} - ${
horses[1].owner !== null ? horses[1].owner.username : "Nobody"
}
${horses[1].position}
${horses[2].name} - ${
horses[2].owner !== null ? horses[2].owner.username : "Nobody"
}
${horses[2].position}
${horses[3].name} - ${
horses[3].owner !== null ? horses[3].owner.username : "Nobody"
}
${horses[3].position}**`
);
await int.editReply({
embeds: [embed],
components: [row],
});
});
},
});`
You could make it into a function:
const displayHorses = (horses: Array<Horse>) => {
return `**${horses[0].name} - ${
horses[0].owner !== null ? horses[0].owner.username : "Nobody"
}
${horses[0].position}
${horses[1].name} - ${
horses[1].owner !== null ? horses[1].owner.username : "Nobody"
}
${horses[1].position}
${horses[2].name} - ${
horses[2].owner !== null ? horses[2].owner.username : "Nobody"
}
${horses[2].position}
${horses[3].name} - ${
horses[3].owner !== null ? horses[3].owner.username : "Nobody"
}
${horses[3].position}**`;
};
And then every time:
embed.setDescription(displayHorses(horses));
If you want to compact it even further, you could map the horse array.
const displayHorses = (horses: Array<Horse>) => {
return horses.map(
({ name, owner, position }) =>
`**${name}** - ${owner !== null ? owner.username : "Nobody"}
${position}`
);
};
Lastly, as a tip, if you're using 14+, you could compact it even further to:
const displayHorses = (horses: Array<Horse>) => {
return horses.map(
({ name, owner, position }) =>
`**${name}** - ${owner?.username ?? "Nobody"}
${position}`
);
};
Basically my bot is taking too long to send me the results for the video research he made on youtube. I do believe that the problem is in this for loop, but I'm not sure about it
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
This is the entire code to the play command:
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search');
const { User } = require('discord.js');
const { accessSync } = require('fs');
module.exports = {
name: 'play',
description: "Plays video from youtube on a earrape mode",
async execute(client, message, args){
const voiceChannel = message.member.voice.channel;
//Check if person is in voice chat
if(!voiceChannel) return message.channel.send('You need to be in a voice chat to execute this command');
//Check person permissions
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT' || 'SPEAK')) return message.channel.send('You dont have the permission to execute this command');
//Check if message has arguments
if(!args.length) return message.channel.send('You need to send some keywords')
var searchResults = [];
//Bot join VC
const connection = await voiceChannel.join();
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
let filter = m => m.author.id === message.author.id
var whichVideo = null;
await message.channel.send({embed: {
color: 3447003,
title: "Select your music:",
fields: [
{
name: `1.`,
value: `***[${searchResults[0].title}](${searchResults[0].url})***`
},
{
name: `2.`,
value: `***[${searchResults[1].title}](${searchResults[1].url})***`
},
{
name: `3.`,
value: `***[${searchResults[2].title}](${searchResults[2].url})***`
},
{
name: `4.`,
value: `***[${searchResults[3].title}](${searchResults[3].url})***`
},
{
name: `5.`,
value: `***[${searchResults[4].title}](${searchResults[4].url})***`
}
],
footer: {
icon_url: client.user.avatarURL,
text: "Timeout in 30 seconds"
}
}
})
.then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content == '1' || message.content == '2' || message.content == '3' || message.content == '4' || message.content == '5'){
whichVideo = parseInt(message.content) - 1;
message.channel.send(`:musical_note: added ~ ***${searchResults[whichVideo].title}*** ~ to the queue`);
try{
message.channel.send(`:loud_sound: :notes: Now Playing: ~ ***${searchResults[whichVideo].title}*** ~`);
//Get only the audio of the video
const stream = ytdl(searchResults[whichVideo].url, {filter: 'audioonly'});
//Bot joins plays music
connection.play(stream, {seek: 0, volume: 1})
//Leave when music ends
.on('finish', () =>{
voiceChannel.leave();
});
} catch (e){
console.log(e);
voiceChannel.leave();
}
} else {
message.channel.send('');
}
})
.catch(collected => {
message.channel.send('');
});
})
}
}
I am not 100% sure, but I think the issue is in this part:
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
You are launching 4 searches (?)
Try using this library instead:
var search = require('youtube-search');
var opts = {
maxResults: 4,
key: 'Your YouTube API V3 key'
};
search('video title', opts, function(err, results) {
if(err) return console.log(err);
console.dir(results);
});
This way you can search for 4 results at the same time, this should speed up your process.
I have been trying to make a function where I tell the bot what channel to deploy the points system in. I am also using MongoDB so that when my bot restarts, it remembers what channel the points system was set in. However, I am getting errors such as 404: Not Found and it does not even update the schema, so as a result, I am looking for available solutions. Here's my code:
const {
prefix,
} = require('./config.json')
const Discord = require('discord.js')
var date = new Date().toLocaleString();
module.exports = (client) => {
const Mongo = require('mongoose')
const LeaderboardSequence = require('./leaderboard.js')
const SLSchema = require('./setLeaderboard.js')
const mongoose = require('mongoose')
mongoose.connect('insert URL here', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
client.on('message', async message => {
if (message.content === `${prefix}setLeaderboardChannel`) {
// Destructure the guild and channel properties from the message object
const { guild, channel } = message
// Use find one and update to either update or insert the
// data depending on if it exists already
await SLSchema.findOneAndUpdate(
{
_id: guild.id,
},
{
_id: guild.id,
channelId: channel.id,
},
{
upsert: true,
}
)
message.reply(`The points channel has been set to <#${channel.id}>!`)
}
});
client.on('message', async message => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (message.channel.id = channelId) {
if (message.attachments.size > 0) {
message.react('🔼')
message.react('🔽')
} else {
message.delete()
}
}
})
client.on('messageReactionAdd', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (user.id === client.user.id) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (reaction.emoji.name === "🔼") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "🔽") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('messageReactionRemove', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (user.id === client.user.id) return;
if (reaction.emoji.name === "🔼") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "🔽") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('message', async message => {
if (message.content === `${prefix}leaderboard`) {
const Users = await LeaderboardSequence.find({guildID: message.guild.id}).sort({ points: -1 })
const embedArray = []
for (var i = 0; i < Users.length % 10 + 1; i++) {
const leaderboard = new Discord.MessageEmbed()
.setTitle(`Here is ${message.guild}'s points leaderboard!`)
.setColor("RANDOM")
.setThumbnail("https://pbs.twimg.com/media/D7ShRPYXoAA-XXB.jpg")
let text = ""
for (var j = 0; j < 10; j++) {
if (!Users[ i * 10 + j ]) break;
text += `${i * 10 + j + 1}. <#${Users[ i * 10 + j ].userid}>: ${Users[ i * 10 + j ].points}\n`
}
leaderboard.setDescription(text)
.setFooter("By (username) and (username), for everyone with the magic of discord.js.")
.setTimestamp()
embedArray.push(leaderboard)
}
paginate(message, embedArray)
}
});
const reactions = ['◀️', '⏸️', '▶️']
async function paginate(message, embeds, options) {
const pageMsg = await message.channel.send({ embed: embeds[0] })
await pageMsg.react(reactions[0])
await pageMsg.react(reactions[1])
await pageMsg.react(reactions[2])
let pageIndex = 0;
let time = 30000;
const filter = (reaction, user) => {
return reactions.includes(reaction.emoji.name) && user.id === message.author.id;
};
if (options) {
if (options.time) time = options.time
}
const collector = pageMsg.createReactionCollector(filter, { time: time });
collector.on('collect', (reaction, user) => {
reaction.users.remove(user)
if (reaction.emoji.name === '▶️') {
if (pageIndex < embeds.length-1) {
pageIndex++
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = 0
pageMsg.edit({ embed: embeds[pageIndex] })
}
} else if (reaction.emoji.name === '⏸️') {
collector.stop()
} else if (reaction.emoji.name === '◀️') {
if (pageIndex > 0) {
pageIndex--
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = embeds.length-1
pageMsg.edit({ embed: embeds[pageIndex]})
}
}
});
collector.on('end', () => pageMsg.reactions.removeAll().catch(err => console.log(err)));
}``
}
In the question, I did not mention that I was also checking for the points channel through an if statement:
(const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id}))
But this does not work as well.
Here is the schema:
const { Schema, model } = require('mongoose')
// We are using this multiple times so define
// it in an object to clean up our code
const reqString = {
type: String,
required: true,
}
const SLSchema = Schema({
_id: reqString, // Guild ID
channelId: reqString,
})
module.exports = model('setLeaderboard', SLSchema)
In the first piece of code, I have pasted the entire script so you guys have an understanding of the thing I am trying to pull off here.