Skip to content

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.

  • You know the Participants roster, which gives the ids you message. See Participants.
  • Chat calls return promises: use them inside async functions with await, and catch errors.
  • Chat works in play only.

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 when snapshot.groupsAvailable is true.
Member What it does
Chat.connect() Connect to chat. Resolves true when connected, false otherwise, for example in the editor or before the scene has been drawn in play.
Chat.getSnapshot() The current chat state.
Chat.subscribe(listener) 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.

Field What it is
connection 'unconfigured', 'disconnected', 'connecting', 'connected' or 'disposed'.
ready Whether chat can be used now.
generalConversationId The id of the General conversation, once ready.
conversations Summaries of your conversations: id, kind ('general', 'direct' or 'group'), lastReceivedMessage, and for groups name and memberCount.
windows The loaded messages per conversation: conversationId, messages, loading, nextCursor and error.
groupsAvailable Whether group conversations are offered.
deleteAvailable Whether deleting messages is offered.
historyEnabled false when the experience keeps no history: only messages sent while you are present are shown.
error The last error code, if any.
Field What it is
id The message’s id.
conversationId The conversation it belongs to.
kind 'general', 'direct' or 'group'.
text The text. Empty when the message was deleted.
sender.displayName 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.
Member What it does
Chat.sendGeneral(text) Send to the General conversation. Resolves the message.
Chat.openDirect(participantId) Open (or find) the direct conversation with a participant. Resolves the conversation.
Chat.sendDirect(conversationId, text) Send in a direct conversation.
Chat.sendMessage(conversationId, text) Send in any conversation, of any kind.
Chat.loadHistory(conversationId, { before?, limit? }) Load a page of messages: messages, and nextCursor when there are older ones. Pass nextCursor as before to load the page before it.
Chat.loadConversations({ cursor?, limit? }) Load a page of conversation summaries: conversations, and nextCursor for the next page.
Chat.deleteMessage(conversationId, messageId) Delete a message you may delete, when deleteAvailable is true. Everyone then sees it as deleted.
Member What it does
Chat.createConversation({ participantIds, name? }) Create a new group with these participants. Resolves its details.
Chat.getConversation(id) Read a conversation’s details. For a group: members (id, displayName), selfMembershipId, ownerMembershipId, canManage and membershipRevision.
Chat.addMembers(id, participantIds, { expectedRevision? }) Add participants to a group you manage.
Chat.removeMembers(id, membershipIds, { expectedRevision? }) Remove members (by their member id, not participant id) from a group you manage.
Chat.leaveConversation(id, { expectedRevision? }) Leave a group.
  • The creator manages the group; every member can leave; when the manager leaves, the earliest remaining member takes over.
  • expectedRevision protects against two people changing the members at once: pass the membershipRevision you read, and the change is refused if the group changed since.
  • To remove yourself, use leaveConversation, not removeMembers.

A refused call rejects with a ChatError whose code is:

Code Meaning
chat_unavailable Chat is not offered here, or not reachable now.
chat_unauthorized You are not, or no longer, allowed into this conversation.
chat_forbidden You may not do this, such as managing a group you do not manage.
chat_validation Something in the request is invalid, such as an empty message.
chat_recipient_offline The direct message recipient is not online.
chat_conflict The conversation changed in the meantime, such as a stale expectedRevision.
chat_storage_unavailable Message history cannot be reached now.
chat_rate_limited Too many messages too fast.
chat_invalid_response An unexpected answer was received.
Greeter.jx
#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!');
});
}
  • connect resolves false before the scene is drawn, so the script waits a second and tries again.
  • The script waits for ready before sending. The listener is called right away inside subscribe, so a flag, not the returned stop function, makes sure it greets only once.
ChatPanel.jx
#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.
DirectMessage.jx
#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 Participants are what openDirect takes.
  • loadHistory pages backwards: pass the nextCursor of one page as before for the page before it.
  • A direct message to someone who went offline rejects with chat_recipient_offline.
TeamChat.jx
#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);
}
});
}
  • createConversation takes participant ids; removeMembers takes the member ids from getConversation.
  • expectedRevision makes the removal fail with chat_conflict if someone changed the group in the meantime.
  • Only the manager (canManage) may remove members.
  • Connecting too early. connect() resolves false in the editor and before play has drawn the scene. Connect after a user action, or retry.
  • Sending before ready. Connected is not ready. Check snapshot.ready.
  • Mixing ids. Direct conversations and new groups take participant ids; removeMembers takes member ids.
  • Assuming history. When historyEnabled is false, loadHistory returns no earlier messages; the live transcript is in windows.