How do I get someones username AND tag? (Discord.js) - discord.js

So, I'm trying to make a serverInfo command as you can see below
let embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setTitle("Server Information")
.setDescription(`Server Name: **${message.guild.name}** \n ────────────────── \n Member Count: **${message.guild.memberCount}** \n ────────────────── \n Server ID: **${message.guild.id}** \n ──────────────────`)
.setTimestamp()
.setFooter(`Ran by: ${message.author.username.id}`)
message.channel.send(embed)
For my result, I get "undefiened"
anyone know the solution to this? (.setFooter)

message.author.tag for get the user with tag (JohnDoe#0000)
message.author.user for get the user
message.author.user.username for get the Username
message.author.user.id for get the ID
Simple (:

To get the complete tag of a user, you can just use .tag after message.author.
In your code, you're trying to get the username but you put .id after it so this is why you get "undefined".
The ID isn't the numbers with the hashtag, it's the user ID and the tag is the username plus the numbers with the hashtag.
⠀⠀⠀↱ John Doe#3040 ↰
Username⠀⠀⠀⠀ ⠀⠀Numbers
↳⠀⠀⠀⠀⠀⠀⠀⠀Tag⠀⠀⠀⠀⠀⠀⠀ ↲

So, to get the username and tag, just do this:
//say it’s called msg instead of message
var tag = msg.author.tag;
var username = msg.author.id;
//tag would return the user's tag, and as someone else stated in a comment in a previous answer, author returns a user, which itself doesn't have a user property because it is the user object
Also just a quick tip: since it’s server info command, you might want to put some information about the user that’s exclusive to that guild (nickname, roles, permissions), and for that, you can use msg.member which returns a GuildMember, which has a user property, and many more, like member.displayName and member.roles

Related

Alternative Ways to Define Users in Discord.JS

So to define users for things like displaying avatars, etc. i've been using this;
var user = message.mentions.users.first() || message.author;
But i've been trying to figure out how people have been able to define users without mentions. Example - my command requires me to tag someone whereas Dyno can do it with partial names. Any tips would be great, thanks!
An easy way to do so would probably be using the .find() function, where you can search for a certain object based on a method.
For example, if we were to have an args variable in our callback (Very easy to do so using a proper command handler - I'd suggest looking for tutorials if you aren't familiar with command handlers), and we were to ask a user to pass in a member's name, we could very easily get the user object using:
const user = message.guild.users.cache.find(user => user.username === args[0]);
// Keep in mind, 'user' is just a variable I've defined. It could also be 'monke => monke.username' if you wish.
Or, if we were to ask for their ID, we could use the .get() function to get the user object by ID:
const user = message.guild.users.cache.get(args[0]);
Do keep in mind it's not the greatest to have these kinds of object getting functions, as there are always multiple conflicts that could occur whilst getting the object, such as if there are multiple users with the same name/tag. I'd highly recommend sticking to your mention-based user objects, as it's the most accurate and non-conflicting method.
Every guild has a list of members which you can search through by enabling the Server Members Intent for your bot via the Discord Developer Portal. Once you have done that, you can fetch a collection of all members of a guild by doing
guild.members.cache;
You can then search this collection to find a member based on a search query using .includes(), .filter() or something similar. For example:
let query = "something";
let list = guild.members.cache.filter(member => member.user.username.includes(query));
console.log(Object.entries(list));
// expected output: list of all server members who's usernames contain "something"
You could also use the .find() method (since a collection is a map) to return a member with an exact username:
let member = guild.members.cache.find(member => member.user.username === query);
console.log(member.tag);
// expected output: tag of the user who's username is "something"
This is as simple as that:
var user = message.guild.members.cache.find(u => u.user.username.toUpperCase() === args.join(" ") || u.user.username.toLowerCase() === args.join(" ") || u.user.username === args.join(" "))
This will find the user on the current guild but you can also search your bot for this user by doing:
var user = client.users.cache.find(u => u.username.toUpperCase() === args.join(" ") || u.username.toLowerCase() === args.join(" ") || u.username === args.join(" "))
I have to assume that you already defined args and client. The example above will find users just by typing their name. toUpperCase means if you type the username in uppercase letters it will find the users anyways. toLowerCase means if you type the username in lowercase letters it will find the user as well. And you could also just type the username as it is. || means or so you can decide how you write the username, it will be found anyways.

?members command for my discord bot - discord.js

So I've been trying to create a ?members command which lists all the users with a role.
So far I've got this:
if (message.content.startsWith("?members")) {
let roleName = message.content.split(" ").slice(1).join(" ");
let membersWithRole = message.guild.members.filter(member => {
return member.roles.find("name", roleName);
}).map(member => {
return member.user.username;
})
const embed = new Discord.RichEmbed({
"title": `Members in ${roleName}`,
"description": membersWithRole.join("\n"),
"color": 0xFFFF
});
return message.channel.send(embed);
}
So, it works if you type the exact name of the role, but not when you ping it or type the first word. I've been trying for hours to figure out how to do it, and I figured I should ask for help.
Thanks in advance!
Pings get translated into a code as they come through, there is a lot of information on how to parse them in the official guide After it's parsed into a role id you can just use members.roles.get() because that is what they are indexed by.
As for finding a partial name, for that you are going to have to run a function on your find and use String.includes.
return member.roles.find(role => role.name.includes(roleName));
This will also work for find the whole name of course, so it can replace your existing line.
However, this may result in more than one role. This is also true for searching by the entire role name, however, as there are no restrictions on duplicate named roles. For this you may want to invert you design and search through message.guild.roles first for any matching roles, then search for members with the roles found.

user merge fields doesn't replace by user record ID

I am trying to send email through email template to user but It is always replacing the user merge fields by org admin's user name instead of targetobjectID user.
Org admin : luke wright
Email template Body :
Dear {!User.Name} ,
Hearty Congratulations on this beautiful occasion. May your marriage bring great joy, love and passion in your life. I wish to God to bless you with a wonderful marriage and a happy life ahead.
Thanks and Regards.
{!Organization.Name}
OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress limit 1];
List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateID('00X0S000000iBYB'); // Template Id
mail.setSaveAsActivity(false);
mail.setTargetObjectId('0050S0000023KS9'); // UserId Name: John Doe
mail.setOrgWideEmailAddressId(owa.id);
allmsg.add(mail);
Messaging.sendEmail(allmsg,false);
Issue: Dear {!User.Name} should be replace by john doe while it is replacing by luke wright and email goes to correct user i.e. john doe
P.S. User's merge fields is not replacing by that record ID
User error? ;)
User is for current running user. Looks like you want Receiving_User.
If you have Communities enabled you probably have this built-in email template. And even if not - check the top of the screenshot.
And if your email template is Visualforce rather than normal - probably you should be using {!relatedTo}.

