Add role to user from DMs? - javascript

So I'm making a verification bot for one of my Discord Servers, and I've come across a problem.
Purpose:
When the user first joins, they will be only allowed to talk in one specific channel, the verification channel. When they type $verify {username on-site}, the bot will reply in-server telling the user to check their DMs to continue. A unique string linked to a verification row in the database will be given, and the discord user will be told to change their status on-site to the given unique ID. Once they do that, they will be given the "Verified" role and will be able to speak on the discord.
The problem:
When everything goes right, and the user is ready to be given the role on the discord server, the bot will not give the role. I'm assuming this is because the user that the bot is trying give the role to is not linked to the actual discord server for it, because it's in DMs.
What I'm looking for:
If possible, give me an example on how to give a role to a user on a discord server from DMs, or documentation. That would be really helpful!
Code: I'll only include the part that is important, there is no other errors.
snekfetch.get("https://vertineer.com/api/getUniq.php?discord_id="+message.author.id).then(function(r){
console.log("here 2");
let uniq = JSON.parse(r.text);
if(uniq.id == uniq.status){
message.member.addRole("Verified");
message.reply("Success!");
} else {
message.reply("Looks like you didn't change your status to `"+uniq.id+"`, try again with `$finish`.");
}
});

If this is only to work for one server you can do:
client.guilds.get('myguildID').members.get(message.author.id).addRole('193654001089118208')
And also, to give a role to a user you can't use the name. You need to use the ID or the Role Object.
If you would prefer to use the name you would need to do something like this:
var role = client.guilds.get('myguildID').roles.find(role => role.name === "Verified");
client.guilds.get('myguildID').members.get(message.author.id).addRole(role);

This is what worked for me:
client.guilds.fetch(<guild.id>).then(async(guild) => {
let role = guild.roles.cache.find(r => r.name === <role.name>);
let member = await guild.members.fetch(<member.id>);
member.roles.add(role);
});
Substitute <guild.id>, <member.id> and <role.name> for the desired values respectively

Related

make an autorole for discord.js v12

I wanna make my bot give automatically role when my friends join for first time to my server: I have tried this one my VPS node version: 12.19.0v:?
client.on('guildMemberAdd', member => {
console.log('User #' + member.user.tag + ' has joined the server!');
var role = member.guild.roles.cache.find(role => role.name == "Newbie")
let user = member.user
user.roles.add(role);
});
but nothing is working ! help me pls
Discord is now enforcing privileged intents. The GUILD_MEMBERS intent is required to receive events such as guildMemberAdd and guildMemberUpdate.
To learn how intents work and how to use them, check out discord.js' detailed guide.
Also, as stated in the comments, you need to use message.member instead of message.user
You need to know the difference between Members and Users. A user represents a Discord account, a member represents a user being in a server. So for example to get someone's tag, you need to do user.tag, member.tag wouldn't work. It's the same with nicknames, user.displayName woudln't work, because a user is an account, a member is a user in a server. You'd do member.displayName instead.
Anyway, where you put
let user = member.user
user.roles.add(role);
it should be replaced with
member.roles.add(role);
and that should hopefully solve your problem.

How do I get a discord bot to mention a role and a user?

I am trying to make a bot that, whenever someone says something, it sends a message in the channel saying that that person is there and is waiting for someone to join. However, it only prints #ne1 (the role I want it to mention) as plain text. Also, when I have it mention the user, it only writes the user ID instead of actually sending #(username).
const Discord = require('discord.js');
const keepAlive = require('./server');
const client = new Discord.Client();
client.on('message', message => {
if (message.toString().toLowerCase().includes('ne1 here')) {
message.channel.send('#ne1, ' + message.author + ' is online and waiting for you to join!');
}
});
keepAlive();
client.login(process.env.TOKEN);
What I want is for it to mention the #ne1 role and the person who used the command to run the bot. It only prints, "#ne1 571713056673890324 is online and waiting for you to join!"
Discord mentions (role, user, etc.) have a special format as detailed in the documentation here.
So, to mention a user you need to use their user ID <#USER_ID>/<#!USER_ID> and for a role it is similarly <#&ROLE_ID>.
In order to mention a user, you must have their User ID and use the following format:
<#USERID> or <#!USERID>. For roles do <#&ROLEID> instead.
Make changes to your message to accommodate it:
message.channel.send(`<#&${ROLEID}> <#${message.author}> is online and waiting for you to join!`);
I guess you are using discord.js v12
If you want the easiest way to mention user you can use
message.channel.send(`#ne1, ${message.author} is online and waiting for you to join!`);
Also I'd use ID of role instead of just #role
You can get the ID by using #role and then just using the thing discord outputs
Usually something like <#&randomnumbers>

