Add member nickname
In this section, the main goal is to include the member's nickname in your Bot's response. But first, you'll change the command your Bot looks for.
1. Update the command
-
Open the
src/example.tsfile. -
Locate the line that defines the prefix.
-
Change it from
/echoto/announceShow code
const prefix: string = "/announce "; -
Build and run your Bot to verify that it now responds to
/announce.
2. Add nickname
-
Import
UserGuidfrom"@rootsdk/server-bot". -
In the
onMessagefunction, add a line of code that retrieves theuserIdproperty of theevtobject. TheuserIdis of typeUserGuidso you'll need to add it to your imports.Show code
const userId: UserGuid = evt.userId; -
Modify the code to include the
userIdin the response message. You can use string concatenation on theUserGuidobject.Show code
const response: string = userId + " said " + incomingText;
const createMessageRequest: ChannelMessageCreateRequest = { channelId: evt.channelId, content: response }; -
Run the Bot to test your work.
-
Notice that the
userIdisn't useful to community members. The Root API lets you exchange theuserIdfor aCommunityMemberobject that contains the member'snickname. This will be much more useful for members to see than theuserId. Complete the implementation of the following function to get thenickname.// add CommunityMember and CommunityMemberGetRequest to your imports
async function getMemberNickname(userId: UserGuid): Promise<string> {
// TODO: Create a CommunityMemberGetRequest object containing the userId
// TODO: Call the async method rootServer.community.communityMember.get() to retrieve a CommunityMember object
// TODO: Extract and return the nickname property.
}Show code
async function getMemberNickname(userId: UserGuid): Promise<string> {
const request: CommunityMemberGetRequest = { userId: userId };
const member: CommunityMember = await rootServer.community.communityMembers.get(request);
return member.nickname;
} -
Modify your response to include the
nicknameinstead of theuserId.Show code
const userId: UserGuid = evt.userId;
const nickname: string = await getMemberNickname(userId);
const response: string = nickname + " said " + incomingText;
const createMessageRequest: ChannelMessageCreateRequest = { channelId: evt.channelId, content: response }; -
Run the Bot to test your work. You should see a human-readable name for the member.
3. Format the nickname as a mention
A mention is a Root-specific link that lets other members easily interact with that member. The format is root://user/userId.
-
Use the following code to format the member's nickname as a mention:
const mention = "[@" + nickname + "](root://user/" + evt.userId + ")"; -
Replace the
nicknamewith thementionin your response. -
Run the Bot to test your work. Select the mention in the Root native client to see the functionality it enables.