How to issue roles using slash commands? DiscordJS - discord

I want to make the issuance of roles through a slash command. So that you can choose which role to give to the participant. Information from the Internet did not help me.

const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('giverole')
.setDescription('Gives a role to a user.')
.addUserOption(option => option.setName('user').setDescription('The user to give the role to').setRequired(true))
.addRoleOption(option => option.setName('role').setDescription('The role to give to the user').setRequired(true)),
async execute(interaction) {
// Check if user has permission to manage roles
if (!interaction.member.permissions.has('MANAGE_ROLES')) {
return interaction.reply('You do not have permission to manage roles.');
}
// Get the mentioned user and role
const member = interaction.options.getMember('user');
const role = interaction.options.getRole('role');
// Give the mentioned role to the mentioned user
member.roles.add(role)
.then(() => {
interaction.reply(`Successfully gave ${role.name} role to ${member.user.tag}`);
})
.catch(error => {
console.error(error);
interaction.reply('There was an error while giving the role.');
});
},
};

Related

Is there a way to only sign in registered users in Firebase Phone Authentication

I am building a React app with Firebase Back End that requires the user to register and sign in using their phone number. The problem is that currently, even for a user that does not have an account, once they receive the OTP, they are automatically registered. Is there a way to check if the user is not registered and instead ask them to register rather than sign them in?
My sign in function
const handleSubmit = async (event) => {
event.preventDefault();
if(phone != ''){
setExpanded(true);
generateRecaptcha();
let appVerifier = window.recaptureVerifier;
signInWithPhoneNumber(auth, phone, appVerifier)
.then(confirmationResult => {
window.confirmationResult = confirmationResult;
}).catch((err) => {
console.log(err);
});
}
}
OTP verification:
const verifyOTP = (e) => {
let otp = e.target.value;
setOtp(otp);
if(otp.length === 6) {
console.log(otp);
let confirmationResult = window.confirmationResult;
confirmationResult.confirm(otp).then((result) => {
const user = result.user;
if(user != null){
console.log('Loged');
router.push('/home')
}
}).catch((err) => {
console.log(err);
})
}
}
Kindly help.
Thanks.
SignInWithPhoneNumber method will automatically sign up a new user if the user doesn't exist. There is no way to prevent users from signing up,you can check if the returned user is a new user and if it's new, delete and sign out the user manually.
check the isNewUser property after authentication to check if user logged in for the first time or not.you can refer this link
x.confirm(code)
.then((result) => {
// User signed in successfully.
const { isNewUser } = getAdditionalUserInfo(result)
if (isNewUser) {
// New user - sign up
} else {
// Existing user - log in
}
})
However, you can disable new user sign up with email providers by setting the flag disableSignUp.status to true. This will display an error message when new users attempt to sign up.You can refer this github for more information

NextJS-Auth0: How can I assign a role on signup with Auth0?

Using the library nextjs-auth0 (https://github.com/auth0/nextjs-auth0) I've been trying to make use of the handleAuth hook to grab a query arg to specify which role should be assigned to the user on signup.
An example of what I'm trying to do:
//pages/api/auth/[...auth0].js
const getLoginState = (req, loginOptions) => {
const { role } = req.query;
return { role: role };
};
export default handleAuth({
async login(req, res) {
try {
await handleLogin(req, res, { getLoginState } );
} catch (error) {
res.status(error.status || 500).end(error.message);
}
}
});
The documentation for handleAuth makes it seem like it's possible to do this ( https://auth0.github.io/nextjs-auth0/modules/handlers_login.html#getloginstate )
// from the documentation
const getLoginState = (req, loginOptions) => {
return { basket_id: getBasketId(req) };
};
From that doc - it looks like basket_id is the custom property to be saved against the user "before they visit the Identity Provider to login".
This sounds, to me, that basked_id will be saved somewhere against the users metadata once they've logged in. Is the documentation misleading, or am I misunderstanding?
How can I set the role during (or even slightly after) signup?
I managed to achieve what I wanted with the following Auth0 "rule":
function (user, context, callback) {
const count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
if (count > 1) {
return callback(null, user, context);
}
const ManagementClient = require('auth0#2.27.0').ManagementClient;
const management = new ManagementClient({
token: auth0.accessToken,
domain: auth0.domain
});
let roles = [context.request.query.role];
const params = { id : user.user_id};
const data = { "roles" : roles};
management.users.assignRoles(params, data, function (err, user) {
if (err) {
// Handle error.
console.log(err);
}
callback(null, user, context);
});
}
Notice that the role is being read in from context.request.query.role. This pulls the query param role key off the login URL which more-or-less works how I wanted it to.
Then forward the role along from the auth in the backend:
const getLoginState = (req, loginOptions) => {
const { role } = req.query;
loginOptions.authorizationParams.role = role;
return { role: role };
};
export default handleAuth({
async login(req, res) {
try {
await handleLogin(req, res, { getLoginState });
} catch (error) {
res.status(error.status || 500).end(error.message);
}
}
});
Notice the loginOptions.authorizationParams.role = role;
So the login link can be set to: /api/auth/login?role=somerole and the rule will pick up the role and set it in the metadata part of the users info.
However: I wasn't able to get this to actually properly set the role on the user but it's enough for me, as it appears in the session.

How do we make a kick command with userid?

So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
}
}

permissions don't work with my code. Member doesn't exist

so I've been trying to make a bot for Discord, and my kick and ban function work, but the permissions don't work. Tried to repair it somehow, but it got worse and it was going into an infinite loop.
bot.on('message', message => {
if (message.member.hasPermission("ADMINISTRATOR")) {
if (!message.guild) return;
if (message.content.startsWith('+kick')) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
}
}
});
This is my code. I want to make it go to further messages only if you have kick members permission. There are many codes on the internet but they seem to break my code somehow.

How can a Discord bot reply to only certain users?

I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.
I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});
I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".

Resources