So in my config.json file I had put my prefix as "!". I was testing the bot in my friends server and the prefix was clashing with other bots. I changed it to ";". But now both the prefixs are functioning "!" and";". I saved all my files and restarted node too, but the commands are still responding to "!". Am I missing something?
The structure of my file system is -
1. index.js
2. config.json
3. commands folder (command files)
index.js
const Discord = require('discord.js');
const fs = require('fs');
const { prefix, token } = require('./config.json');
const profanity = require('profanities')
//console.log(profanity);
const client = new Discord.Client();
const cooldowns = new Discord.Collection();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); //returns an array of all file anmes in a dir ['ping.js', beep.js, ....]; the filter is used to get only .js files.
const commandFiles_mod = fs.readdirSync('./commands/mod').filter(file => file.endsWith('.js')); //mod folder
const commandFiles_info = fs.readdirSync('./commands/info').filter(file => file.endsWith('.js')); //info folder
const commandFiles_extras = fs.readdirSync('./commands/extras').filter(file => file.endsWith('.js')); //
//file system
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// set a new item in the Collection
// with the key as the command name and the value as the exported module
client.commands.set(command.name, command); //set takes the file name and the path to the file. //command is the path to file and command.name is the name of the file
}
for (const file of commandFiles_info) {
const command1 = require(`./commands/info/${file}`);
client.commands.set(command1.name, command1);
}
for (const file of commandFiles_mod) {
const command2 = require(`./commands/mod/${file}`);
client.commands.set(command2.name, command2);
}
for (const file of commandFiles_extras) {
const command3 = require(`./commands/extras/${file}`);
client.commands.set(command3.name, command3);
}
client.once('ready', () => {
client.user.setActivity(`${prefix}help`)
console.log(`Hello! ${client.user.username}-bot is now online!`)
});
client.on('message', message => {
//command handling
if (message.content === 'galaxy-prefix') {
const prefix_embed = new Discord.MessageEmbed()
.setTitle('Prefix')
.setDescription(`Use this ahead of comamnds for usage: **${prefix}**`)
.setColor('RANDOM')
.setTimestamp()
message.channel.send(prefix_embed);
}
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm') { //edit here
const args = message.content.slice(prefix.length).split(/ +/); //caveats
//console.log(args);
const messageArray = message.content.split(/ +/);
//console.log(messageArray);
const cmd = args[1];
//console.log(cmd);
const commandName = args.shift().toLowerCase();
//console.log(commandName);
/*if (!message.content.startsWith(prefix) && !message.author.bot) {
const messageArray = message.content.split(" ");
console.log(messageArray);
}*/
/*for (i=0; i < profanity.length; i++) {
if (messageArray.includes(profanity[i])) {
message.delete();
break;
}
}*/
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); //aliases
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!'); //cannot dm this command
}
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}\``; //usage check, in file as usage: '<...>'
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) { //cooldown
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
//console.log(now);
const timestamps = cooldowns.get(command.name); // gets the collection for the triggered command
const cooldownAmount = (command.cooldown || 3) * 1000; //3 is default cooldown time, if cooldown isnt set in command files.
if (timestamps.has(message.author.id)) {
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(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}
});
client.on('shardError', error => {
console.error('A websocket connection encountered an error:', error);
});
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
});
client.login(token);
config.json
{
"token": " ................. ",
"prefix": ";"
}
Your bot will respond to anything actually...
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm')
This means your bot will run if the message starts with the prefix OR the sender is not a bot OR the channel type is DM. You should try using ? - .... They will probs work too.
To use an and you use && instead of ||
Related
I can actually run the bot, it will let mi interact with the other 3 commands, but when trying to do the "kickembed" it will fail and give me the error "client.commands.get('kickembed').execute(message,args,Discord)"
^
Cannot read property of 'execute' of undefined
tbh, i tried everithing, my little brain cant work this out, tysm for your time!
const client = new Discord.Client();
const prefix = ('^');
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () =>{
console.log('Cataclysm is online, beep bop')
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
message.channel.send('pong!');
} else if (command === 'welcome'){
client.commands.get('welcome').execute(message, args);
} else if (command === 'ban'){
client.commands.get('Ban').execute(message, args);
} else if (command === 'kick'){
client.commands.get('kick').execute(message, args);
} else if (command === 'kickembed'){
client.commands.get('kickembed').execute(message, args, Discord);
}
}); ~~~
and this is "kickembed"(where i have the problem i think)
~~~ const name = 'kick';
const description = "This command kicks a member!";
function execute(message, args, Discord) {
const banembed = new Discord.MessageEmbed()
.setColor('#ff3838')
.setTitle('A user has been kicked')
.setDescription('player (fix this plis) has been kicked by etc');
message.channel.send(banembed);~~~
your kickembed files have wrong name it is kick
So it should be like:
const name = 'kickembed';
const description = "This command kicks a member!";
function execute(message, args, Discord) {
const banembed = new Discord.MessageEmbed()
.setColor('#ff3838')
.setTitle('A user has been kicked')
.setDescription('player (fix this plis) has been kicked by etc');
message.channel.send(banembed);
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');
const fs = require('fs');
module.exports = {
name: 'prefix',
aliases: ['setprefix'],
description: 'Установить новый префикс на вашем сервере',
execute(message, args) {
if (!message.member.hasPermission('MANAGE_SERVER'))
return message.reply(' Не не не.');
if (!args[0] || args[0 == 'help'])
return message.reply(`Использование: prefix <Тут ваш префикс> `);
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
prefixes[message.guild.id] = {
prefix: args[0]
};
fs.writeFile('./prefixes.json', JSON.stringify(prefixes), (err) => {
if (err) console.log(err)
})
let pEmbed = new MessageEmbed()
.setColor('#000001')
.setTitle('Префикс изменён!')
.setDescription(`Новый префикс на сервере **${args[0]}**`)
message.channel.send(pEmbed)
message.delete({ timeout: 10000 })
}}
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
if (!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefix: config.prefix
};
}
let prefix = prefixes[message.guild.id].prefix;
if i'm change prefix, bot stopping music.
Tried to do it via ' ReadFile`, it returns me a callback error
I know I could use readFileSync, but if I do, I know I'll never understand async/await and I'll just bury the issue.
UPD:
client.on('message', async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
if (!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefix: config.prefix
};
}
let prefix = prefixes[message.guild.id].prefix;
// let msgArray = message.content.split(" ");
// let cmd = msgArray[0];
// if(cmd.slice(0, prefix.length) !== prefix) return;
// let args = msgArray.slice(1);
// let cmdFile = client.commands.get(cmd.slice(prefix.length))
// if(cmdFile) cmdFile.run(client, message, args);
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (message.content.startsWith(prefix) && commandFiles) {
if (message.deletable) {
try {
await message.delete();
} catch(e) {
console.error(e);
}
}
}
if (!command) return;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.set(command.name);
const cooldownAmount = (command.cooldown || 1) * 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(
`Пожалуйста подождите ${timeLeft.toFixed(1)} секунд перед повторным использованием \`${command.name}\` команд.`
);
}
}
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('Произошла ошибка при выполнении этой команды.')
.then(message => message.delete({ timeout: 5000 }))
.catch(console.error);
}
});
fs doesn't offer the possibility to give the Promise of a file, but it can read a file asynchronously with a callback instead of a promise. But in the fs module, you can use fs/promises (aka fs.promises). Here's the same code. I corrected 1 problem, added the fsp var (fs promises), and used it to read your prefixes.json file. fs.readFileSync is totally fine though.
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const fs = require("fs");
const fsp = fs.promises; // ++
module.exports = {
name: "prefix",
aliases: ["setprefix"],
description: "Установить новый префикс на вашем сервере",
async execute(message, args) {
if (!message.member.hasPermission("MANAGE_SERVER"))
return message.reply(" Не не не.");
if (!args[0] || args[0] == "help") /** Correction */
return message.reply(`Использование: prefix <Тут ваш префикс> `);
let prefixes = JSON.parse(await fsp.readFile("prefixes.json", "utf8")); // Using fsp
prefixes[message.guild.id] = {
prefix: args[0],
};
fs.writeFile("./prefixes.json", JSON.stringify(prefixes), (err) =>
err ? console.error(err) : null
);
let pEmbed = new MessageEmbed()
.setColor("#000001")
.setTitle("Префикс изменён!")
.setDescription(`Новый префикс на сервере **${args[0]}**`);
message.channel.send(pEmbed);
message.delete({ timeout: 10000 });
},
};
This code is for playing music, and I want to have a stop command on my bot. Could you help me?
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json")
const ytdl = require("ytdl-core")
const streamOptions = {seek:0, volume:1}
client.on("message", async message => {
if(message.author.bot) return
if(message.channel.type === "dm") return
if(!message.content.startsWith(config.prefix)) return
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const comando = args.shift().toLocaleLowerCase()
if(comando === "play") {
var voiceChannel = message.guild.channels.cache.get("733122593019789314")
let file = args[0]
if(voiceChannel == null) {
console.log("Canal não encontrado.")
}
if(voiceChannel != null) {
console.log("Canal encontrado.")
await voiceChannel.join().then(connection => {
const stream = ytdl(file, {filter:"audioonly", quality:"highestaudio"})
const DJ = connection.play(stream, streamOptions)
DJ.on("end", end => {
voiceChannel.leave()
})
}).catch(console.error)
}
}/* I was trying to do the command this way:
else if(comando === "stop") {
voiceChannel.leave()
}*/
}
client.login(config.token);
Everything works, I just want to stop the music.
(I'm Brazilian, some words or sentences may be wrong.)
Thank you for your help! 😁
You can use StreamDispatcher.pause() and StreamDispatcher.resume().
Your StreamDispatcher is defined as DJ, so you can use:
DJ.pause(); // Pauses the stream.
DJ.resume(); // Resumes the stream.
DJ.destroy(); // Ends the stream.
I'm trying to make a 'random meme' command for my Discord Bot. I'm new to working with APIs, but I've tried my best.
The problem is, when I type the command, nothing happens. There are no errors, but the bot doesn't send anything in discord.
This is my code:
if (command === "meme")
async (client, message, args) => {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
Here Is One That Will Show Info About The Meme
if(command === "meme") {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/${random}.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('It seems we are out of memes');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("r/" + random)
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
Let Me Know If It Don't Work, But I Should
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === "meme") {
async (client, message, args) =>
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
});
This should work, not quite sure, haven't tested it. (You can put in a command handler your self)
if (command === "meme")
async (client, message, args) => {
const fetch = require('node-fetch');
let userAvatar = message.author.avatarURL({ format: "png", dynamic: true, size: 2048 }); // this is just the users icon, u can remove it if you want.
fetch(`https://meme-api.herokuapp.com/gimme`)
.then(res => res.json())
.then(async json => {
const embed = new MessageEmbed()
.setAuthor(`${json.title}`, `${userAvatar + "?size=2048"}`, `${json.postLink}`)
.setImage(`${json.url}`)
.setFooter(`👍${json.ups} | ${json.subreddit}`)
.setColor("RANDOM")
message.channel.send(embed).catch((error) => {
console.log("An error has occured on the \"meme\" command\n", error)
})
}
Here you go! I've tested this on my own command handler.
I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})