Sometimes bot won't add role and set the nickname - javascript

I set up a bot so whenever someone types t!accept #user [nickname] it will add a role to the user and changes the user's nickname. This is my code :
mention = message.mentions.members.first();
if (msg.startsWith (prefix + "accept")){
if(!message.member.hasPermission("MANAGE_ROLES")) return message.reply("You have no permission!");
if (mention == null) { return; }
let args = message.content.split(" ").slice(2);
mention.roles.add('123456789')
mention.setNickname(mention.displayName+" "+args.join(' '))
mention.send("Congratulations");
try{
await message.author.send("Sent.")
}catch(e){
message.channel.send("An error has occured.")
}
}
However, only most of the time it will fully work, sometimes it won't do both things, and sometimes it will only do one of the task (Add role, but not nickname and vice versa)
Is there anything wrong with my code?
Thanks in advance!

It's possible the nickname you're providing at times is too long and exceeds discords nickname length limit of 32 characters. You should add a check of:
if ((mention.displayName + " " + args.join(" ")).length > 32) return message.channel.send("The nickname exceeds 32 characters")
However that could not be it of course, I would've posted a comment beforehand but I unfortunately do not have enough reputation.

Related

Get balance of other people

I'm basically trying to making a balance command (with quick.db) that checks for yourself and for other people as well, suppose -bal
(my balance pop up) but then when I ping someone with -bal #(user) it shows my current balance as well, here's an image:
I've also tried lots of ways but it seems to not work for me :/
Here's the code:
let bal =
db.fetch(`money_${message.guild.id}_${message.author.id}`) ||
db.fetch(`money_${message.guild.id}_${message.mentions.users.first()}`);
if (bal === null) bal = 0;
let user = message.mentions.users.first().username || message.author.username;
const embed = new Discord.MessageEmbed()
.setTitle('[ ' + user + "'s balance ]")
.setDescription(bal);
message.channel.send(embed);
You need to check the order of values when you declare the bal variable. You're basically saying that if there is a message.author then bal's value will be their balance. As there is always a message author, you will never check the mentioned user. So, you need to change the order.
Or, you could also simplify it like I did below. You can create a new user variable and if there is a mentioned user, assign its value, if not, assign the author. Later, as both the mentioned user and the author has an id and a username, you can simply use user.id and user.username.
You can also simplify the if (bal === null) bal = 0 part, by simply using a logical OR (||) after the db.fetch.
let user = message.mentions.users.first() || message.author;
let balance = db.fetch(`money_${message.guild.id}_${user.id}`) || 0;
const embed = new Discord.MessageEmbed()
.setTitle('[ ' + user.username + "'s balance ]")
.setDescription(balance);
message.channel.send(embed);

Discord.js sell command won't work, stops running after certain line