How to get or create user profile in GAE?

I have a Profile model:
class Profile(db.Model):
user = db.UserProperty(auto_current_user=True)
bio = db.StringProperty()
I'd like to display the user's existing bio in this view. If the user has no profile yet, I'd like to create it. Here's what I have so far, which doesn't work yet:
class BioPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
profile = Profile.get_or_insert(user=user) #This line is wrong
profile.bio = "No bio entered yet."
profile.save()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, ' + user.nickname() + '<br/>Bio: ' + profile.bio)
else:
self.redirect(users.create_login_url(self.request.uri))
How do I fix the incorrect line above? I know that get_or_insert() should take a key name, but I can't figure out what that would be.
(Should the user field in Profile even be a db.UserProperty?)
You have to pass the key_name to get_or_insert(), in this case, like so:
profile = Profile.get_or_insert(key_name=user.email())
Note that since the user property is auto-populated because of the auto_current_user=True you don't need to pass it to the get_or_insert() call. In your case you don't need to pass anything but the key name.
You probably don't want to use db.UserProperty, for reasons explained here. In summary, if a user changes his/her email address, your (old) stored 'User' will not compare equal to the currently-logged-in (new) 'User'.
Instead, store the user.user_id() as either a StringProperty on your Profile model (as shown on the page I referenced above), or as the key (key_name) of your Profile model. An example of the latter is here.

Converting a User.user_id() to a User.email()

Is there a way to derive a user's email given his user_id?
You can build a relationship between the email and the user_id,and then retrieve it as needed. If the user is logged in you can easily access both properties separately.
http://code.google.com/intl/en/appengine/docs/python/users/userclass.html
However the user_id is not a hashed version of the email that can be reconstructed using some kind of algorithm.
It seems like it's not possible to derive an email from a user id. If you want to go from user_id to email, you must store both when the user is logged in, and then, when the user is not logged in, do a lookup to convert. Eg.
class Email(db.model):
'''keyed by user_id'''
email=db.EmailProperty()
def save_user():
u=users.get_current_user()
k=db.Key.from_path('Email',u.user_id())
e=Email.get(k)
if not e:
Email(key=k, email=u.email()).put()
def get_email_from_user_id(id):
'''No way to derive email without a lookup.'''
k=db.Key.from_path('Email',id)
return Email.get(k).email # raises exception if email is not found

Resources