Discord Bot setting someones nickname - javascript

I am trying to make a Discord bot and I want to make a !nick command and I keep getting the same error, could someone help me:
ERROR:
{ DiscordAPIError: Missing Permissions
at item.request.gen.end (/rbd/pnpm-volume/76d7cd6d-9602-4908-bb55-ccc4f8de8537/node_modules/.registry.npmjs.org/discord.js/11.4.2/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:79:15)
at then (/rbd/pnpm-volume/76d7cd6d-9602-4908-bb55-ccc4f8de8537/node_modules/.registry.npmjs.org/snekfetch/3.6.4/node_modules/snekfetch/src/index.js:215:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
name: 'DiscordAPIError',
message: 'Missing Permissions',
path: '/api/v7/guilds/485921672013283339/members/469227202345697280',
code: 50013,
method: 'PATCH' }
CODE:
const Discord = require("discord.js");
exports.run = (client, message, args, member) => {
const arg = args.join(" ")
if (arg === null || arg === "" || arg === undefined || arg == " ") {
var embed = new Discord.RichEmbed()
embed.setColor(0x00AE86);
embed.addField("USAGE", "!nick (nickname)", false);
message.channel.send(embed);
}
else {
var embed = new Discord.RichEmbed()
embed.setColor(0x00AE86);
embed.addField("NICKNAME", "You have set your nickname to **" + arg + "**", false);
message.channel.send(embed);
message.member.setNickname("["+ member.highestRole.name + "]" + member.displayName)
.then(console.log)
.catch(console.error);
}
}
Does anyone know why I am getting this error, if so please tell me HOW to fix it. Thank you!

From message: 'Missing Permissions' we can conclude that your bot is missing the required permissions.
To fix the issue go to your Discord Developer Portal and get the PERMISSIONS INTEGER that contains the permissions you need. The most common is 8, which is the integer for Administrator permissions.
If that doesn't work, ensure that your bot's role is above others in your Discord Server
as shown here

Related

Discord.JS UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined

I'm currently trying to implement speech recognition into a discord bot, but I keep running into errors. I'm also new to Discord.JS and programming as a whole.
I copied some of the following code from an event file that interprets normal messages instead of speech, and it works fine there.
The following line throws an "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined": if (!msg.content.startsWith(prefix) || msg.author.bot) return;
My entire file:
const fs = require('fs');
module.exports = {
name: "join",
description: "Joins the VC that user is in",
async execute(client, message, args, Discord) {
const voiceChannel = message.member.voice.channel;
const connection = await voiceChannel.join();
if (!voiceChannel) return message.channel.send('Join a VC retard');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send("You don't have the correct permissions");
if (!permissions.has('SPEAK')) return message.channel.send("You don't have the correct permissions");
connection.client.on('speech', msg => {
console.log(msg.content);
const prefix = 'yo bot ' || 'Aries ' || 'Ares ' || 'yobot ';
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if (command) command.execute(client, msg, args, Discord);
})
}
}
If message content is not a string then you cannot use that function.
You need to check if message content exists first:
if (!msg.content
|| !msg.content.startsWith(prefix)
|| msg.author.bot
) {...}
You need to make sure that the message content is defined, before reading it's startsWith property. You can do this with optional chaining.
if (!msg?.content?.startsWith(prefix) || msg.author.bot) return;
msg?.content?.startWith(prefix) will return undefined if either:
msg does not have a content propery
content does not have a startWith property

I want to disable discord bot commands in dms but I keep getting an error

This is my discord reject code:
client.on('message', msg => {
if (msg.channel instanceof Discord.DMChannel && msg.author.id !== "828093594098204702") {
const Reject = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle('Error')
.setDescription('This command can only be used in the server.')
msg.author.send(Reject);
}
})
This is the error I'm getting:
const member = msg.guild.members.cache.get(msg.author.id);
^
TypeError: Cannot read property 'members' of null
at Client.<anonymous>
How can I fix this?
(v13)
I know, that you are using messages, but if you will you'll change your mind and will start using slash commands, use if (!interaction.guild) return;, this will disable slash commands in DMS. Also you can add interaction.followUp to return a message.
client.on("message", message => {
if(message.author.bot
|| message.channel.type === "dm") return;
// your code here
}
this is what I use to filter out bots and dms.

Discord.js v12 Ban Command

I made a ban command for my discord.js v12 bot. However whenever I run the command I get an error.
Here is my code:
const Discord = require('discord.js');
module.exports = {
name: "ban",
description: "Kicks a member from the server",
async run (client, message, args) {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send('Please specify a user');
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban(`${reason}`).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Kicked by', message.author)
.addField('Reason', reason)
.setFooter('Time kicked', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
This is the error I get whenever I run the command
DiscordAPIError: Invalid Form Body
DICT_TYPE_CONVERT: Only dictionaries may be used in a DictType
at RequestHandler.execute (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
method: 'put',
path: '/guilds/751424392420130907/bans/155149108183695360',
code: 50035,
httpStatus: 400
}
I could'nt understand how to correct the problem in the code. I'm a bit new to coding. Can you please help me out!. Thanks in advance
This is pretty easy to solve, all you have to to is pass the right amount of Parameters in the right way to the .ban function.
.ban({ days: 7, reason: 'your reason here' })
https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=ban
This looks like code from my video. It is a very simple error I made in the code. The .ban part should actually look like this:
.ban({ reason: 'your reason here' })
-thesportstacker

discord.js UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined

Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...

"send" is undefined? | Discord.js

const Discord = require ("Discord.js")
exports.exec = async (client, message, args) => {
const bug = args.slice().join(" ");
if (!args[0]) return message.channel.send(`${message.author}\` Please right, in as much detail about the bug\``);
const channel = client.channels.get('498750658569306123')
const embed = new Discord.RichEmbed()
.setAuthor(message.author.tag, message.author.avatarURL)
.setColor(0)
.setDescription(bug)
.setTimestamp()
.setFooter(`Suggestion by ${message.author.tag} from ${message.guild.name}`)
channel.send(embed)
Error thrown back is:
TypeError: Cannot read property 'send' of undefined
at Object.exports.exec (C:\Users\Cake\Peepo\modules\help\bugreport.js:14:11)
Everything seems to work fine.. I'm unsure how "send" is undefined? Someone care to explain?
Try doing this to find your report channel.
let channel = message.guild.channels.find(c => c.name === "report-channel-name-here");
channel.send(embed);
if that fails, make sure that your bot can access the channel.

Categories

Resources