I am trying to make a discord bot with an economy, everything was going well until I got to the sell command. When I try to sell, the bot just doesn't respond. It only responds on the lines where it will return message.channel.send
Can anyone help me?
Code:
if (message.content === `${prefix}sell`) {
let item = message.content.split(" ").slice(1).join(" ");
if (!item) return message.channel.send("Please enter what you want to sell!");
item = item.toLowerCase();
if (animals.includes(item) === false) return message.channel.send("That is not a valid thing to sell!");
let inventory = db.get(`Data_${message.author.id}.inv`);
if (inventory.includes(item) === false) return message.channel.send("You don't have a " + item + "!");
let price = prices[animals.indexOf(item)];
let embed = new Discord.MessageEmbed()
.setTitle("Sold!")
.setDescription("You sold 1 " + item + " and got " + price.toString() + " for it.")
.setColor(embedColor);
message.channel.send(embed);
message.channel.send("Sold.");
db.add(`Data_${message.author.id}.coins`, price);
let newInventory = inventory.splice(inventory.indexOf(item), 1);
db.set(`Data_${message.author.id}.inv`, newInventory);
}
Things I have tried:
Logging each line to see where it stops, it will send an error message if you don't meet a requirement, but if you meet it the bot just doesn't respond.
Turning lines of code into comments to see what is not working (This didn't help me)

How to get text from individual users

I'm trying to make a notes command for specific users, but my Discord bot makes the notes any note that a user public has said. How do I fix this? I already know the problem with my code, but I don't know how to fix it.
if (command == "Note") {
const notes = db.fetch('userInfo');
while (!args[0]) return message.channel.send("Here are your notes: " + notes);
db.set('userInfo', args.join(' '));
message.channel.send((args.join(' ')) + (" successfully noted!"));
}
You have a row called userInfo, this row gets updated whenever someone executes the command. If you want it to link with a user, you're better of using the id of the user because everyone has a different ID. I suggest using something like:
const notes = db.fetch(`userInfo.${message.author.id}`)
while (!args[0]) return message.channel.send("Here are your notes: " + notes )
db.set('userInfo.${message.author.id}', args.join(' '))
message.channel.send(args.join(' ') + " successfully noted!")

Discord.js mention players on welcome

a few days ago i made a code to mention users when they join my discord server, this is the code i currently have:
bot.on( "guildMemberAdd", member => {
let textChannel = member.guild.channels.find(channel => channel.id === '569582472812298240');
if (textChannel){
var messages = [
`Brace yourselves. <#${member.user.id}> just joined the server.`,
`Challenger approaching - <#${member.user.id}> has appeared`,
`Welcome <#${member.user.id}>. Leave your weapon by the door.`,
`Big <#${member.user.id}> showed up!`,
`<#${member.user.id}> just joined... or did they?`,
`Ready player <#${member.user.id}>`,
`<#${member.user.id}> hopped into the server. Kangaroo!!`,
`<#${member.user.id}> joined. You must construct additional pylons.`,
`Hello. Is it <#${member.user.id}> you're looking for?`,
`Where's <#${member.user.id}> in the server!`,
`It's dangerous to go alone, take <#${member.user.id}>`
]
textChannel.send({embed: {
color: 3447003,
description: messages[ Math.floor( Math.random() * 11 ) ],
timestamp: new Date(),
}
});
}
});
The problem? Sometimes i get the correct nickname of the person as you can see in this picture, but other times i get just numbers and i can't even click on that 'link'...
Correct way:
They are clickable and i can see their profile.
Incorrect way:
I can't click their id, nothing can be done with it.
Not sure why this happens randomly, any help would be extremely appreciated.
If someone joins the server and then leaves, and you have no other mutual servers with them and are not their friend, it'll just show their user id. This is a client side thing and there isn't really any real fix for mentions. You can however opt to just send their username instead of a mention.
You could try running toString on the member object, as it will automatically generate the right mention (as sometimes it can be prepended with <#!), but the likely reason it still won't work is because your Discord client did not cache the user that just joined.
It can be either because you're in a log channel, the server has too many members or the member left before your Discord client cached the user. You can either try to not use an embed, or (probably the best solution) provide the full username as well as the mention in the embed.
Try this:
bot.on('guildMemberAdd', member => {
var ran = randomRange(0,2);
var greeting;
switch (ran) {
case 0:
greeting = "Brace yourselves. " + member.user + " just joined the server.";
break;
case 1:
greeting = "Challenger approaching - " + member.user + " has appeared";
break;
case 2:
greeting = "Welcome " + member.user + ". Leave your weapon by the door.";
break;
// add more if you want (but dont forget to also change the values in line 2
}
member.guild.channels.get('CHANNEL ID HERE').send(greeting);
});
And add this function:
function randomRange(min, max) { // returns an int >= min and <= max
return Math.floor(Math.random() * (max - min + 1)) + min;
}

nodejs discord bot - message with words separated by emojis

I'm writing my first Discord bot. I want him to read a users message, and then send the message back, with words separated by emojis. So the effect would be something like this: https://i.stack.imgur.com/ysg4f.png
So this is theoretically working - I say theoretically, because I used completely ridiculous solution just to show what I'm aiming for:
if (message.substring(0, 2) == "m.") {
var args = message.substring(2).trim().split(/ +/g);
var cmd = args.shift().toLowerCase();
switch (cmd) {
// m.clap
case "clap":
bot.sendMessage({
to: channelID,
message:
":clap: " + args[0] + " :clap: " + args[1] + " :clap: " + args[2],
});
break;
}
}
So, obviously, this only works for max. three words sentences, and I need it to work for any length of the sentence.
I tried wrapping the "sendMessage" function in a for loop, iterating from 0 to args.length, but that makes the bot send each word in a separate message, obviously. And it won't let me put a for loop inside of the sendMessage function.
Any help would be greatly appreciated. Thank you!!!
You can use the join() method.
message: ':clap: ' + args.join(':clap: ')

Categories