I've been getting this error while trying to code a discord bot in discord.js. The Bot is being used to check for the status of a discord server.
Error:
D:\MinecraftBot\commands\mcserver.js:13
.then((res) => res.join())
^
TypeError: res.join is not a function
at D:\MinecraftBot\commands\mcserver.js:13:28
Code In Question:
module.exports = {
name: "mcserver",
description: "Get info about a Minecraft Server",
usage: "mcserver <ip>",
run: async (client, message, args) => {
let ip = args[0];
fetch("https://api.mcsrvstat.us/2/"+args[0])
.then((res) => res.join()) // <-------- This Line Is Producing The Error
.then((body) => {
if(body.online === false) {
let oneembed = new discord.MessageEmbed()
.setColor('RANDOM')
.setAuthor("MC SERVER", message.guild.iconURL ({ dynamic: true }))
.addField("Status","<a:Offline:766303914654957610>")
.setTimestamp();
message.channel.send(oneembed)
}
else {
let embed = new discord.MessageEmbed()
.setColor('RANDOM')
.setThumbnail(`https://mc-api.net/v3/server/favicon/${args[0]}`)
.setAuthor("Mc Server", message.guild.iconURL({ dynamic: true }))
.addField("Status", "<a:Online:766303827850690600>")
.addField("IP", body.ip)
.addField("Hostname", body.hostname)
.addField("Players", `${body.players.online}/${body.players.max}`)
.addField("Software", body.software)
.addField("Version", body.version)
.addField("Motd", `${body.motd.clean[0]}\n${body.motd.clean[1]}`)
.setTimestamp()
.setImage(`http://status.mclive.eu/${args[0]}/${args[0]}/25565/banner.png`)
message.channel.send(embed)
}
})
}
}
The Data It's Requesting Is Here: https://api.mcsrvstat.us/2/hypixel.net
Related
I have downloaded a discord bot to read commands such as !gen dysney then they get the account. (educational purposes only ofc) then the user gets a messasage with the details but my discord bot wont recognise my commands. It is online but I put !gen disney and it doesnt do anything. I'd love to know where I've gone wrong. I'd love some support as I've been working on this all day but can't figure out the problem. I've given it administrator and everthing but nothing works. I've included an image of the permissions it has, incase something is wrong.
index.js:
// Dependencies
const Discord = require('discord.js');
const fs = require('fs');
const config = require('./config.json');
const CatLoggr = require('cat-loggr');
// Functions
const client = new Discord.Client();
const log = new CatLoggr();
// New discord collections
client.commands = new Discord.Collection();
// Logging
if (config.debug === true) client.on('debug', stream => log.debug(stream)); // if debug is enabled in config
client.on('warn', message => log.warn(message));
client.on('error', error => log.error(error));
// Load commands from folder
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); // Command directory
for (const file of commandFiles) {
const command = require(`./commands/${file}`); // Load the command
log.init(`Loaded command ${file.split('.')[0] === command.name ? file.split('.')[0] : `${file.split('.')[0]} as ${command.name}`}`); // Logging to console
client.commands.set(command.name, command); // Set command by name to the discord "commands" collection
};
// Client login
client.login(config.token);
client.once('ready', () => {
log.info(`I am logged in as ${client.user.tag} to Discord!`); // Say hello to console
client.user.setActivity(`${config.prefix} • ${client.user.username.toUpperCase()}`, { type: "LISTENING" }); // Set the bot's activity status
/* You can change the activity type to:
* LISTENING
* WATCHING
* COMPETING
* STREAMING (you need to add a twitch.tv url next to type like this: { type: "STREAMING", url: "https://twitch.tv/twitch_username_here"} )
* PLAYING (default)
*/
});
// Discord message event and command handling
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix)) return; // If the message does not start with the prefix
if (message.author.bot) return; // If a command executed by a bot
// Split message content to arguments
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
// If the command does not exists
if (config.command.notfound_message === true && !client.commands.has(command)) {
return message.channel.send(
new Discord.MessageEmbed()
.setColor(config.color.red)
.setTitle('Unknown command :(')
.setDescription(`Sorry, but I cannot find the \`${command}\` command!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// Executing the command
try {
client.commands.get(command).execute(message, args); // Execute
} catch (error) {
log.error(error); // Logging if error
// Send error messsage if the "error_message" field is "true" in the configuration
if (config.command.error_message === true) {
message.channel.send(
new Discord.MessageEmbed()
.setColor(config.color.red)
.setTitle('Error occurred!')
.setDescription(`An error occurred while executing the \`${command}\` command!`)
.addField('Error', `\`\`\`js\n${error}\n\`\`\``)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
};
});
config.json
{
"token": "TOKEN_placeholder",
"prefix": "!gen",
"genChannel": "1011720065739133008",
"genCooldown": "120000",
"color": {
"green": "0x57F287",
"yellow": "0xFEE75C",
"red": "0xED4245",
"default": "0x5865F2"
},
"command": {
"notfound_message": false,
"error_message": false
}
}
commands/gen.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const fs = require('fs');
const config = require('../config.json');
const CatLoggr = require('cat-loggr');
// Functions
const log = new CatLoggr();
const generated = new Set();
module.exports = {
name: 'gen', // Command name
description: 'Generate a specified service if stocked.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
* #param {Array[]} args Arguments splitted by spaces after the command name
*/
execute(message, args) {
// If the generator channel is not given in config or invalid
try {
message.client.channels.cache.get(config.genChannel).id; // Try to get the channel's id
} catch (error) {
if (error) log.error(error); // If an error occured log to console
// Send error messsage if the "error_message" field is "true" in the configuration
if (config.command.error_message === true) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Error occured!')
.setDescription('Not a valid gen channel specified!')
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
} else return;
};
// If the message channel id is the generator channel id in configuration
if (message.channel.id === config.genChannel) {
// If the user have cooldown on the command
if (message.author.id === "665621994649288770" ){
generated.delete(message.author.id);
};
if (message.author.id === "705881983909363742" ){
generated.delete(message.author.id);
};
if (generated.has(message.author.id)) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Cooldown!')
.setDescription(`Please wait ${generated} before executing that command again!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
} else {
// Parameters
const service = args[0];
// If the "service" parameter is missing
if (!service) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Missing parameters!')
.setDescription('You need to give a service name!')
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// File path to find the given service
const filePath = `${__dirname}/../stock/${args[0]}.txt`;
// Read the service file
fs.readFile(filePath, function (error, data) {
// If no error
if (!error) {
data = data.toString(); // Stringify the content
const position = data.toString().indexOf('\n'); // Get position
const firstLine = data.split('\n')[0]; // Get the first line
// If the service file is empty
if (position === -1) {
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`I do not find the \`${args[0]}\` service in my stock!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
// Send messages to the user
message.author.send(
new MessageEmbed()
.setColor(config.color.green)
.setTitle('Generated account')
.addField('Service', `\`\`\`${args[0][0].toUpperCase()}${args[0].slice(1).toLowerCase()}\`\`\``, true)
.addField('Account', `\`\`\`${firstLine}\`\`\``, true)
.setTimestamp()
)
.then(message.author.send('Here is your copy+paste:'))
.then(message.author.send(`\`${firstLine}\``));
// Send message to the channel if the user recieved the message
if (position !== -1) {
data = data.substr(position + 1); // Remove the gernerated account line
// Write changes
fs.writeFile(filePath, data, function (error) {
message.channel.send(
new MessageEmbed()
.setColor(config.color.green)
.setTitle('Account generated seccessfully!')
.setDescription(`Check your private ${message.author}! *If you do not recieved the message, please unlock your private!*`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
generated.add(message.author.id); // Add user to the cooldown set
// Set cooldown time
setTimeout(() => {
generated.delete(message.author.id); // Remove the user from the cooldown set after expire
}, config.genCooldown);
if (error) return log.error(error); // If an error occured, log to console
});
} else {
// If the service is empty
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`The \`${args[0]}\` service is empty!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
} else {
// If the service does not exists
return message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Generator error!')
.setDescription(`Service \`${args[0]}\` does not exist!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
});
};
} else {
// If the command executed in another channel
message.channel.send(
new MessageEmbed()
.setColor(config.color.red)
.setTitle('Wrong command usage!')
.setDescription(`You cannot use the \`gen\` command in this channel! Try it in <#${config.genChannel}>!`)
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
};
}
};
commands/help.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const config = require('../config.json');
module.exports = {
name: 'help', // Command name
description: 'Display the command list.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
*/
execute(message) {
const { commands } = message.client; // Get commands from the client
message.channel.send(
new MessageEmbed()
.setColor(config.color.default)
.setTitle('Command list')
.setDescription(commands.map(c => `**\`${config.prefix}${c.name}\`**: ${c.description ? c.description : '*No description provided*'}`).join('\n')) // Mapping the commands
.setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 }))
.setTimestamp()
);
}
};
commands/stock.js
// Dependencies
const { MessageEmbed, Message } = require('discord.js');
const fs = require('fs');
const config = require('../config.json');
module.exports = {
name: 'stock', // Command name
description: 'Display the service stock.', // Command description
/**
* Command exetute
* #param {Message} message The message sent by user
*/
execute(message) {
// Arrays
const stock = [];
// Read all of the services
fs.readdir(`${__dirname}/../stock/`, function (err, files) {
// If cannot scan the dictionary
if (err) return console.log('Unable to scan directory: ' + err);
// Put services into the stock
files.forEach(function (file) {
if (!file.endsWith('.txt')) return
stock.push(file)
});
const embed = new MessageEmbed()
.setColor(config.color.default)
//.setTitle(`${message.guild.name} has **${stock.length} services**`)
.setTitle(`**${stock.length} services**`)
.setDescription('')
// Push all services to the stock
stock.forEach(async function (data) {
const acc = fs.readFileSync(`${__dirname}/../stock/${data}`, 'utf-8')
const lines = [];
// Get number of lines
acc.split(/\r?\n/).forEach(function (line) {
lines.push(line); // Push to lines
});
// Update embed description message
embed.description += `**${data.replace('.txt','')}:** \`${lines.length}\`\n`
});
message.channel.send(embed);
});
}
};
I tried to add adminitrator. I tried to use differnt ways to run the bot. I added and removed the bot. I tried different prefixes
I'm working on a userbanner command that is in discord.js v13 and I get this error and I have no idea how I can fix it
Error: https://i.stack.imgur.com/xuFXB.png
CODE:
const { Discord, MessageEmbed } = require(`discord.js`);
const axios = require(`axios`)
module.exports = {
name: "UserBanner",
category: "🔰 Information",
permissions: ["SEND_MESSAGES"],
aliases: ["userbanner", "memberbanner"],
usage: "userbanner <#user>",
description: "Get the Banner of a user",
run: async (client, message, args) => {
let user = message.mentions.users.first() || client.users.cache.get(args[0]) || message.author;
try {
const data = await
axios.get(`https://discord.com/api/users/${user.id}`, {
headers: {
Authorization: `Bot: ${client.token}`
}
}).then(d => d.data);
if(data.banner){
let url = data.banner.startsWith("a_") ? ".gif?size=4096" : ".png?size=4-96";
url = `https://cdn.discordapp.com/baners*${user.id}/${data.banner}${url}`;
let avatar = user.displayAvatarURL({ dynamic: true})
let embed = new MessageEmbed()
.setColor(`#ffffff`)
.setTitle(`${user.tag} banner`)
.setImage(url)
.setThumbnail(avatar)
message.channel.send({ embeds: [embed]})
} else {
message.channel.send({ content: `<a:mark_rejected:975425274487398480> **Has no Banner!**`})
};
} catch(err){
console.log(err)
}
}
}
I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction
i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})
I am getting this error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined which is caused by client.user.username in embed's .setFooter().
module.exports = {
name: 'suggest',
aliases: ['sug', 'suggestion'],
description: 'Suggest something for the Bot',
execute(message, client, args) {
const Discord = require('discord.js');
const filter = m => m.author.id === message.author.id;
message.channel.send(`Please provide a suggestion for the Bot or cancel this command with "cancel"!`)
message.channel.awaitMessages(filter, { max: 1, })
.then(async (collected) => {
if (collected.first().content.toLowerCase() === 'cancel') {
message.reply("Your suggestion has been cancelled.")
}
else {
let embed = new Discord.MessageEmbed()
.setFooter(client.user.username, client.user.displayAvatarURL)
.setTimestamp()
.addField(`New Suggestion from:`, `**${message.author.tag}**`)
.addField(`New Suggestion:`, `${collected.first().content}`)
.setColor('0x0099ff');
client.channels.fetch("702825446248808519").send(embed)
message.channel.send(`Your suggestion has been filled to the staff team. Thank you!`)
}
})
},
catch(err) {
console.log(err)
}
};
According to your comment here
try { command.execute(message, args); } catch (error) { console.error(error); message.reply('There was an error trying to execute that command!'); } });
You are not passing client into execute(), you need to do that.
You also need to use await on channels.fetch() since it returns a promise so replace client.channels.fetch("702825446248808519").send(embed) with:
const channel = await client.channels.fetch("702825446248808519")
channel.send(embed)