Reference channels

Version 2 functionality

Operations in this document use message draft version 2 unless otherwise specified.

Channel referencing lets users mention channels in messages by typing # followed by at least three letters. Matching channel names appear as suggestions.

Generic referencing

Channel references, user mentions, and links are MessageElement instances with different mentionType values.

Suggestions include all channels in the app keyset (up to 100), regardless of user membership. Configure up to 100 channel references per message (default: 10) and display them as links.

Implementation is similar to user mentions and links.

Requires App Context

Enable App Context for your keyset in the Admin Portal.

Interactive demo​

Sample React app demonstrating channel references and user mentions.

Want to implement something similar?

Test it out​

Type in #EME in the input field and select one of the suggested channels to reference.

Add channel references​

Add channel references with # followed by at least three letters of the channel name (e.g., #Sup).

icon

Under the hood

Method signature​

You can add a channel reference by calling the addMention() method with the mentionType of channelReference.

Refer to the addMention() method for details.

Sample code​

Create the Hello Alex! I have sent you this link on the #offtopic channel. message where #offtopic is a channel reference.

1// Create a message draft
2messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })
3
4// Add initial text
5messageDraft.update("Hello Alex! I have sent you this link on the #offtopic channel.")
6
7// Add a user mention to the string "Alex"
8messageDraft.addMention(45, 9, "channelReference", "group.offtopic")

Remove channel references​

Remove a channel reference from a draft message with removeMention().

Method signature​

You can remove channel references from a draft message by calling the removeMention() method at the exact offset where the channel reference starts.

Refer to the removeMention() method for details.

Offset value

Provide the exact position of the first character; otherwise the element is not removed.

Sample code​

Remove the channel reference from the Hello Alex! I have sent you this link on the #offtopic channel. message where #offtopic is a channel reference.

1// assume the message reads
2// Hello Alex! I have sent you this link on the #offtopic channel.`
3
4// remove the channel reference
5messageDraft?.removeMention(45)

Get channel suggestions​

The message elements listener returns matching channels from your keyset for the 3-letter string typed after #.

icon

Single listener


Typing #Sup returns channels like Support or Support-Agents. Default: 10 suggestions (max: 100).

Method signature​

You must add a message elements listener to receive channel suggestions.

Refer to the addChangeListener() method for details.

Sample code​

Create a message draft and add a change listener to listen for channel references.

1// Create a message draft
2messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })
3// Add the listener
4const listener = async function(state) {
5 elements.push(state.messageElements);
6 if (elements.length === 3) {
7 resolve();
8 return;
9 }
10 let mentions = await state.suggestedMentions;
11 messageDraft.insertSuggestedMention(mentions[0], mentions[0].replaceWith);
12};
13messageDraft.addChangeListener(listener)

Get referenced channels​

Return all channel names referenced in a message with getMessageElements().

Method signature​

This method has the following signature:

1message.getMessageElements()

Sample code​

Check if the message with the 16200000000000000 timetoken contains any channel references.

1// reference the "incident-management" channel
2const channel = await chat.getChannel("incident-management")
3// get the timetoken of the last message on the channel
4const messageTimetoken = (await channel.getHistory({count: 1})).messages[0].timetoken
5// return the message object
6const message = await channel.getMessage("16200000000000001")
7// Retrieve the message elements
8let messageElements = message.getMessageElements()

Get referenced channels (deprecated)​

Return all channel names referenced in a message with the referencedChannels getter.

Method signature​

This method has the following signature:

1message.referencedChannels: Channel[]
Properties​
PropertyDescription
referencedChannels
Type: Channel[]
Returned array of Channel objects.

Sample code​

Check if the last message on the support channel contains any channel references.

1// reference the "support" channel
2const channel = await chat.getChannel("support")
3// get the last message on the channel
4const message = (await channel.getHistory({count: 1})).messages[0]
5// check if it contains any channel references
6message.referencedChannels

Track channel references​

In message draft v2, use the Message draft state listener to track channel references.

Get channel suggestions​

Get matching channel suggestions with getChannelSuggestions().

Typing #Sup returns channels like Support or Support-Agents. Default: 10 suggestions (max: 100).

Method signature​

This method takes the following signature:

1chat.getChannelSuggestions(
2 text: string,
3 {
4 limit: number
5 }
6): Promise<Channel[]>

Input​

* required
ParameterDescription
text *
Type: string
Default:
n/a
At least a 3-letter string typed in after # with the channel name you want to reference.
limit *
Type: number
Default:
10
Maximum number of returned channel names that match the typed 3-letter suggestion. The default value is set to 10, and the maximum is 100.

Output​

TypeDescription
Promise<Channel[]>Returned array of Channel objects.

Sample code​

Return five channels that have names starting with Sup.

1chat.getChannelSuggestions(
2 "Sup",
3 { limit: 5 }
4)

Add referenced channel​

