I have searched arround for a while for this but can't seem to find an answer. Does anyone know how to get the user who ran the interactions nickname, username, and user id? Thanks.
You can use the user/member properties of Interaction.
client.on('interactionCreate', async interaction => {
// Making sure the interaction is a command
if (!interaction.isCommand()) return false;
await interaction.reply(`Hello, ${interaction.user.tag}!`)
})
I'd suggest fetching the user, and then getting all the information you want.
const interactionUser = await interaction.guild.members.fetch(interaction.user.id)
const nickName = interactionUser.nickname
const userName = interactionUser.user.username
const userId = interactionUser.id
Not fetching the user explicitly may lead to missing information.
It's not necessary to make another fetch-request in order to get the nickname of the user who ran the interaction. The interaction sends a GuildMember instance which contains all the data of the user who sent the interaction and which can be accessed through interaction.member. So in your code example you could do so:
client.on('interactionCreate', async interaction => {
// Making sure the interaction is a command
if (!interaction.isCommand()) return false;
await interaction.reply(`Hello, ${interaction.member.displayName}!`)
})
Related
I want to make a functionality where I persist the user while the window is open or to be precise in the current session. To make this I've researched the Firebase documentation, and I found out about this: Authentication State Persistence.
After researching it, I decided to put it inside my app, here's how my code looks like:
function logIn(email, password) {
setPersistence(auth, browserLocalPersistence)
.then(() => {
return signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
console.log(error);
});
}
This function is inside my UserAuthContext file where I keep all functionalities regarding user. Now some may say that there is nothing wrong with the way this function is made, but whenever email and password are empty the user can still Login without being stopped by Firebase errors like it happens without setPersistence function.
Does anyone know why does my Login go through even though email and password are empty?
I can see the names, ids and user numbers of the servers where my bot is located, but how can I get the list of users (nicknames)?
You can make use of guild.members.fetch() in order to get all members and then use the nickname property to receive their nicknames. Finally I removed all bots with a simple filter.
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
Working example as a command:
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.content === "!list") {
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
}
});
client.login("your-token");
Thanks to #MrMythical who suggested using displayName only. That property automatically returns the normal username when no nickname has been set for a user.
Users do not have nicknames, only guild members, if you are trying to fetch a list of server member nicknames.
You can use the code snippet from below:
const map = message.guild.members.cache.filter(c=> !c.member.user.bot).map(c=>c.displayName).join('\n');
console.log(map)
The
message.guild.members.cache.filter(c=> !c.member.user.bot)
Filters bots from the list, the
.map(c=>c.displayName).join('\n');
maps the data and only the user nicknames and joins them by paragraph breaks.
If there are any issues, please comment!
can someone please help me to retrieve username from user ID and send a message to the chat with that ID?
if (message.content.startsWith(prefix)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(prefix.length)
.split(/\s+/);
if (CMD_NAME === "getid") {
const getid1 = new MessageEmbed()
.setDescription("❗️ | Please tag the member to retrieve the ID!")
.setColor(10181046);
if (args.length === 0) return message.reply(getid1);
const username = client.guilds.cache.get('<GUILD ID>');
const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id
message.channel.send(`${username} id is ${userid}`);
}
}
});
When I type the command "d!getid #Username", it shows me this error:
C:\Users\USER\Desktop\DiscordBotas\index.js:152 const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id TypeError: Cannot read property 'id' of undefined at Client. (C:\Users\USER\Desktop\DiscordBotas\index.js:152:90)
You are creating a lambda of a variable that you just defined above the actual lambda, this could probably mess with your code.
The const username = client.guilds.cache.get('<GUILD ID>'); is wrong.
The fetching of the userId should probably work if you fix the line above it.
You are trying to get the user the wrong way. Firstly, why are you trying to match a user's tag with a guild? Maybe you think guild.cache has users? Well actually, this is client.guilds.cache, which only has guilds in it, and it returns a guild, not a user. Secondly, to get a user, you can try this method:
const user = client.users.cache.find(u => u.tag === 'SomeUser#0000')
console.log(user.id);
Below is code to get user by ID, but it probably won’t help with this, considering you would already have access to the ID
const user = client.users.cache.get("<UserID>");
console.log(user);
Also, you should add code to see if user isn’t found (client can’t find user with the condition). Here is some code to check that:
//... the find user code I put
if(!user) return message.reply('User could not be found');
message.channel.send(user.id);
So I have been developing a bot recently and I have implemented the slash commands into said bot. I have come across the need for a type 5 command "response" but I can't seem to find good documentation on the slash commands. I can't seem to make it "stop thinking". Any help would be appreciated!
EDIT: I found that you need to edit the interaction response (https://discord.com/developers/docs/interactions/slash-commands#interaction-response) but I'm not using webhooks I'm using a bot and I don't want to have to get another npm library if I don't have to. So how do I edit my interaction?
I have solved this, if you want to know how I did here is some code.
if your interaction responder looks like this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction)//i am using a command handler to put
//the actual event into a different file
}
and your "interaction message sender" looks like this: (notice it's type 5)
module.exports.whatever = (interaction) => {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 5
}
})
};
then it will say "{botname} is thinking" with a little ellipses, and after 15 minutes if nothing happens it will fail the interaction. If you want to make it "stop thinking" you have to edit the message. I am using the axios npm library (https://www.npmjs.com/package/axios) and if you just put in this code it should edit your interaction message. this goes at the top of your file with your requirements:
const axios = require('axios')
const appId = ''//bot id goes here
and somewhere near the bottom of your file maybe put in this:
const editInteraction = async (client, interaction, response) => {
const data = typeof response === 'object' ? { embeds: [ response ] } : { content: response };
const channel = await client.channels.resolve(interaction.channel_id);
return axios
.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, data)
.then((answer) => {
return channel.messages.fetch(answer.data.id)
})
};
then you will have the basic code structure to edit the message, now you just need to edit the message. to do that, in your code, do this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction).then(m => {
editInteraction(client, interaction, '>:(')//this will actually edit the message so
//instead of " >:( " put in what you want to edit you message to be
})
}
then you can run that command and it will say the bot is thinking then after whatever event you want to run it will edit it to say whatever!
I am creating an alexa app and for that i have permission for the user's location and customer's firstname. My first question is if customer's first name is what is user's first name or it is something different. But if it is asking for the user's first name then to get that. For location info, we use ConsentToken, so is there any way to get the user name out of it?
I can ask for the user name and store it and then can greet the user. But i have to ask everytime user launches the app. I am using php.
First, the user has to link his account with your skill and accept the permission
(you need to set it in your skill configuration)
once the user is loged in, You will just be able to use a access/refresh token to get the user name from Alexa output
Check this, could be clearest: https://developer.amazon.com/fr/docs/custom-skills/request-customer-contact-information-for-use-in-your-skill.html
In addition to Neryuk's answer pointing correctly the documentation, I give some code sample in NodeJS.
Assuming you already gave all the permissions needed from Alexa Skill Developer Portal, you can ask for user information within your intent handler in this way:
const PERMISSIONS = ['alexa::profile:name:read', 'alexa::profile:email:read', 'alexa::profile:mobile_number:read'];
const MyIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
// checks request type
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& request.intent.name === 'MyIntent');
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
const requestAttributes = handlerInput.attributesManager.getRequestAttributes();
const consentToken = handlerInput.requestEnvelope.context.System.apiAccessToken;
if (!consentToken) {
return responseBuilder
.speak('Missing permissions')
.withAskForPermissionsConsentCard(PERMISSIONS)
.getResponse();
}
const client = serviceClientFactory.getUpsServiceClient();
const userName = await client.getProfileName();
const userEmail = await client.getProfileEmail();
const userMobileNumber = await client.getProfileMobileNumber();
console.log('Name successfully retrieved '+ userName);
console.log('Email successfully retrieved '+ userEmail);
console.log('PhoneNumber successfully retrieved '+ JSON.stringify(userMobileNumber));
const speakOutput = 'The username is '+userName;
return handlerInput.responseBuilder
.speak(speakOutput)
.withSimpleCard('MyFavSkill')
.getResponse();
},
};
Note that you must declare your handlerInput code as async because you are invoking an async request you must wait within your method.
Code is missing the "try-catch" block to simplify its reading, but you should manage unexpected errors.
Hope this may help.