How to make a bot send DMs to a specific person?

I'm trying to make a VA training section for my bot, it's supposed to send me the training type they've requested. But I've hit a wall and have no idea where to go from here.
I've looked online for a solution but haven't found any that work for me
if (cmd === `${prefix}request`) {
let args = messageArray.slice(1);
let sUser = user.get('My_ID_Goes_Here');
message.sUser.send(args)
}
It is supposed to send the message argument to me, but it give me
Reference Error: user is not defined
It looks like you're trying to send a DM to yourself using the bot. In this case, the Client can do exactly that.
The Client has a property named users. This property contains all the User objects that your bot has cached (a.k.a., has interacted with.) The users property is a collection containing User objects, mapped by their IDs.
If you want to get your User, simply get the User from the collection that has your ID. Once you have your User object, you can send a DM to yourself using the send method.
// assuming "client" is your bot client
var me = client.users.get(MY_ID_HERE);
me.send("args");
Therefore, your code should be:
if(cmd === `${prefix}request`) {
let args = messageArray.slice(1);
let sUser = client.users.get('Your_ID_goes_here');
sUser.send(args)
}
You can also modify this to send direct messages to anyone, as long as you use their ID instead of yours.
if (message.content.startsWith(prefix + "training-P1")) {
let trainingstudent = message.mentions.users.first();
let mentuor = message.mentions.users.second();
mentour.send(trainingstudent "has requested P1 training");
}
That should work.

Discord command doesn't work if user has changed their nickname

My if statement won't work if the user has changed their nickname in the guild.
Does anyone know how can I get around this?
if (message.content.includes(message.mentions.users.first())) {
let user = message.mentions.users.first();
if (results.afk === 1) {
message.channel.send(`${user} is AFK - ${results.reason} (${moment(results.afktime).fromNow()})`);
}
}
results.afk is from an mySQL key object. The above works if the user has not changed his nickname in discord.
I created a temp/test function:
console.log(message.mentions.users)
if (message.content.includes(message.mentions.users.first())){
console.log("Has mention")
}
If I mention a user in discord that has not changed his username, I get the collection data from console.log(message.mentions.users) and "Has mention".
If I mention a user in discord that has changed his username I only get the collection data from console.log(message.mentions.users).
The issue lies with (message.content.includes(message.mentions.users.first())). That is not detecting a mention in the message if the user changes his nickname. I need a way to pass the if function if there is a user mention (not #everyone, #here #channelname).
if (message.isMentioned(message.mentions.users.first())) solved it for me.

How to make a discord js bot send direct/private message not to author?

I am using node.js for discord.
After I make a command, I want my bot to send a direct/private message to a specific person, not the author who makes the command (me).
Right now I have the person's <#000000000000000000> (I think this is called an ID), which is in String format.
For instance, this code client.sendMessage(message.author, "Hello!"); sends the author the message Hello. But I want one like client.sendMessage(message.user("<#000000000000000000>"), "Hello!");
Does a function like that exist?
For background information, I'm making a werewolf game bot where players are randomly assigned a role, and after I command w!play I want the players to receive their roles in the DM.
Yes just get the user object and send to that. You will need their id, so parse out the id part of the string "<#0000>". Also, sendMessage is deprecated. Use channel.send(). In the case of a user:
let str = "<#123456789>"; //Just assuming some random tag.
//removing any sign of < # ! >...
//the exclamation symbol comes if the user has a nickname on the server.
let id = str.replace(/[<#!>]/g, '');
client.fetchUser(id)
.then(user => {user.send("Hello I dmed you!")})
I would not write it that way unless you have a reason for doing so specifically.
I have used webhooks with git for discord, used hashtags to communicate on a private channel, (and create dm channels) thus I can add in rules for deletion/exclusions (for admins or otherwise)
(This wouldn't be applicable to Facebook if you need Facebook integration)

Categories

Resources