Discord bot can not read files with commands - node.js

I put this into my code:
const pmie = require("./commands/pmie.js");
and I made directory commands and put file "pmie.js" in there
This is code in file pmie.js:
const Disocrd = require("discord.js");
const client = new Disocrd.Client();
const prefix = ""
client.on("message", (message)=>{
if(!message.content.startsWith(prefix)) return;
if(message.content.startsWith(prefix + "pmie")){
let author = message.member;
let role = message.guild.roles.find('name', "Founder");
if(author.roles.has(role.id)){
message.reply("You have Permission.");
return
}else{
message.reply("You don't have permission");
}
}
})
But bot does not do anything when I use "pmie" command, what's wrong?

To fix that you would need something like this.
pmie.js:
module.exports = function (client, message, Discord, prefix) {
if(!message.content.startsWith(prefix)) return;
if(message.content.startsWith(prefix + "pmie")){
let author = message.member;
let role = message.guild.roles.find('name', "Founder");
if(author.roles.has(role.id)){
message.reply("You have Permission.");
return
}else{
message.reply("You don't have permission");
}
}
Your main javascript file:
client.on('message', message => {
const pmie = require("./commands/pmie.js")
pmie(client, message, Discord, prefix)
})
Hopefully this solves your issue.

Related

How to show username when we speak though a discord bot

client.on('messageCreate', message => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572"){
var messageContent = message.content;
client.channels.cache.get('1012048291111903292').send(messageContent)
}
});
This code can only send a message from a channel to another though a bot but it's only the bot speaking, I want to add which user is speaking. How can i implement this?
Use this
client.on('messageCreate', async (message) => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572") {
const { content, member, author } = message
const channel = await client.channels.fetch('1012048291111903292')
// for nickname:
const str = `**${member.displayName}:**\n${content}`
// for username and tag
const str = `**${author.tag}:**\n${content}`
// you may only use one of these. when you
// adapt it to your own code, remove one of
// these "str", keep the one you want
channel.send({ content: str })
}
})

Setting up chatbot command in discord.js 12

