Discord.js currency to command handler - javascript

I am trying to move all of my currency/shop commands/ Sequelize database into the command handler from index.js (works perfectly in index.js file) but I am running into issues transferring data from the index.js file into the individual command files. Any help on how to properly integrate the index.js commands into the command handler would be greatly appreciated. I realize this is a lot to go through but it would really mean a lot to me if anyone was able to help me out
index.js:
Reflect.defineProperty(currency, 'add', {
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
client.once('ready', async () => {
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async message => {
if (message.author.bot) return;
currency.add(message.author.id, 1);
if (!message.content.startsWith(prefix)) return;
const input = message.content.slice(prefix.length).trim();
if (!input.length) return;
const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);
if (command === 'balance') {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}πŸ’°`);
} else if (command === 'buy') {
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
} else if (command === 'shop') {
const items = await CurrencyShop.findAll();
return message.channel.send(items.map(i => `${i.name}: ${i.cost}πŸ’°`).join('\n'), { code: true });
} else if (command === 'leaderboard') {
return message.channel.send(
currency.sort((a, b) => b.balance - a.balance)
.filter(user => client.users.cache.has(user.user_id))
.first(10)
.map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}πŸ’°`)
.join('\n'),
{ code: true }
);
}
});
converting balance command to balance.js
balance.js:
const { currency, getBalance, id, tag } = require('../index.js');
module.exports = {
name: "balance",
description: "checks balance",
execute(message) {
const target = message.mentions.users.first() || message.author;
message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}πŸ’°`);
},
};
error:
TypeError: Cannot read property 'getBalance' of undefined
Command Handler
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
the bot sends an error from the command handler as seen above
EDIT: Cherryblossom's post seems to work. i have 1 more issue with immigrating the buy command though I dont know how to make the async work as async doesnt work in command handler. here is what i tried
const { currency, CurrencyShop} = require('../index.js');
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);```

What's happening is that in balance.js, currency is undefined. You need to export currency from index.js:
module.exports = { currency }
Also, in balance.js, you don't need to (and actually can't) import/require properties of other objects (getBalance, tag, id). Sorry if that doesn't make sense but basically you only need to require currency:
const { currency } = require('../index.js')
Edit
await can only be used in an async function. Edit the execute function so it is like this:
async execute(message) {
// your code here
}
When calling execute, use await. You'll need to make the message handler async as well:
client.on('message', async message => {
// code...
try {
await command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}

Related

JoinCommand discord.js issue, Cannot read property 'voice' of undefined

I'm still trying to place an order for the voice bot to enter. I want to make a music system using youtube-dl and I always get this error saying that it doesn't know what "Voice" means in the line "message.member.voiceChannel"
I'm already getting nervous about this problem, I tried to add permissions, but it doesn't work, I want to specify that it uses Discord.js#v12
below you have all the files that I use for the command, such as message event and command class.
Error Code:
2022-06-02 05:39:42 [info] [Command] "n!join" (join) ran by "GhostStru#1982" (780808189226123294) on guild "GhostStru🌿's server" (939865905708552242) channel "#cmmds" (980923745768181831)
TypeError: Cannot read properties of undefined (reading 'voice')
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\commands\music\join.js:23:36)
at module.exports.runCommand (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:417:23)
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:391:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is my Join command
const { joinVoiceChannel } = require('#discordjs/voice');
const { MessageEmbed, Util } = require('discord.js');
const discord = require("discord.js")
const Command = require('../../structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: 'join',
aliases: ['add'],
usage: "",
category: "Music",
examples: ["join"],
description: "Join into you'r voice channel.",
cooldown: 5,
})
}
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!message.member.voiceChannel) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You must be a voice channel before using this command.`)]});
if (message.guild.me.voiceChannel && message.member.voiceChannel.id !== message.guild.me.voiceChannel.id) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You are not in same voice channel.`)]});
try {
joinVoiceChannel({
channelId: message.member.voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
await message.react('πŸ‘').catch(() => { });
} catch {
return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`An error occurred while joining the voice channel.`)]});
}
}
}
This is my message event
const Event = require('../../structures/Event');
const { Permissions, Collection } = require("discord.js");
const afk = require("../../models/afk");
const Statcord = require("statcord.js");
const moment = require('moment');
const discord = require("discord.js");
const config = require('./../../config.json');
const { MessageEmbed } = require('discord.js');
const logger = require('../../utils/logger');
const nsfwplease = require('../../assets/json/nfsw.json');
const mongoose = require('mongoose');
const Guild = require('../../database/schemas/Guild');
const User = require('../../database/schemas/User');
const Moderation = require('../../database/schemas/logging');
const Blacklist = require('../../database/schemas/blacklist');
const customCommand = require('../../database/schemas/customCommand');
const autoResponse = require('../../database/schemas/autoResponse');
const autoResponseCooldown = new Set();
const inviteFilter = require('../../filters/inviteFilter');
const linkFilter = require('../../filters/linkFilter');
const maintenanceCooldown = new Set();
const metrics = require('datadog-metrics');
const permissions = require('../../assets/json/permissions.json')
const Maintenance = require('../../database/schemas/maintenance')
require("moment-duration-format");
module.exports = class extends Event {
constructor(...args) {
super(...args);
this.impliedPermissions = new Permissions([
"VIEW_CHANNEL",
"SEND_MESSAGES",
"SEND_TTS_MESSAGES",
"EMBED_LINKS",
"ATTACH_FILES",
"READ_MESSAGE_HISTORY",
"MENTION_EVERYONE",
"USE_EXTERNAL_EMOJIS",
"ADD_REACTIONS"
]);
this.ratelimits = new Collection();
}
async run(message) {
try {
if (!message.guild) return;
if(config.datadogApiKey){
metrics.init({ apiKey: this.client.config.datadogApiKey, host: 'nucleus', prefix: 'nucleus.' });
}
const mentionRegex = RegExp(`^<#!?${this.client.user.id}>$`);
const mentionRegexPrefix = RegExp(`^<#!?${this.client.user.id}>`);
if (!message.guild || message.author.bot) return;
const settings = await Guild.findOne({
guildId: message.guild.id,
}, async (err, guild) => {
if (err) console.log(err)
if (!guild) {
const newGuild = await Guild.create({
guildId: message.guild.id,
prefix: config.prefix || 'p!',
language: "english"
});
}
});
//if (!settings) return message.channel.send('Oops, this server was not found in the database. Please try to run the command again now!');
if (message.content.match(mentionRegex)) {
const proofita = `\`\`\`css\n[ Prefix: ${settings.prefix || '!'} ]\`\`\``;
const proofitaa = `\`\`\`css\n[ Help: ${settings.prefix || '!'}help ]\`\`\``;
const embed = new MessageEmbed()
.setTitle('Hello, I\'m Nucleus. What\'s Up?')
.addField(`Prefix`,proofita, true)
.addField(`Usage`,proofitaa, true)
.setDescription(`\nIf you like Nucleus, Consider [voting](https://top.gg/bot/980373513691090974), or [inviting](https://discord.com/oauth2/authorize?client_id=980373513691090974&scope=bot&permissions=470150262) it to your server! Thank you for using Nucleus, we hope you enjoy it, as we always look forward to improve the bot`)
.setFooter('Thank you for using Nucleus!!')
.setColor('#FF2C98')
message.channel.send(embed);
}
if(config.datadogApiKey){
// Add increment after every darn message lmfao!
metrics.increment('messages_seen');
}
// Filters
if (settings && await inviteFilter(message)) return;
if (settings && await linkFilter(message)) return;
let mainPrefix = settings ? settings.prefix : '!';
const prefix = message.content.match(mentionRegexPrefix) ?
message.content.match(mentionRegexPrefix)[0] : mainPrefix
const guildDB = await Guild.findOne({
guildId: message.guild.id
});
const moderation = await Moderation.findOne({
guildId: message.guild.id
});
if(!moderation){
Moderation.create({
guildId: message.guild.id
})
}
// maintenance mode
const maintenance = await Maintenance.findOne({
maintenance: "maintenance"
})
const userBlacklistSettings = await Blacklist.findOne({ discordId: message.author.id,});
const guildBlacklistSettings = await Blacklist.findOne({ guildId: message.guild.id });
//autoResponse
const autoResponseSettings = await autoResponse.findOne({ guildId: message.guild.id, name: message.content.toLowerCase() });
if (autoResponseSettings && autoResponseSettings.name) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
if(maintenance && maintenance.toggle == "true") return;
if(autoResponseCooldown.has(message.author.id)) return message.channel.send(`${message.client.emoji.fail} Slow Down - ${message.author}`)
message.channel.send(autoResponseSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`))
autoResponseCooldown.add(message.author.id)
setTimeout(()=>{
autoResponseCooldown.delete(message.author.id)
}, 2000)
return;
}
//afk
let language = require(`../../data/language/english.json`)
if(guildDB) language = require(`../../data/language/${guildDB.language}.json`)
moment.suppressDeprecationWarnings = true;
if(message.mentions.members.first()){
if(maintenance && maintenance.toggle == "true") return;
const afklist = await afk.findOne({ userID: message.mentions.members.first().id, serverID: message.guild.id});
if(afklist){
await message.guild.members.fetch(afklist.userID).then(member => {
let user_tag = member.user.tag;
return message.channel.send(`**${afklist.oldNickname || user_tag || member.user.username}** ${language.afk6} ${afklist.reason} **- ${moment(afklist.time).fromNow()}**`).catch(() => {});
});
}
}
const afklis = await afk.findOne({ userID: message.author.id, serverID: message.guild.id});
if(afklis) {
if(maintenance && maintenance.toggle == "true") return;
let nickname = `${afklis.oldNickname}`;
message.member.setNickname(nickname).catch(() => {});
await afk.deleteOne({ userID: message.author.id });
return message.channel.send(new discord.MessageEmbed().setColor('GREEN').setDescription(`${language.afk7} ${afklis.reason}`)).then(m => {
setTimeout(() => {
m.delete().catch(() => {});
}, 10000);
});
};
if (!message.content.startsWith(prefix)) return;
// eslint-disable-next-line no-unused-vars
const [cmd, ...args] = message.content.slice(prefix.length).trim().split(/ +/g);
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
// maintenance mode
if(!this.client.config.developers.includes(message.author.id)){
if(maintenance && maintenance.toggle == "true") {
if(maintenanceCooldown.has(message.author.id)) return;
message.channel.send(`Nucleus is currently undergoing maintenance which won't allow anyone to access Nucleus Commands. Feel free to try again later. For updates: https://discord.gg/FqdH4sfKBg`)
maintenanceCooldown.add(message.author.id);
setTimeout(() => {
maintenanceCooldown.delete(message.author.id)
}, 10000);
return;
}
}
// Custom Commands
const customCommandSettings = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
const customCommandEmbed = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
if (customCommandSettings && customCommandSettings.name && customCommandSettings.description) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
let embed = new MessageEmbed()
.setTitle(customCommandEmbed.title)
.setDescription(customCommandEmbed.description)
.setFooter(``)
if( customCommandEmbed.image !== "none") embed.setImage(customCommandEmbed.image)
if( customCommandEmbed.thumbnail !== "none") embed.setThumbnail(customCommandEmbed.thumbnail)
if( customCommandEmbed.footer !== "none") embed.setFooter(customCommandEmbed.footer)
if( customCommandEmbed.timestamp !== "no") embed.setTimestamp()
if( customCommandEmbed.color == 'default') {
embed.setColor(message.guild.me.displayHexColor)
} else embed.setColor(`${customCommandEmbed.color}`)
return message.channel.send(embed)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "false") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
return message.channel.send(customCommandSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`)
)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "true") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
const command = JSON.parse(customCommandSettings.content)
return message.channel.send(command).catch((e)=>{message.channel.send(`There was a problem sending your embed, which is probably a JSON error.\nRead more here --> https://nucleus.xyz/embeds\n\n__Error:__\n\`${e}\``)})
}
if (command) {
await User.findOne({
discordId: message.author.id
}, (err, user) => {
if (err) console.log(err)
if (!user) {
const newUser = new User({
discordId: message.author.id
})
newUser.save()
}
});
const disabledCommands = guildDB.disabledCommands;
if (typeof(disabledCommands) === 'string') disabledCommands = disabledCommands.split(' ');
const rateLimit = this.ratelimit(message, cmd);
if (!message.channel.permissionsFor(message.guild.me).has('SEND_MESSAGES')) return;
// Check if user is Blacklisted
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the user is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} You are blacklisted from the bot :(`);
}
// Check if server is Blacklisted
if (guildBlacklistSettings && guildBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the guild is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} This guild is Blacklisted :(`);
}
let number = Math.floor((Math.random() * 10) + 1);
if (typeof rateLimit === "string") return message.channel.send(` ${message.client.emoji.fail} Please wait **${rateLimit}** before running the **${cmd}** command again - ${message.author}\n\n${number === 1 ? "*Did You know that Nucleus has its own dashboard? `https://nucleus.xyz/dashboard`*" : ""}${number === 2 ? "*You can check our top.gg page at `https://vote.nucleus.xyz`*" : ""}`).then((s)=>{
message.delete().catch(()=>{});
s.delete({timeout: 4000}).catch(()=>{})
}).catch(()=>{})
if (command.botPermission) {
const missingPermissions =
message.channel.permissionsFor(message.guild.me).missing(command.botPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${this.client.user.tag}`, message.client.user.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing Bot Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join(' - ')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if (command.userPermission) {
const missingPermissions =
message.channel.permissionsFor(message.author).missing(command.userPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${message.author.tag}`, message.author.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing User Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join('\n')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if(disabledCommands.includes(command.name || command)) return;
if (command.ownerOnly) {
if (!this.client.config.developers.includes(message.author.id)) return
}
if(config.datadogApiKey){
metrics.increment('commands_served');
}
if (command.disabled) return message.channel.send(`The owner has disabled the following command for now. Try again Later!\n\nFor Updates: https://discord.gg/duBwdCvCwW`)
if (command.nsfwOnly && !message.channel.nsfw && message.guild) return message.channel.send(`${nsfwplease[Math.round(Math.random() * (nsfwplease.length - 1))]}`)
Statcord.ShardingClient.postCommand(cmd, message.author.id, this.client);
await this.runCommand(message, cmd, args)
.catch(error => {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("commandError", error, message, cmd);
})
}
} catch(error) {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("fatalError", error, message);
}
}
async runCommand(message, cmd, args) {
if (!message.channel.permissionsFor(message.guild.me) || !message.channel.permissionsFor(message.guild.me).has('EMBED_LINKS'))
return message.channel.send(`${message.client.emoji.fail} Missing bot Permissions - **Embeds Links**`)
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
logger.info(`"${message.content}" (${command.name}) ran by "${message.author.tag}" (${message.author.id}) on guild "${message.guild.name}" (${message.guild.id}) channel "#${message.channel.name}" (${message.channel.id})`, { label: 'Command' })
await command.run(message, args)
}
ratelimit(message, cmd) {
try {
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
if (message.author.permLevel > 4) return false;
const cooldown = command.cooldown * 1000
const ratelimits = this.ratelimits.get(message.author.id) || {}; // get the ENMAP first.
if (!ratelimits[command.name]) ratelimits[command.name] = Date.now() - cooldown; // see if the command has been run before if not, add the ratelimit
const difference = Date.now() - ratelimits[command.name]; // easier to see the difference
if (difference < cooldown) { // check the if the duration the command was run, is more than the cooldown
return moment.duration(cooldown - difference).format("D [days], H [hours], m [minutes], s [seconds]", 1); // returns a string to send to a channel
} else {
ratelimits[command.name] = Date.now(); // set the key to now, to mark the start of the cooldown
this.ratelimits.set(message.author.id, ratelimits); // set it
return true;
}
} catch(e) {
this.client.emit("fatalError", error, message);
}
}
}
And this is my Command class
module.exports = class Command {
constructor(client, name, options = {}) {
this.client = client;
this.name = options.name || name;
this.aliases = options.aliases || [];
this.description = options.description || "No description provided.";
this.category = options.category || "General";
this.usage = `${this.name} ${options.usage || ''}` || "No usage provided.";
this.examples = options.examples || [];
this.disabled = options.disabled || false;
this.cooldown = "cooldown" in options ? options.cooldown : 5 || 5;
this.ownerOnly = options.ownerOnly || false;
this.guildOnly = options.guildOnly || false;
this.nsfwOnly = options.nsfwOnly || false;
this.botPermission = options.botPermission || ['SEND_MESSAGES', 'EMBED_LINKS'];
this.userPermission = options.userPermission || null;
}
// eslint-disable-next-line no-unused-vars
async run(message, args) {
throw new Error(`The run method has not been implemented in ${this.name}`);
}
reload() {
return this.store.load(this.file.path);
}
}
In this "code cases" i put my personal codes, and i dont know where can i find the problem, or what can i modifiy in my code, thats all i can say..
Can someone tell me what can i do?...
Its a simple join command, and he cannot read voice.channel...

