Create message drafts
A MessageDraft object is an abstraction for composing a message that has not yet been published. You can use it to:
- Edit text before it is published
- Add channel references, user mentions, links
You can display user mentions, channel references, and links (collectively called "message elements") to the user on the front end of your application by adding a message draft state listener.
- Basics
- Class diagram
- Example
- Internal mention format
Message drafts consist of MessageElement objects, which can be either instances of Text or MentionTarget.
Text are simple strings, while MentionTarget elements are used for user mentions, channel references, and URLs. They contain a text and a reference to the linked element regardless if it's a user, a channel, or a URL.
Each MentionTarget has a MentionType enum property, which defines the type of mention. Available targets include:
MentionTarget.UserMentionTarget.ChannelMentionTarget.Url
Store draft messages locally
Unity Chat SDK does not provide a method for storing the drafted message on the client, so whenever a user drafts a message in a chat app, changes a channel, and goes back to that channel, the drafted message gets lost.
To save drafted messages before they are published on channels, implement your own local storage mechanism suitable for the platform you use.
Consider the message Hey, I sent Alex this link on the #offtopic channel. where:
Alexis a reference to the user with the ID ofalex_dlinkis a URL of thewww.pubnub.comwebsite#offtopicis a reference to the channel with the ID ofgroup.offtopic
The list of MessageElement objects returned by the MessageDraftChangeListener is as follows:
By internally leveraging a Markdown-like syntax, the message draft format integrates links directly into the message text using the pattern [link text](link target) understood by the Unity Chat SDK.
| Mention Type | Example |
|---|---|
| user | [John Doe](pn-user://john_doe) |
| channel | [General Chat](pn-channel://group.chat.123) |
| url | [PubNub](https://www.pubnub.com) |
Custom schemas like pn-user:// and pn-channel:// are used to identify user and channel mentions, while traditional URLs are supported as-is.
Adding message elements
You don't use this Markdown-like syntax when adding message elements. It's only a representation of your message elements under the hood.
For more information, refer to Add message element.
Create a draft message
CreateMessageDraft() creates a message draft (MessageDraft object) that can consist of:
- Plain text
- Mentioned users
- Referenced channels
- Links
Method signature
This method has the following signature:
1public MessageDraft CreateMessageDraft(
2 UserSuggestionSource userSuggestionSource = UserSuggestionSource.GLOBAL,
3 bool isTypingIndicatorTriggered = true,
4 int userLimit = 10,
5 int channelLimit = 10,
6 bool shouldSearchForSuggestions = false
7)
Input
| Parameter | Description |
|---|---|
userSuggestionSourceType: UserSuggestionSource = .GLOBAL or UserSuggestionSource = .CHANNELDefault: UserSuggestionSource = .GLOBAL | This parameter refers to the Mentions feature. Data source from which you want to retrieve users. You can choose either the list of channel members (.CHANNEL) or users on the app's Admin Portal keyset (.GLOBAL). |
isTypingIndicatorTriggeredType: BoolDefault: true | This parameter refers to the Typing Indicator feature. Defines if the typing indicator should be enabled when writing the message. |
userLimitType: IntDefault: 10 | This parameter refers to the Mentions feature. Maximum number of usernames (name field from the User object) you can mention in one message (the default value is 10 and max is 100). |
channelLimitType: IntDefault: 10 | This parameter refers to the References feature. Maximum number of channel names (name field from the Channel object) you can reference in one message (the default value is 10 and max is 100). |
shouldSearchForSuggestionsType: BoolDefault: false | Whether the MessageDraft should automatically search for suggestions whenever the text is changed. When set to true, the OnDraftUpdated event will include suggested mentions for users, channels, and links. |
Output
| Type | Description |
|---|---|
MessageDraft | Instance of MessageDraft, which represents a draft version of a message with the content, all links, referenced channels, mentioned users and their names. |
Sample code
Create a draft message containing just plain text.
1
Add message draft change listener
The OnDraftUpdated event is triggered when there is a change to a message draft. You must handle the event to update to the contents of a message draft, as well as retrieve the current message elements suggestions for user mentions, channel reference, and links. For example, when the message draft contains ... @name ... or ... #chann ....
Enable receiving suggested mentions
You must enable receiving suggested mentions by setting messageDraft.ShouldSearchForSuggestions = true; before introducing your event handler.
Event signature
1public event Action<List<MessageElement>, List<SuggestedMention>> OnDraftUpdated;
Event handler signature
1void EventHandler(List<MessageElement> elements, List<SuggestedMention> mentions)
| Parameter | Description |
|---|---|
elements *Type: MessageElementDefault: n/a | A list of MessageElement objects, representing the current state of the message draft. This could contain a mix of plain text and links, channel references, or user mentions. |
mentions *Type: SuggestedMentionDefault: n/a | A list of SuggestedMention objects. These are potential suggestions for message elements based on the current text in the draft. Suggested mentions are not returned by default. You must enable receiving them by setting messageDraft.ShouldSearchForSuggestions = true; before introducing your event handler. |
SuggestedMention
A SuggestedMention represents a potential mention suggestion received from MessageDraftChangeListener.
Suggested mentions are not returned by default. You must enable receiving them by setting messageDraft.ShouldSearchForSuggestions = true; before introducing your event handler.
| Parameter | Description |
|---|---|
OffsetType: Int | The position from the start of the message draft where the message elements starts. It's counted from the beginning of the message (including spaces), with 0 as the first character. |
ReplaceFromType: String | The original text at the given offset in the message draft text. |
ReplaceToType: String | The suggested replacement for the replaceFrom text. |
TargetType: MentionTarget | The message element type. Available types include:
|
Output
This method doesn't return any data.
Sample code
Add the listener to your message draft.
1
Remove message draft change listener
Remove a previously added OnDraftUpdated event handler. You can only remove an event handler that was added using a dedicated callback.
Sample code
Remove a listener from your message draft.
1
Add message element
AddMention() adds a user mention, channel reference or a link specified by a mention target at a given offset.
Method signature
This method has the following signature:
1messageDraft.AddMention(
2 int offset,
3 int length,
4 MentionTarget target
5)
Input
| Parameter | Description |
|---|---|
offset *Type: intDefault: n/a | Position of a character in a message where the message element you want to insert starts. It's counted from the beginning of the message (including spaces), with 0 as the first character. |
length *Type: intDefault: n/a | Number of characters the message element should occupy in the draft message's text. |
target *Type: MentionTargetDefault: n/a | Mention target type. mentionTarget = new MentionTarget { Type = MentionType, Target = String }; Available mention types include:
|
Output
This method returns no output data.
Sample code
Create the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention, link is a URL, and #offtopic is a channel reference.
1
Remove message element
RemoveMention() removes a user mention, channel reference, or a link at a given offset.
Method signature
This method has the following signature:
1messageDraft.RemoveMention(int offset)
Input
| Parameter | Description |
|---|---|
offset *Type: intDefault: n/a | Position of the first character of the message element you want to remove. |
Offset value
If you don't provide the position of the first character of the message element to remove, it isn't removed.
Output
This method returns no output data.
Sample code
Remove the URL element from the word link in the Hello Alex! I have sent you this link on the #offtopic channel. message.
1
Update message text
Update() lets you replace the text of a draft message with new content.
Removing message elements
As a best effort, the optimal set of insertions and removals that converts the current text to the provided text is calculated to preserve any message elements.
If any message element text is found to be modified in the updated text, the message element is removed.
Method signature
This method has the following signature:
1messageDraft.Update(string text)
Input
| Parameter | Description |
|---|---|
text *Type: stringDefault: n/a | Text of the message that you want to update. |
Output
This method returns no output data.
Sample code
Change the message I sent Alex this picture. to I did not send Alex this picture. where Alex is a user mention.
1
Mention text changes
If you decided to change the name Alex to some other name, the mention would be removed because your updated text's index coincided with an existing mention.
For more manual control over inserting and removing parts of a message, refer to Insert message text and Remove message text.
Insert suggested message element
Inserts a message element returned by the MessageDraftChangeListener into the MessageDraft.
Text must match
The SuggestedMention must be up to date with the message text, that is, SuggestedMention.ReplaceFrom must match the message draft at position SuggestedMention.ReplaceFrom, otherwise an exception is thrown.
Method signature
This method has the following signature:
1messageDraft.InsertSuggestedMention(
2 SuggestedMention mention,
3 string text
4)
Input
| Parameter | Description |
|---|---|
mention *Type: SuggestedMentionDefault: n/a | A user, channel, or URL suggestion obtained from MessageDraftChangeListener. |
text *Type: stringDefault: n/a | The text you want the message element to display. |
Output
This method returns no output data.
Sample code
Register a listener and insert a suggested element.
1
Insert message text
InsertText() lets you insert plain text in the draft message at a given offset from the beginning of the message.
Removing message elements
If the position of the text you want to insert corresponds to an existing message element, this element is removed.
Method signature
This method has the following signature:
1messageDraft.InsertText(
2 int offset,
3 string text
4)
Input
| Parameter | Description |
|---|---|
offset *Type: intDefault: n/a | Position of a character in a message where the text you want to insert starts. It's counted from the beginning of the message (including spaces), with 0 as the first character. |
text *Type: stringDefault: n/a | Text that you want to insert. |
Output
This method returns no output data.
Sample code
In the message Check this support article https://www.support-article.com/., add the word out between the words Check and this.
1
Remove message text
RemoveText() lets you remove plain text from the draft message at a given offset from the beginning of the message.
Removing message elements
If the position of the text you want to remove corresponds to an existing message element, this element is removed.
Method signature
This method has the following signature:
1messageDraft.RemoveText(
2 int offset,
3 int length
4)
Input
| Parameter | Description |
|---|---|
offset *Type: intDefault: n/a | Position of a character in a message where the text you want to insert starts. It's counted from the beginning of the message (including spaces), with 0 as the first character. |
length *Type: intDefault: n/a | How many characters to remove, starting at the given offset. |
Output
This method returns no output data.
Sample code
In the message Check out this support article https://www.support-article.com/., remove the word out.
1
Send a draft message
Send() publishes the draft text message with all mentioned users, links, and referenced channels.
Whenever you mention any users, Send() also emits events of type mention.
Method signature
This method has the following signature:
1messageDraft.Send(SendTextParams sendTextParams)
Input
| Parameter | Description |
|---|---|
sendTextParamsType: SendTextParamsDefault: new() | Object which holds additional parameters. |
SendTextParams → MetaType: stringDefault: string.Empty; | Additional description of the request. |
SendTextParams → StoreInHistoryType: BoolDefault: true | If true, the messages are stored in Message Persistence (PubNub storage). If StoreInHistory is not specified, the Message Persistence configuration specified on the Admin Portal keyset is used. |
SendTextParams → SendByPostType: BoolDefault: false | When true, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request instead of the query string when HTTP GET is used. The messages are also compressed to reduce their size. |
SendTextParams → MentionedUsersType: Dictionary<int, User>Default: new() | Object mapping a mentioned user (with name and ID) with the number of mention (like @Mar) in the message (relative to other user mentions). For example, { 0: { id: 123, name: "Mark" }, 2: { id: 345, name: "Rob" } } means that Mark will be shown on the first mention in the message and Rob on the third. Refer to User Mentions for more details and example. |
SendTextParams → QuotedMessageType: MessageDefault: null | Object added to a message when you quote another message. This object stores the following info about the quoted message: { timetoken: quotedMessage.timetoken, text: quotedMessage.text, userId: quotedMessage.userId }, where timetoken is the time when the quoted message was published, text contains the original message content, and userId is the identifier of the user who published the quoted message. Refer to Quotes for more details and example. |
Suppose a user adds elements to the message draft, such as links, quotes, other user mentions, or channel references. In that case, these are not explicitly passed in the send() method but get added to the MessageDraft object through the AddMention() and addQuote() methods.
Output
An awaitable Task.
Sample code
Send a draft message containing just plain text.
1