i wanted to make a chatbot command like a example of command
?bsetchatbot [channel name]
heres a syntax of the command and here what code i used
note - i already impoted required modules
const Chat = require("easy-discord-chatbot");
const chat = new Chat({ name: "Blabbermouth" });
if (message.content === "?bsetchatbot") {
channelname = message.mentions.channels.first()
if(!channelname) {
return message.channel.send("Pleease Mention A channel!")
}
if(message.channel.name === `${channelname}` && !message.author.bot) {
let reply = await chat.chat(message.content)
message.channel.send(reply)
}
message.channel.send(`Chat Bot Channel is set as ${channelname}`)
}
The problem is that you don't save the channel where people can chat with the bot. I recommend to save the channel with the ValueSaver package as you can can save it and import it again when your server shut down. Here is an example
const { ValueSaver } = require('valuesaver');
const channels = new ValueSaver();
channels.import(`channels`); // Import the ValueSaver named 'channels' if a save exists with this name
const { Client } = require('discord.js');
const Chat = require('easy-discord-chatbot');
const chat = new Chat({name: 'Blabbermouth'});
const client = new Client();
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag} on ${new Date().toString()}`);
});
client.on('message', async message => {
if(message.author.bot || message.channel.type === `DM`) return;
let args = message.content.substring(1).split(" ");
const _channelid = channels.get(message.guild.id); // Get the channel id
if(_channelid){ // If there has been set a channel
if(message.channel.id === _channelid){ // If the channel is the chat channel
let reply = await chat.chat(encodeURI(message.content));
message.channel.send(reply).catch(console.log)
}
}
if(message.content.startsWith('?')){
switch(args[0].toLowerCase()){
case 'bsetchatbot':
const channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`Please mention a channel to set the chat channel`).catch(console.log);
channels.set(message.guild.id, channel.id); // Access the channel id by the guild id
channels.save(`channels`); // Create a new save with the name 'channels'
break;
}
}
});
client.login('Your Token');
ValueSaver: https://npmjs.com/package/valuesaver

My bot says it doesnt have permissions to kick/ban

I am making a Discord bot in js. Yesterday i finished some work on the bot's ban command and it worked normally. Today I wake up, don't modify anything and when I try it again, it says that it does not have permission. Nothing was changed and noone changed the permissions of the bot, it still has administrator. The error message:
(node:2490) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
My code is (a bit long):
const Discord = require("discord.js");
const dp = require('discord-prefix');
const lang = require('../language_manager');
const settings = require('discord-server-settings');
module.exports = (message, client) => {
if (!message.member.permissions.has("BAN_MEMBERS")) return message.reply("You do not have the permission to ban users");
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.reply("I do not have permission to ban users");
let prefix = dp.getPrefix();
if(dp.getPrefix(message.guild.id)){
prefix = dp.getPrefix(message.guild.id);
}
var langchar = settings.getSetting('lang', message.guild.id)
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
var noerror = true;
const member = getUserFromMention(args[0]);
const reason = args[1] || lang.get('ban_no_reason', langchar);
const embed1 = new Discord.MessageEmbed()
.setAuthor('AUN', 'https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI')
.setTitle(lang.get('ban_title', langchar))
.setColor('#ed3f2c')
.setDescription(lang.get('ban_noone_banned', langchar))
.setTimestamp()
.setFooter('Ping: ' + client.ws.ping + ' | '+prefix+command);
const embed = new Discord.MessageEmbed()
.setTitle(lang.get('ban_you_title', langchar))
.setAuthor("AUN", "https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI")
.setColor(0x00AE86)
.setDescription(lang.get('ban_you_part1', langchar)+message.guild.name+lang.get('ban_you_part2', langchar)+message.member.name+lang.get('ban_you_part3', langchar)+reason)
.setFooter("Ping: "+client.ws.ping+" | AUN discord bot")
.setTimestamp();
if (!member) {
embed1.setTitle(lang.get('ban_error', langchar))
.setDescription(lang.get('ban_no_mention', langchar))
.setColor('#bd1300');
noerror = false;
}
if(noerror){
embed1.setDescription(lang.get('ban_banned_part1', langchar)+member.tag+lang.get('ban_banned_part2', langchar));
member.send(embed);
}
message.channel.send(embed1);
try{
return message.guild.member(member).ban();
}catch (e){
return;
}
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
}
Please if you have any idea what is going on, tell me
You should check if you can actually ban the member.
You can check this with
GuildMember#manageable

Discord.js code wont ban people. How do i fix this?

So i have coded a little ban command here is the code
if (message.content.startsWith(`${prefix}ban`)) {
let member = message.mentions.members.first();
member.ban().then((member) => {
message.channel.send(`:wave: ${member.displayName} has been kicked`);
}).catch(() => {
if (!message.member.hasPermission(['BAN_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannot ban members");
} else if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannont ban this member");
}
})
}
And when i do my prefix ban and then the player name it does not ban them and i dont get any errors in the console so can i please have some help
Thnaks
Robin
You can do it like this
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', (message) => {
let args = message.content.split(' ');
let command = args.shift();
if (command === 'ban') {
let member = message.mentions.members.first() || message.guild.members.get(args[0]);
if (!member) return message.reply('pls mention a member or write ID for BAN');
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('You has no permission for ban members');
if (message.member.roles.highest <= member.roles.highest) return message.reply(`You can't ban member with the same or highest role position`);
if (!member.manageable) return message.reply('I cant ban this member');
member.ban();
}
});
my answer was the
client.on('message', (message) => {
let args = message.content.split(' ');
let command = args.shift();
if (command === 'ban') {
let member = message.mentions.members.first() || message.guild.members.get(args[0]);
if (!member) return message.reply('pls mention a member or write ID for BAN');
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('You has no permission for ban members');
if (message.member.roles.highest.position <= member.roles.highest.position) return message.reply(`You can't ban member with the same or highest role position`);
if (!member.manageable) return message.reply('I cant ban this member');
member.ban();
}
});
This will definitely work:
if (message.content.startsWith('+ban')){
const user2 = message.mentions.users.first();
// If we have a user mentioned
if (user2) {
// Now we get the member from the user
const member = message.guild.member(user2);
const banembed = new Discord.MessageEmbed()
.setDescription("*You don't have permission to use this command*")
.setColor(0xffe6f7)
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send(banembed)
// If the member is in the guild
if (member) {
/**
* Ban the member
* Make sure you run this on a member, not a user!
* There are big differences between a user and a member
*/
member
.ban('Being bad') //This is the reason
.then(() => {
// We let the message author know we were able to kick the person
const bannedembed = new Discord.MessageEmbed()
.setDescription(`***Successfully banned ${user2.tag}***`)
.setColor(0xffe6f7)
message.channel.send(bannedembed)
})
.catch(err => {
// An error happened
// This is generally due to the bot not being able to kick the member,
// either due to missing permissions or role hierarchy
message.reply('I was unable to ban the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
const nomemembed = new Discord.MessageEmbed()
.setDescription("*That user isn't in this server!*")
.setColor(0xffe6f7)
message.channel.send(nomemembed)
}
// Otherwise, if no user was mentioned
} else {
const nobanmentionembed = new Discord.MessageEmbed()
.setDescription("*You didn't mention the user*")
.setColor(0xffe6f7) //you can remove the color if you want
message.channel.send(nobanmentionembed)
}
}

Discord.js "Error: FFMPEG not found" but I'm pretty sure I have it

I'm learning Discord.js and following this tutorial: https://discord.js.org/#/docs/main/stable/topics/voice . From the start, when I try to run- npm install ffmpeg-binaries I get a huge error message but it tells me to just use install ffmpeg so I did.
Here is my Index.js page(I've replaced my token with * here):
const Discord = require('discord.js');
const Colesbot = new Discord.Client();
const token = '**********************************';
Colesbot.on('ready', () =>{
console.log('Slamsbot is online.');
})
Colesbot.on('message', msg=>{
if(msg.content == "What up bot?"){
msg.reply("Whats good pimp?")
}
});
Colesbot.on('message', message=>{
if (message.content === '/join') {
// Only try to join the sender's voice channel if they are in one themselves
if (message.member.voiceChannel) {
message.member.voiceChannel.join().then(connection => {
message.reply('I have successfully connected to the channel!');
}).catch(console.log);
} else {
message.reply('You need to join a voice channel first!');
}
}
});
//Event listener for new guild members
Colesbot.on('guildMemberAdd', member =>{
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(ch => ch.name === 'general');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}. Please use the bot-commands channel to assign yourself a role.`);
})
Colesbot.login(token);
exports.run = (client, message, args) => {
let user = message.mentions.users.first || message.author;
}
If I type "/join" while not connected to a voice channel I get the proper message. However, if I try while I am I get this error message:
Error: FFMPEG not found
task_queues.js:94
message:"FFMPEG not found"
stack:"Error: FFMPEG not found\n at Function.selectFfmpegCommand (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:46:13)\n at new FfmpegTranscoder (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:7:37)\n at new MediaTranscoder (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\MediaTranscoder.js:10:19)\n at new Prism (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\Prism.js:5:23)\n at new VoiceConnection (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\discord.js\src\client\voice\VoiceConnection.js:46:18)\n at c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\discord.js\src\client\voice\ClientVoiceManager.js:63:22\n at new Promise (<anonymous>)\n at ClientVoiceManager.joinChannel (c:\Users\bobal\Documents\GitHub\Spotif...
So I went to that folder and the file Ffmpeg.js is there and here is its contents:
const ChildProcess = require('child_process');
const FfmpegProcess = require('./FfmpegProcess');
class FfmpegTranscoder {
constructor(mediaTranscoder) {
this.mediaTranscoder = mediaTranscoder;
this.command = FfmpegTranscoder.selectFfmpegCommand();
this.processes = [];
}
static verifyOptions(options) {
if (!options) throw new Error('Options not provided!');
if (!options.media) throw new Error('Media must be provided');
if (!options.ffmpegArguments || !(options.ffmpegArguments instanceof Array)) {
throw new Error('FFMPEG Arguments must be an array');
}
if (options.ffmpegArguments.includes('-i')) return options;
if (typeof options.media === 'string') {
options.ffmpegArguments = ['-i', `${options.media}`].concat(options.ffmpegArguments).concat(['pipe:1']);
} else {
options.ffmpegArguments = ['-i', '-'].concat(options.ffmpegArguments).concat(['pipe:1']);
}
return options;
}
/**
* Transcodes an input using FFMPEG
* #param {FfmpegTranscoderOptions} options the options to use
* #returns {FfmpegProcess} the created FFMPEG process
* #throws {FFMPEGOptionsError}
*/
transcode(options) {
if (!this.command) this.command = FfmpegTranscoder.selectFfmpegCommand();
const proc = new FfmpegProcess(this, FfmpegTranscoder.verifyOptions(options));
this.processes.push(proc);
return proc;
}
static selectFfmpegCommand() {
try {
return require('ffmpeg-binaries');
} catch (err) {
for (const command of ['ffmpeg', 'avconv', './ffmpeg', './avconv']) {
if (!ChildProcess.spawnSync(command, ['-h']).error) return command;
}
throw new Error('FFMPEG not found');
}
}
}
module.exports = FfmpegTranscoder;
I also added ffmpeg to system path and it didn't help:
C:\ffmpeg
C:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\ffmpeg
I'm not quite sure what to do from here. If you need any other info I'd be glad to give it.

Resources