messageReactionAdd isn't firing despite proper setup Discord.js

Entire file below. I've been trying for an ungodly amount of time to get a reaction roles command working. Currently using MongoDB and everything is setup properly no errors my schema has worked properly as well there are no issues. Despite everything working I cannot get my event to fire at all with multiple revisions. Any help would be phenomenal on this one as I am too new to all of this to figure it out for myself...
const Schema = require('../reactions');
const Discord = require('discord.js');
const { client, intents } = require('..')
module.exports = {
name: 'messageReactionAdd',
run: async (reaction, message, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
const { guild } = reaction.message;
if (!guild) return;
if (!guild.me.permissions.has("MANAGE_ROLES")) return;
isEmoji = function(emoji) {
const e = Discord.Util.parseEmoji(emoji);
if (e.id === null) {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: false
}
} else {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: true
}
}
}
const member = guild.members.cache.get(user.id);
await Schema.findOne({
guild_id: guild.id,
msg_id: reaction.message.id
}, async (err, db) => {
if (!db) return;
if (reaction.message.id != db.msg_id) return;
const data = db.rcs;
for (let i in data) {
if (reaction.emoji.id === null) {
if (reaction.emoji.name === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
} else {
if (reaction.emoji.id === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
}
}
});
},
};```
Intents
You need the GUILD_MESSAGE_REACTIONS in your client

SlashCommands not showing up

I just finished my bot and wanted to invite it to another server to test it out.
However, when I typed / no commands showed up.
When I invited the bot I enabled application.commands so I can use the slashcommands but it still did not work. My bot also has a global slashcommand handler so it should normally work right?
I don't know if the handler code is needed but I'll still add it here in case you do need it:
const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js');
/**
* #param {Client} client
*/
module.exports = async (client, PG, Ascii) => {
const Table = new Ascii("Command Loaded");
CommandsArray = [];
(await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
const command = require(file);
if(!command.name)
return Table.addRow(file.split("/")[7], "β›” FAILED", "Missing a name.")
if(command.type !== "USER" && !command.description)
return Table.addRow(command.name, "β›” FAILED", "Missing a description.")
if(command.permission){
if(Perms.includes(command.permission))
command.defaultPermission = false;
else
return Table.addRow(command.name, "β›” FAILED", "Permission is invalid.")
}
client.commands.set(command.name, command);
CommandsArray.push(command);
await Table.addRow(command.name, "βœ… SUCCESSFUL");
});
console.log(Table.toString());
// PERMISSIONS CHECK //
client.on("ready", async () =>{
client.guilds.cache.forEach((g) => {
g.commands.set(CommandsArray).then(async (command) =>{
const Roles = (commandName) => {
const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission;
if(!cmdPerms) return null;
return g.roles.cache.filter((r) => r.permissions.has(cmdPerms) && !r.managed).first(10);
}
const fullPermissions = command.reduce((accumulator, r) =>{
const roles = Roles(r.name);
if(!roles) return accumulator;
const permissions = roles.reduce((a, r) =>{
return [...a, {id: r.id, type: "ROLE", permission:true}]
}, []);
return [...accumulator, {id: r.id, permissions}]
}, []);
await g.commands.permissions.set({ fullPermissions });
});
})
});
}
You have to register the command first, which is essentially creating the command within Discord. Follow the guide to get it set up. And to clarify, you only register the command once, if that isn't obvious.
You can use Postman to create/edit the commands if you are comfortable with it.

UnhandledPromiseRejectionWarning: TypeError: channel.createWebhook is not a function

This is my setuplogger.js file, and the bottom part is the code I have in my index.js. This code is supposed to create a webhook for the channel set as the logschannel, this webhook will send logs for every ban that happens in the guild. But the problem is that I keep getting the .createWebhook is not a function, I couldn't figure out how to fix this error so I just came here.
if (!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send(`***Error:*** *You do not have* ***[ADMINISTRATOR]*** *permission.*`);
}
const logEnableDisable = args[0];
const logChannel = message.mentions.channels.first();
if (!logEnableDisable) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (!logChannel) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (logEnableDisable === 'enable') {
db.set(`${message.guild.id}_logChannel`, logChannel.id)
message.channel.send(`*Succesfully enabled logs to* ***${logChannel}.***`)
}
if (logEnableDisable === 'disable') {
const findLogchannel = db.get(`${message.guild.id}_logChannel`);
if (!findLogchannel) {
message.channel.send(`***Error:*** *Log channel has not been setup yet, use \`${prefix}setuplogger enable <channel>\`.*`)
} else {
db.delete(`${message.guild.id}_logChannel`, true)
message.channel.send(`*Succesfully removed logs from* ***${logChannel}.***`)
}
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
client.on("guildBanAdd", async (guild, user) => {
const channel = db.get(`${guild.id}_logChannel`);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_BAN_ADD",
});
const banLog = fetchedLogs.entries.first();
if(!banLog) return console.log("It doesn't work.")
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`)
.setTimestamp()
.setColor(color);
channel.createWebhook('Logger', { avatar: 'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png' }).then(webhook => { webhook.send(embed) });
}
});
It seems you're saving the channel's ID in the database (logChannel.id) and later, you're trying to call the createWebhook method on a string, not the channel. If you call a non-existing method on a string you'll receive an error; "channel.createWebhook is not a function":
const channel = '86924931458913231434'
const webhook = channel.createWebhook('Logger')
To solve this, you need to fetch the channel first so you can use the createWebhook method:
client.on('guildBanAdd', async (guild, user) => {
const channelID = db.get(`${guild.id}_logChannel`);
if (!channelID) return console.log('No channel ID');
try {
const channel = await client.channels.fetch(channelID);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log("It doesn't work.");
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(
`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`,
)
.setTimestamp()
.setColor(color);
const webhook = await channel.createWebhook('Logger', {
avatar:
'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png',
});
webhook.send(embed);
}
} catch (error) {
console.log(error);
}
});

Chunks of code being ignored. No errors, no logs. Might be API related

The code below doesn't give any errors but I have a weird bug anyway. I have four streams to aggregate twitter feeds to a discord channel. 3 of those often work. but whenever I run the code there is always a feed not coming through, no line is getting executed in that stream. This often happens with the IntelFeed and/or covid-19feed. When I wait for some time or repeatedly rerun the code it starts working. I think it may be due to the structure of the code (not having enough time to fulfill the conditions) or due to the API. But I can't confirm the latter one.
const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const { Client, RichEmbed } = require('discord.js');
const twitterFeedsModel = require('./models/twitterFeedsModel');
const client = new Discord.Client();
const mongoose = require('mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true });
mongoose.connect('mongodb://localhost/twitterFeedDatabeses');
const Twit = require('twit');
const T = new Twit({
consumer_key: botconfig.consumer_key,
consumer_secret: botconfig.consumer_key_secret,
access_token: botconfig.access_token,
access_token_secret: botconfig.access_token_secret,
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
//Newsfeed
const stream = T.stream("statuses/filter", { follow: ["5402612", "1652541", "831470472", "26792275", "380648579", "426802833", "144274618", "31696962", "1642135962", "16561457"]});
const scr_name = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
stream.on("tweet", function (tweet) {
if(!scr_name.includes(tweet.user.screen_name)) return;
client.channels.get("646745474514026506").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
});
//Covid-19stream
const secondStream = T.stream("statuses/filter", {follow: "2985479932"});
const secondScr_name = "BNODesk"
secondStream.on("tweet", function (tweet){
console.log(tweet.user.screen_name)
if(secondScr_name.includes(tweet.user.screen_name)) {
const tweetContent = tweet.text.split(" ");
console.log(tweetContent)
const filteredWords = ['thank', 'Thank', 'you', 'you.', 'you!']
console.log("It does include Breakin: " + tweetContent.includes("BREAKING:"))
if(!filteredWords.some(word => tweet.text.includes(word))){
if(tweetContent.includes("BREAKING:")){
console.log("It does include breaking (after if-statement): " + tweetContent.includes("BREAKING:"))
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get('645733080061181965').send('I found out this tweet covers important news')
} else if(!tweet.text.startsWith("#")){
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get("645733080061181965").send(`Hello <#283206528004259850>, there is a new tweet!`)
}
}
}
});
//GRUNNstream
const thirdStream = T.stream("statuses/filter", { follow: ["14907733", "22465767", "18549902", "451432440", "97639259", "2343981858"]});
const thirdScr_name = ['rtvnoord', 'oogtv', 'dvhn_nl', 'P2000Groningen', 'polgroningen', 'Sikkom050']
thirdStream.on("tweet", function (tweet) {
if(thirdScr_name.includes(tweet.user.screen_name)) {
client.channels.get("632705489108729867").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
// intelstream
const fourthStream = T.stream("statuses/filter", {follow: ['3331851939', '2407993940', '1140336427550552000', '2790057867', '2315512764', '1517300821', '70529694', '62248461', '146958450', '85904241', '762565517026664400']});
const fourthScr_name = ['IntelCrab', 'IntelDoge', 'IntelAgencyNGO', 'lummideast', 'bellingcat', 'obretix', 'JanesINTEL', 'BarzanSadiq', 'ragipsoyly', 'leventkemal', 'OmerOzkizilcik']
fourthStream.on("tweet", function (tweet) {
if(fourthScr_name.includes(tweet.user.screen_name)) {
client.channels.get("646745512011235339").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
});
module.exports.run = client.on('message', message => {
if (!message.content.startsWith(botconfig.prefix) || message.author.bot) return;
const args = message.content.slice(botconfig.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command.length === 0) {
return message.channel.send(`I ain't gonna fill the command in by myself fam`);
}
if (command === 'add_twitter_feed'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_feed = args;
T.get('users/show', { screen_name: twitterUsername_feed.join() }, function (err, data, response) {
console.log(data.id)
const twitterFeedVar = new twitterFeedsModel({
_id: mongoose.Types.ObjectId(),
twitterUsernameAddedToFeed: twitterUsername_feed.join(),
twitterUsername_idAddedToFeed: data.id,
})
twitterFeedVar.save()
.then(result => console.log(result))
.catch(err => console.log(err))
twitterFeedVar.find()
.then(doc => {
message.channel.send(doc)
})
})
}
/*if (command === `savelist`) {
Test.find()
.then(doc => {
message.channel.send(doc)
})
}
*/
if (command === 'twitter_user_id'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_lookup = args;
console.log(`${message.member.user.tag} requested the ID of the following user: ` + twitterUsername_lookup.join())
T.get('users/show', { screen_name: twitterUsername_lookup.join() }, function (err, data, response) {
console.log(data)
message.channel.send(`This is the ID of ` + twitterUsername_lookup.join() + `: ` + data.id)
if (!data.id) {
return message.channel.send(`Twitter user not found.`)
}
})
message.delete()
}
if (command === `hello`){
return message.channel.send("Hi there :)")
}
if (command === `feedlist`){
var scr_name2 = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
return message.channel.send(scr_name2)
}
if (command === `reload`) {
message.channel.send(`Reloading...`)
console.clear();
client.destroy()
client.login(botconfig.token);
message.channel.send(`Bot reloaded succesfully!`);
return;
}
});
module.exports.help = {
name: "testtest"
}
client.login(botconfig.token);

Categories

Resources