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);
Related
I want to make my bot autorole if username of anyone member contains a specific tag and the code i made isn't working, bot starts fine but didn't assign role if user have tag in username than also so i thought to use stackoverflow to get some help
Here is the code:
client.on("userUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).addRole(role)
} if (!newUser.username.includes(tag) && client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).removeRole(role)
}
}
})
You would require to define USER_UPDATE, GUILD_MEMBER_UPDATE, and
PRESENCE_UPDATE intents if you are on discord.js version 13 and further enable the members and presence intent too, they can be located in the Discord Developer Portal further I would like to suggest using the Client#guildMemberUpdate listener instead since your code has nothing to do with presence you would not need the "extra" intents.
Additional Information
Directed by this comment It has come to my notice that you are using version 12 of discord.js so you would want to make adequate changes to your code for that ( your code as it currently is, is clearly written for discord.js v11) the following changes would be made in your code:
client.on("guildMemberUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.add(role)
} if (!newUser.username.includes(tag) && client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.remove(role)
}
}
})
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!
Aim: To ban every time a user is caught on the audit log attempting to create a channel
Code:
// Channel Create
client.on("channelCreate", async (channel) => {
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
Result:
It bans the user successfully but still throws an error.
Error:
TypeError: Cannot read property 'id' of undefined
Code: Error Specified | Referring to channel.guild.id
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
I'm guessing the reason for this is that the parameter ,channel, type is DMChannel and not GuildChannel
Is there any way to fix this or be able to change the parameter type to GuildChannel??? I've checked the Docs and I can't seem to find anything that indicates this is possible. Any help is appreciated ;)
Your assumption of why this error is occurring is correct. The channelCreate event does indeed handle the creation of both GuildChannel and DMChannel, and your code sends the guild owner a DM after banning the user. That's why the ban works but you get an error afterwards; because the DM creates a DMChannel with the owner, triggering the event handler again but with channel.guild being undefined since DMs do not have guilds.
So let me state the problem again. You are getting the error Cannot read property 'id' of undefined which you've figured out means channel.guild is undefined. You don't want the error to occur, so you don't want channel.guild to be undefined. But in your question you're asking:
Is there any way to fix this or be able to change the parameter type to GuildChannel???
That's not the approach you want to take. Doing that would mean users would get banned for DMing your bot because it would trigger your channelCreate event handler; plus, the bot would try to ban the guild owner since it sends the owner a DM. And you only want to ban users for creating channels in the guild.
When we put the problem that way, the solution is simple: check if the channel is a DMChannel, and discontinue if it is. Only allow users to get banned for creating a GuildChannel. So how do you do that? Well, as you've seen from your error already, channel.guild is undefined when the channel is a DMChannel. So simply check for this condition, and return if it is the case. Here's an example:
// Channel Create
client.on("channelCreate", async (channel) => {
if (!channel.guild) return; //<- added this
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
This prevents the error from occurring, prevents users from getting banned for DMing the bot, and prevents the guild owner from being infinitely DM'd (if the DMChannel were to be somehow converted into a GuildChannel, the bot would DM the owner after banning the user that created the channel, which would trigger the event again and ban the user again, and DM the owner again, in an infinite loop).
so I am trying to make a ROSTER command. The command is $roster add/remove #user RANK. This command basically should edit a previous bot's message (roster) and add a user to the roster to the RANK in the command... This is my code so far, but I haven't managed to make the roster message and the editing part of it and the RANK system. If someone could help that would be very amazing!
//ROOSTER COMMAND
client.on('message', async message => {
if (message.content.startsWith(prefix + "roster")) {
if (!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
const args = message.content.slice(prefix.length + 7).split(/ +/)
let uReply = args[0];
const user = message.mentions.members.first()
if(!uReply) message.channel.send("Please use `add` or `remove`.")
if(uReply === 'add') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are adding **${user.displayName}** from the roster.`)
} else if(uReply === 'remove') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are removing **${user.displayName}** from the roster.`)
}
}})
Sounds like the .edit() method is what you want.
Example from the docs:
// Update the content of a message
message.edit('This is my new content!')
.then(msg => console.log(`Updated the content of a message to ${msg.content}`))
.catch(console.error);
To edit your bots previous message, you need to have a reference of the message you want to edit. The returned reference is a promise so do not forget to use await keyword. you can then use .edit() function on the reference to update you msg.
const msgRef = await msg.channel.send("Hello");
msgRef.edit("Bye");
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.