Chat
Updated
Chat lets a script take part in the experience’s text chat: read the conversation, send messages to everyone, write privately to one person, or run a small group conversation. Use it to build a custom chat panel, a bot that greets newcomers, or a game that reacts to what people type. Chat is optional: an experience may not offer it, and every call says so instead of failing silently.
Before you start
Section titled “Before you start”- You know the
Participantsroster, which gives the ids you message. See Participants. - Chat calls return promises: use them inside
asyncfunctions withawait, and catch errors. - Chat works in play only.
Conversations
Section titled “Conversations”Chat has three kinds of conversation, each with an opaque id:
- General. One conversation for everyone in the experience. Its id is
snapshot.generalConversationId. - Direct. A private conversation between you and one participant, opened with
openDirect(participantId). Sending a new direct message needs the other person to be online; reading earlier history does not. - Group. A private conversation with a chosen set of people, created with
createConversation. Available whensnapshot.groupsAvailableistrue.
Connecting
Section titled “Connecting”| Member | What it does |
|---|---|
Chat. |
Connect to chat. Resolves true when connected, false otherwise, for example in the editor or before the scene has been drawn in play. |
Chat. |
The current chat state. |
Chat. |
Call listener(snapshot) with the state and again on each change. Returns a function that stops it; it also stops when the script is released. |
Call connect() yourself once play has drawn the scene; reading the snapshot or subscribing never connects. Being connected is not enough to send: wait until snapshot.ready is true, which means your chat identity is confirmed.
The snapshot
Section titled “The snapshot”| Field | What it is |
|---|---|
connection |
'unconfigured', 'disconnected', 'connecting', 'connected' or 'disposed'. |
ready |
Whether chat can be used now. |
general |
The id of the General conversation, once ready. |
conversations |
Summaries of your conversations: id, kind ('general', 'direct' or 'group'), last, and for groups name and memberCount. |
windows |
The loaded messages per conversation: conversation, messages, loading, nextCursor and error. |
groups |
Whether group conversations are offered. |
delete |
Whether deleting messages is offered. |
history |
false when the experience keeps no history: only messages sent while you are present are shown. |
error |
The last error code, if any. |
A message
Section titled “A message”| Field | What it is |
|---|---|
id |
The message’s id. |
conversation |
The conversation it belongs to. |
kind |
'general', 'direct' or 'group'. |
text |
The text. Empty when the message was deleted. |
sender. |
The sender’s name. |
isSelf |
Whether you sent it from this attendance. |
createdAt |
When it was sent. |
sequence |
Its position in the conversation. |
redacted |
true when the message was deleted. |
canDelete |
Whether you may delete it. |
Sending and reading
Section titled “Sending and reading”| Member | What it does |
|---|---|
Chat. |
Send to the General conversation. Resolves the message. |
Chat. |
Open (or find) the direct conversation with a participant. Resolves the conversation. |
Chat. |
Send in a direct conversation. |
Chat. |
Send in any conversation, of any kind. |
Chat. |
Load a page of messages: messages, and nextCursor when there are older ones. Pass nextCursor as before to load the page before it. |
Chat. |
Load a page of conversation summaries: conversations, and nextCursor for the next page. |
Chat. |
Delete a message you may delete, when delete is true. Everyone then sees it as deleted. |
Group conversations
Section titled “Group conversations”| Member | What it does |
|---|---|
Chat. |
Create a new group with these participants. Resolves its details. |
Chat. |
Read a conversation’s details. For a group: members (id, displayName), self, owner, canManage and membership. |
Chat. |
Add participants to a group you manage. |
Chat. |
Remove members (by their member id, not participant id) from a group you manage. |
Chat. |
Leave a group. |
- The creator manages the group; every member can leave; when the manager leaves, the earliest remaining member takes over.
expectedRevisionprotects against two people changing the members at once: pass themembershipRevisionyou read, and the change is refused if the group changed since.- To remove yourself, use
leaveConversation, notremoveMembers.
Errors
Section titled “Errors”A refused call rejects with a ChatError whose code is:
| Code | Meaning |
|---|---|
chat_ |
Chat is not offered here, or not reachable now. |
chat_ |
You are not, or no longer, allowed into this conversation. |
chat_ |
You may not do this, such as managing a group you do not manage. |
chat_ |
Something in the request is invalid, such as an empty message. |
chat_ |
The direct message recipient is not online. |
chat_conflict |
The conversation changed in the meantime, such as a stale expected. |
chat_ |
Message history cannot be reached now. |
chat_ |
Too many messages too fast. |
chat_ |
An unexpected answer was received. |
Examples
Section titled “Examples”1. Greeting the room
Section titled “1. Greeting the room”#pragma lifecycle(startup)
// Connect once play has drawn the scene, retrying a few times.async function connectChat(tries = 5) { for (let i = 0; i < tries; i++) { if (await Chat.connect()) return true; await new Promise((done) => delay(done, 1000)); } return false;}
async function startup() { if (!(await connectChat())) { log('Chat is not available here'); return; } let greeted = false; Chat.subscribe(async (snapshot) => { if (greeted || !snapshot.ready) return; greeted = true; await Chat.sendGeneral('Hello everyone!'); });}Connects to chat once the scene is drawn, retrying a few times, waits for the snapshot to be ready and sends one greeting to the general conversation.
Read the log. The preview has no Arena room, so after a few retries the script says chat is not available; in a published world it greets everyone once.
connectresolvesfalsebefore the scene is drawn, so the script waits a second and tries again.- The script waits for
readybefore sending. The listener is called right away insidesubscribe, so a flag, not the returned stop function, makes sure it greets only once.
Snippets
Section titled “Snippets”1. A chat panel
Section titled “1. A chat panel”#pragma lifecycle(startup)
// Scene: a "Transcript" UI Label (with maxWidth and maxHeight, overflow 'scroll'),// a "Message" UI Input with a Signal Emitter on 'chat/input'.let transcript;let input;
function render(snapshot) { const general = snapshot.windows.find((w) => w.conversationId === snapshot.generalConversationId); const lines = (general?.messages ?? []) .slice(-20) .map((m) => (m.redacted ? '(deleted)' : `${m.isSelf ? 'You' : m.sender.displayName}: ${m.text}`)); transcript.setProps({ text: lines.join('\n') || 'No messages yet' });}
async function startup() { transcript = findEntity('Transcript').getComponent(UILabelComponent); input = findEntity('Message').getComponent(UIInputComponent);
Chat.subscribe(render);
on('chat/input', async (event) => { if (event.eventType !== EventType.UIInput.Submit) return; const text = event.data.text.trim(); if (!text) return; if (!Chat.getSnapshot().ready && !(await Chat.connect())) return; try { await Chat.sendGeneral(text); input.setValue(''); } catch (error) { if (error.code === 'chat_rate_limited') log('Slow down'); else log('Not sent:', error.code); } });}- The General conversation’s loaded messages live in
snapshot.windows; the subscription redraws the last twenty. - Connecting on the first submit happens after a user action, when the scene is certainly drawn.
- Errors are reported by
code, so the panel can explain a rate limit.
2. Messaging one participant
Section titled “2. Messaging one participant”#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'chat/dm-host'.async function messageHost() { if (!(await Chat.connect())) return; const host = Participants.getSnapshot().participants.find( (p) => !p.isLocal && p.role === 'host' && p.world.state === 'connected', ); if (!host) { log('No host online'); return; } try { const conversation = await Chat.openDirect(host.id); await Chat.sendDirect(conversation.id, 'Hi, could you help me?');
// Show the last 50 messages, then one older page if there is one. const page = await Chat.loadHistory(conversation.id, { limit: 50 }); log(page.messages.map((m) => m.text)); if (page.nextCursor) { const older = await Chat.loadHistory(conversation.id, { before: page.nextCursor, limit: 50 }); log(`${older.messages.length} older messages`); } } catch (error) { if (error.code === 'chat_recipient_offline') log('The host just left'); else log('Direct message failed:', error.code); }}
function startup() { on('chat/dm-host', (event) => { if (event.eventType === EventType.UIButton.Press) messageHost(); });}- Participant ids from
Participantsare whatopenDirecttakes. loadHistorypages backwards: pass thenextCursorof one page asbeforefor the page before it.- A direct message to someone who went offline rejects with
chat_recipient_offline.
3. A small group for a team
Section titled “3. A small group for a team”#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'chat/team'.let teamId;
async function makeTeam() { await Chat.connect(); if (!Chat.getSnapshot().groupsAvailable) { log('Groups are not offered here'); return; } const others = Participants.getSnapshot().participants.filter((p) => !p.isLocal); const group = await Chat.createConversation({ name: 'Blue team', participantIds: others.slice(0, 3).map((p) => p.id), }); teamId = group.id; await Chat.sendMessage(teamId, 'Welcome to the blue team!');}
async function removeQuietest() { const details = await Chat.getConversation(teamId); if (details.kind !== 'group' || !details.canManage) return; const someone = details.members.find((m) => m.id !== details.selfMembershipId); if (!someone) return; await Chat.removeMembers(teamId, [someone.id], { expectedRevision: details.membershipRevision });}
function startup() { on('chat/team', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; try { if (!teamId) await makeTeam(); else await removeQuietest(); } catch (error) { if (error.code === 'chat_conflict') log('The team changed, try again'); else log('Team chat:', error.code); } });}createConversationtakes participant ids;removeMemberstakes the member ids fromgetConversation.expectedRevisionmakes the removal fail withchat_conflictif someone changed the group in the meantime.- Only the manager (
canManage) may remove members.
Common mistakes
Section titled “Common mistakes”- Connecting too early.
connect()resolvesfalsein the editor and before play has drawn the scene. Connect after a user action, or retry. - Sending before
ready. Connected is not ready. Checksnapshot.ready. - Mixing ids. Direct conversations and new groups take participant ids;
removeMemberstakes member ids. - Assuming history. When
historyEnabledisfalse,loadHistoryreturns no earlier messages; the live transcript is inwindows.