Version 1 functionality

Available in message draft version 1 only. See Message Draft for version differences.

Map a # character to a specific channel with addReferencedChannel(). Without this mapping, # displays as plain text.

Method signature​

This method has the following signature:

1messageDraft.addReferencedChannel(
2 channel: Channel,
3 channelNameOccurrenceIndex: number
4): void

Input​

* required
ParameterDescription
channel *
Type: Channel
Default:
n/a
Channel object that you want to map to a given occurrence of # in the message.
channelNameOccurrenceIndex *
Type: number
Default:
n/a
Specific occurrence of # in the message (like 3) that you want to map to a given channel.

Output​

TypeDescription
voidMethod returns no output data.

Sample code​

Map #Support to the third # in the message.

1const response = await messageDraft.onChange("Contact #Sup")
2// let's say it returns { suggestedChannels: [channel Support, someOtherChannel...], channelNameOccurrenceIndex: 0 }
3messageDraft.addReferencedChannel(response.suggestedChannels[0], response.channelNameOccurrenceIndex)

Remove referenced channel​

Version 1 functionality

Available in message draft version 1 only. See Message Draft for version differences.

Remove the mapping between #Some-channel and a channel with removeReferencedChannel(). Editing the reference text also removes the mapping automatically.

Method signature​

This method has the following signature:

1messageDraft.removeReferencedChannel(
2 channelNameOccurrenceIndex: number
3): void

Input​

* required
ParameterDescription
channelNameOccurrenceIndex *
Type: number
Default:
n/a
Specific occurrence of # in the message (like 3) that you want to unmap from a given channel.

Output​

TypeDescription
voidMethod returns no output data.

Sample code​

Remove #Support from the third # in the message.

1messageDraft.removeReferencedChannel(3)

Send message with channel references​

Publish the message with all channel references using send().

icon

Under the hood

Method signature​

Head over to the Drafts documentation for details on the method signature, input, and output parameters.

Sample code​

Send the previously drafted message in which you reference two channels #Support and #Support-Agents.

1// Create a message draft
2messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })
3
4// Add the text
5messageDraft.update("Hello Alex! I have sent you this link on the #Support and #Support-Agents channels.")
6
7// Add a first URL mention
8messageDraft.addMention(44, 8, "channelReference", "group.support")
9
10// Add a second URL mention
11messageDraft.addMention(56, 15, "channelReference", "group.support-agents")
12
13messageDraft.send()

Get referenced channels​

Return all channel names referenced in a message with the referencedChannels getter.

Method signature​

This method has the following signature:

1message.referencedChannels: Channel[]

Properties​

PropertyDescription
referencedChannels
Type: Channel[]
Returned array of Channel objects.

Sample code​

Check if the last message on the support channel contains any channel references.

1// reference the "support" channel
2const channel = await chat.getChannel("support")
3// get the last message on the channel
4const message = (await channel.getHistory({count: 1})).messages[0]
5// check if it contains any channel references
6message.referencedChannels

Render referenced channels (like #Support) as clickable links with getMessageElements(). Create custom functions to customize rendering.

This is the same method that lets you render plain or text links and show mentions as links.

Method signature​

Head over to the Links documentation for details on the method signature, input, and output parameters.

Sample code​

Show all linked referenced channels in a message as clickable links.

1message.getMessageElements()

Other examples​

Check how you can customize the default behavior of the Chat SDK methods and render the referenced channels differently.

Add a link to a PubNub channel under each channel reference.

1const renderMessagePart = (messagePart: MixedTextTypedElement) => {
2 if (messagePart.type === "channelReference") {
3 // assuming messagePart.content.id is the channel ID
4 const channelUrl = `https://pubnub.com/channels/${messagePart.content.id}`;
5 return (
6 <span>
7 <a href={channelUrl}>{messagePart.content.name}</a>
8 {" "}
9 {/* add a space after channel reference */}
10 </span>
11 );
12 }
13 return "";
14}

Modify display color​

Change the display color of the referenced channels from the default blue to green.

1const renderMessagePart = (messagePart: MixedTextTypedElement) => {
2 if (messagePart.type === "channelReference") {
3 const linkStyle = {
4 color: "green", // set the color to green
5 // add any other desired styles here, e.g., textDecoration: "underline"
6 };
7
8 return (
9 <a href={`https://pubnub.com/${messagePart.content.id}`} style={linkStyle}>
10 {messagePart.content.name}
11 </a>
12 );
13 }
14
15 return "";
show all 16 lines

Show referenced channel preview​

Get a list of message draft elements (text, referenced channels, user mentions, URLs) with getMessagePreview(). Format each element type separately, such as rendering channel references as links.

Method signature​

Head over to the Links documentation for details on the method signature, input, and output parameters.

Sample code​

Show a preview of the linked referenced channel.

1messageDraft.getMessagePreview()

Was this page useful?

Last updated on