I searched for someone with the same error but didn't found. I'm trying to make a command that sets the nickname of a user but it gives me an error when changing the nickname (actually the code works because if I change the "mentionedMember.setNickname(args)" to something else like "mentionedMember.setNickname(message.author.id)" it works).
The error:
UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
nick: Could not interpret "['testing']" as string.
The code:
const Discord = require('discord.js');
const Client = new Discord.Client();
const Command = require('../../Structures/Command');
const { MessageEmbed } = require('discord.js');
const config = require('../../../config.json');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
aliases: ['nickname', 'name'],
description: "changes someone's nickname.",
category: 'mod',
usage: '<#person> <new nickname>',
});
}
async run(message, target) {
let userId = message.content.substring(message.content.indexOf(' ') + 1);
const args = message.content.split(' ').slice(2);
const mentionedMember =
message.mentions.members.first() ||
message.guild.members.cache.get(target) ||
message.guild.members.cache.get(args[0]);
const now = new Date();
if (!mentionedMember) {
try {
if (!message.guild.members.get(args.slice(0, 1).join(' ')))
throw new Error("There isn't someone with this ID!");
user = message.guild.members.get(args.slice(0, 1).join(' '));
user = user.user;
} catch (error) {
return message.channel.send(
`${message.author.username}, this username doesn't exists!`
);
}
}
if (
(mentionedMember.id !== message.guild.owner.id,
mentionedMember.id !== this.client.owners)
) {
if (!message.member.hasPermission('MANAGE_NICKNAMES'))
return message.channel.send("You don't have permissions!");
if (!message.guild.me.hasPermission('MANAGE_NICKNAMES'))
return message.channel.send(
"I don't have permissions to manage nicknames. Give it to me!"
);
if (
mentionedMember.roles.highest.position >=
message.member.roles.highest.position
) {
return message.channel.send("You can't change this user's nickname.");
}
if (!args) {
return message.channel.send('Remember mentioning someone!');
}
const LogChannel = await message.guild.channels.cache.find(
(channel) => channel.id == config.logModeraçãoId
);
var embed = new Discord.MessageEmbed()
.setAuthor(
`${message.author.username} - (${message.author.id})`,
message.author.displayAvatarURL()
)
.setThumbnail(mentionedMember.user.displayAvatarURL())
.setColor('#BA1F1F').setDescription(`
**Member:** ${mentionedMember.user.username} - (${
mentionedMember.user.id
})
**Action:** changing nickname
**Reason:** ${'not specified'}
**Time:** ${now}
`);
LogChannel.send(embed);
message.channel.send('Nickname changed!');
mentionedMember.setNickname(args);
}
}
};
args is an array, but GuildMember.setNickname() requires a string. You'll need to use args[0] to get the string you want.
the function .setNickname() accepts a parameter of type string. message.author.id is a string which is why it worked. args is an array so it doesn't work.
Related
hey i need my code which i wrote fixed because it wont work here it is the terminal shows the args arent defined if there is some how a different way to do this its accepted too thanks in advance. <3
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'tokengoeshere';
bot.on('message', message => {
if (!message.guild) return;
const ubWords = ["!unban", "?unban", ".unban","-unban","!ub","?ub",".ub","-ub"];
if (ubWords.some(word => message.content.toLowerCase().includes(word)) )
if(!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply(`, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
return message.reply(`, I do not have perms to unban someone`)
}
let userID = args[0]
message.guild.fetchBans().then(bans=> {
if(bans.size == 0) return
let bUser = bans.find(b => b.user.id == userID)
if(!bUser) return
message.guild.members.unban(bUser.user)
})
});
bot.login(token);
let userID = args[0]
if (!userID) return message.reply("Please specify the user ID you wish to unban!")
try {
message.guild.fetchBans().then(bans => {
if(bans.size === 0) {
return message.reply("There is no users banned!")
} else {
message.guild.members.unban(userID)
}
})
} catch (err) {
console.log(err)
}
You can simply define args like this:
const args = message.content.slice('?'.length).trim().split(/ +/g)
Put it after the message.guild check
I am working on an advanced suggestion command and here's my code so far:
if (command === 'accept') {
try {
const suggestionchan = bot.channels.cache.get('840493081659834403');
const acceptreason = message.content.split(' ')[2];
if(!acceptreason) return message.lineReply("Please provide the reason!")
const messageid = message.content.split(' ')[1];
console.log(messageid)
if(!messageid) return message.lineReply("Please provide the message id of the suggestion!")
const suggestionData = suggestionchan.messages.fetch(messageid)
const suggestionembed = suggestionData.embeds[0];
const acceptembed = new Discord.MessageEmbed()
.setAuthor(suggestionembed.author.name, suggestionembed.author.iconURL)
.setTitle("Suggestion!")
.setDescription(suggestionembed.description)
.setColor("GREEN")
.addFields(
{ name: `Accepted by ${message.author.tag}`, value: `**Reason:**\n${acceptreason}`}
)
.setFooter("Bot made by Sɱαɾƚx Gαɱιɳɠ YT")
suggestionembed.edit(acceptembed)
message.delete();
const user = bot.users.cache.find( (u) => u.tag === suggestionembed.author.name);
user.send(acceptembed)
} catch (err) { console.log(err)
message.lineReply("That message ID is not a valid ID!")}
}
I am getting an error on the part suggestionembed = suggestionData.embeds[0];
The error is TypeError: Cannot read property '0' of undefined at Client.<anonymous>
suggestionchan.messages.fetch returns a promise, so you'll need to resolve it first. You can either use the .then() method or the await keyword (as below).
It's also a good idea to check if the fetched message have any embeds.
if (command === 'accept') {
try {
const suggestionChannel = bot.channels.cache.get('840493081659834403');
const acceptReason = message.content.split(' ')[2];
if (!acceptReason)
return message.lineReply('Please provide the reason!');
const messageId = message.content.split(' ')[1];
if (!messageId)
return message.lineReply('Please provide the message id of the suggestion!');
const suggestionData = await suggestionChannel.messages.fetch(messageId);
const suggestionEmbed = suggestionData.embeds[0];
if (!suggestionEmbed)
return message.lineReply(`The message with ID ${messageId} doesn't have any embeds!`);
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(suggestionEmbed.author.name, suggestionEmbed.author.iconURL)
.setTitle('Suggestion!')
.setDescription(suggestionEmbed.description)
.setColor('GREEN')
.addFields({
name: `Accepted by ${message.author.tag}`,
value: `**Reason:**\n${acceptReason}`,
})
.setFooter('Bot made by Sɱαɾƚx Gαɱιɳɠ YT');
suggestionData.edit(acceptEmbed);
message.delete();
const user = bot.users.cache.find(
(u) => u.tag === suggestionEmbed.author.name,
);
user.send(acceptEmbed);
} catch (err) {
console.log(err);
message.lineReply('That message ID is not a valid ID!');
}
}
So when i warn a user it works perfectly, but when i try to warn again a person it replace the old string (the reason) but i want to make it add and keep the old string. (the reason) i tryed many things but still, fs is replacing automaticaly the old string (the reason).
And there is my javascript code :
const Discord = require("discord.js")
const fs = require("fs");
module.exports = {
name: "warn",
description: "Warn command",
async execute( message){
let config = require("../config.json")
let lang = JSON.parse(fs.readFileSync("./langs.json", "utf8"));
if(!lang[message.guild.id]){
lang[message.guild.id] = {
lang: config.lang
};
}
let correct1 = lang[message.guild.id].lang;
const ping = require(`../lang/${correct1}/warn.json`)
const response = ping
const messageArray = message.content.split(' ');
const args = messageArray.slice(1);
let sEmbed1 = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle("Permission refused.")
.setDescription("<:dont:803357503412502588> | You don't have the permission for this command. (`MANAGE_ROLES`)");
if(!message.member.hasPermission("MANAGE_ROLES")) return message.reply(sEmbed1)
const user = message.mentions.users.first()
if(!user) {
return message.channel.send("<:dont:803357503412502588> | You need to mention a user.")
}
if(message.mentions.users.first().bot) {
return message.channel.send("<:dont:803357503412502588> | You can't warn a bot")
}
if(message.author.id === user.id) {
return message.channel.send("<:dont:803357503412502588> | You can't warn yourself!")
}
const reason = args.slice(1).join(" ")
if(!reason) {
return message.channel.send("<:dont:803357503412502588> | You need a reason")
}
const warnings = {
reason: `${reason}`,
guild_id: `${message.guild.id}`,
user_id: `${user.id}`,
moderator: `${message.author.username}`
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
}
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
Could you replace line 2 with fs.writeFileSync("./warnings.json", jsonString, {'flags': 'a'}, err => {
I'm making a command that would remove all roles from a user and give him one specified role. However, I've run into a problem that it doesn't remove the roles, giving me the [INVALID_TYPE]: Supplied roles is not an Array or Collection of Roles or Snowflakes. error. My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let antagonistRoleList = JSON.parse(
fs.readFileSync("./roleIDs/antagonistRole.json", "utf-8")
);
const commands = require("./commands");
module.exports = {
name: "antagonise",
description: "The bot will antagonise the mentioned user",
execute(message, args) {
let antagonistRoleList = JSON.parse(
fs.readFileSync("./roleIDs/antagonistRole.json", "utf-8")
);
let guildID = message.guild.id;
let antagonistRole = antagonistRoleList[guildID].antagonistRoleList;
var member = message.mentions.members.first(); // || message.guild.members.cache.get(args[0]);
var role = message.guild.roles.cache.get(
`${antagonistRoleList[guildID].antagonistRoleList}`
);
if (!member) {
var member = message.guild.members.cache.get(args[0]);
var antagReason = args.join(" ").slice(18);
} else {
var antagReason = args.join(" ").slice(22);
}
if (!member) {
return message.reply(
"please specify the user that should be antagonised"
);
}
if (!role) {
return message.reply(
"there is not a role set as the antagonist role, set it by doing &setantagonistrole (that requires manage server permissions)"
);
}
if (!antagReason) {
antagReason = "no reason given";
}
if (member.id === message.author.id) {
return message.reply("can not allow self-harm");
}
if (
message.member.roles.highest.comparePositionTo(member.roles.highest) <= 0
) {
return message.reply(
"you can not antagonise a user with the same (or higher) permissions as you"
);
}
if (!message.member.permissions.has("MANAGE_ROLES")) {
return message.reply(
`you don't have manage roles permissions that are required to execute this command.`
);
}
console.log(`${role}`);
console.log(`${antagonistRole}`);
if (member.roles.cache.has(`${antagonistRole}`)) {
return message.reply("this user is already antagonised!");
}
member.roles.remove(member.roles).catch((error) => {
console.log(error);
});
member.roles
.add(role)
.then((memberAdded) => {
message.reply(
`you have succesfully antagonised <#${member.id}> with the reason **${antagReason}**`
);
})
.catch((error) => {
console.log(error);
});
const embed = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`You were antagonised in ${message.guild.name}`)
//.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
.addFields({ name: `Antagonised by`, value: `${message.author.tag}` })
.addFields({ name: `Reason`, value: `${antagReason}` })
.setTimestamp();
member.user.send(embed).catch((error) => {
message.channel.send(
`Failed to DM <#${member.id}> the info about this action`
);
console.log(error);
});
console.log(`${antagonistRoleList[guildID].antagonistRoleList}`);
console.log(`${message.guild.name}`);
console.log(`${message.author.tag}`);
console.log(`${antagReason}`);
},
};
What have I done wrong? I'm pretty sure it's a mistake in the member.roles.remove(member.roles) line, but what should I change it to?
The member.roles.remove methods takes a Role, Array of Roles or Collection of Roles as an argument. You've supplied the method with member.roles, which according to the docs, is of type GuildMemberRoleManager, which isn't an accepted argument type for the remove method.
Try changing member.roles.remove(member.roles) to member.roles.remove(member.roles.cache), since the cache property returns a Collection of Roles.
This works for me (discord.js v12):
let role = message.member.guild.roles.cache.find(role => role.name === "RoleName");
if (role) message.guild.members.cache.get(message.author.id).roles.remove(role);
making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.