Events from the page
Pages send events to the rooms they are in, straight through WordPlus Cloud, with no request to your server: chat messages, typing, read ticks, a cursor. A room rule says which events may be sent to it, and every one is sealed like those your server sends.

What a room allows
A chat room for each two people, named after them: chat:34:42, the smaller id first. The use case chat builds it whole, groups too.
Your plugin decides who may join and what their pages may send. A page that joins asks your site first, and a rule answers: a function your plugin declares once for every room whose name fits chat:{a}:{b}. WordPlus Cloud then holds the page to the answer, and to the options beside it. This rule says:
- The two people in the name join, and anyone else is refused.
- Their pages send messages, typing, reactions and read ticks, and nothing else.
- Messages and reactions reach your site too, to keep.
- The last 50 events stay for 5 minutes, for a page that reconnects.
// The chats of two people, such as chat:34:42.
wordplus_realtime()->room( 'chat:{a}:{b}', function ( $user_id, array $p ) {
// 1. The two people in the name.
return in_array( (string) $user_id, array( $p['a'], $p['b'] ), true );
}, array(
// 2. What their pages send.
'emit' => array( 'message', 'typing', 'reaction', 'read' ),
// 3. What reaches your site too.
'webhook' => array( 'message', 'reaction' ),
// 4. The last 50 events, for 5 minutes.
'history' => 50,
) );
emitlists the names, or'*'for any. None by default: a room your server alone sends to.webhooknames those your server gets too, to keep them (below).historykeeps the last events of the room for 5 minutes: what a page that reconnects missed comes again from it.- The answer for one user can narrow it:
array( 'emit' => array( 'typing' ) ), orarray( 'readOnly' => true )for none. - The names kept for the rooms themselves (
joined,join,leave,count,error,kicked,connect,disconnect,connect_error,state,online) are never allowed.
Sending
A page sends to a room it has joined, and hears what the others send:
const chat = wordplusRealtimeClient.page().join( 'chat:34:42' );
chat.emit( 'message', { text: 'Hi' } ); // sent, nothing waited for
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } ); // WordPlus Cloud took it: checked, kept, sent on
chat.volatile.emit( 'typing', { on: true } ); // dropped rather than queued while off line, never kept
await chat.timeout( 5000 ).emitWithAck( 'message', { text: 'Hi' } ); // an ack waited for 5 seconds at most
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) ); // meta: { from, id, at, replayed? }
- Everyone in the room gets it, the other tabs and devices of the sender too. The tab that sent it does not.
emitWithAckresolves with{ id, at }once WordPlus Cloud has checked the event, kept it (when the room keeps history) and sent it on. It rejects with a code:not_allowed(the rule does not list it),forbidden(not in the room),rate_limited,too_large,bad_event.meta.fromis the sender user id, as the site vouched for them: a page cannot send as someone else.- Limits: 1 MB an event (kept in history up to 64 KB), 50 a second a connection, in bursts of up to 100.
Keeping the conversation
The conversation is for your plugin to keep, in the WordPress database, as Better Messages keeps its own. A room keeps its events for 5 minutes, for pages that reconnect. Your server gets the events a room rule names in webhook (webhooks) and saves them by event_id, the id the pages saw as meta.id. A route of yours gives them back, a page at a time:
add_action( 'plugins_loaded', function () {
wordplus_realtime()->on( 'message', function ( array $e ) {
my_chat_save( $e['event_id'], $e['room'], (int) $e['from'], (string) $e['data']['text'], (int) $e['at'] );
} );
} );
// GET /wp-json/my-chat/v1/chat/34/42/messages: the newest 50, or with ?before=<id> the 50 before that one, oldest
// first. Only its two people may read it.
add_action( 'rest_api_init', function () {
register_rest_route( 'my-chat/v1', '/chat/(?P<a>\d+)/(?P<b>\d+)/messages', array(
'methods' => 'GET',
'permission_callback' => function ( $request ) {
return in_array( get_current_user_id(), array( (int) $request['a'], (int) $request['b'] ), true );
},
'callback' => function ( $request ) {
return my_chat_page( 'chat:' . $request['a'] . ':' . $request['b'], $request->get_param( 'before' ), 50 ); // array( 'messages' => array( array( id, from, text, at, reactions ) ), 'more' => … )
},
) );
} );
- Check there anything that matters: the events do not go through your server before they are sent on.
atis in milliseconds, andreactionsmaps each reaction to who chose it. A reaction comes as{ id, key }: the one reaction of the user to messageid, an emptykeytaking it back.- A gap: a page back after the 5 minutes a room keeps its events, or after more came than it keeps, gets what the room still had, then
erroron the room with{ code: 'gap' }, still joined. Some events are lost to it, so ask your route for the newest page again:chat.on( 'error', ( e ) => e.code === 'gap' && reload() ).
Ready-made: the chat
Optional, as every ready-made part: the events above are all a chat needs, drawn your way with the JavaScript API. This is the ready-made one.
The Better Messages conversation on a room: your plugin conversation paged back as the reader scrolls up, the room filling in what came since, the day separators and unread line, the messages of a sender stacked, typing, reactions, the read ticks and the composer.
<chat-room room="chat:34:42" placeholder="Write a message" reactions="1f44d 2764 1f602" max-length="2000"></chat-room>
<typing-line room="chat:34:42"></typing-line> <!-- the typing line alone -->
// wp.apiFetch sends the REST nonce, so your route knows the user (your script depends on wp-api-fetch).
document.querySelector( 'chat-room' ).load = ( before ) =>
wp.apiFetch( { path: '/my-chat/v1/chat/34/42/messages' + ( before ? '?before=' + encodeURIComponent( before.id ) : '' ) } );
load( before )answers{ messages, more }:beforeisnullfor the newest page, or the oldest message shown ({ id, at }). Without it, the chat shows what the room still has. It may be set before the element is on the page.- It loads with
wordplus_realtime()->call_screen(), orui()on a page without calls (the call screen). Names and pictures come from the site directory. - It fills the height the page gives it, 480px when you give none.
| Attribute | |
|---|---|
room | the room of the conversation, whose rule lets the page send message, typing, read and reaction |
placeholder | the words in the empty composer |
reactions | the reactions to pick from, emoji (👍 ❤️) or their code points (1f44d 2764), apart by spaces. Empty for none. 👍 ❤️ 😂 😮 😢 🙏 by default |
max-length | the most characters of a message |
messages | a route for the messages your plugin kept, asked with the page cookies alone. A WordPress REST route knows the user only with its nonce, so on WordPress set load instead, as above |
to | in a chat between two, the other person: on the top bar of the chat, with whether they are online |
name, avatar | the name and picture of to, as your page has them: on the bar, on their messages and in their call. Without them, those of the site directory |
call | the call of the conversation, shown in the chat while it is on (its call) |
start-call | video or audio: calls to as the chat opens, once, for a page that a Video Call button elsewhere links to, so the call starts in the chat |
The element also says when the room took a message of this user, as the sent event, with { id, room, text, at } as its detail: for your plugin to keep it from the page, on a local site no webhook reaches.
It sends what a page of your own would, so the two read each other:
| Event | Data | |
|---|---|---|
message | { text } | with an ack. Your server keeps it |
typing | { on } | volatile |
read | { id }, the newest message seen | volatile, for the sender ticks |
reaction | { id, key }, key empty to take it back | with an ack. Your server keeps it |
Its call
With call, the call of the conversation shows in the chat while it is on: beside the messages where the chat is 600px wide or more, and over them where it is narrower, with Show Chat and Hide Chat in the call controls. With to, the top bar of the chat has an Audio Call and a Video Call button. The call moves into the chat as its page opens, and back to the window in the corner as the page closes, going on throughout, as in a <call-spot>.
call alone is the call named as the room, so your plugin owns calls of the same pattern as its chats, with a rule of its own. A page that places or answers a call asks your site first, as for joining the room. This rule says yes when:
- Both people are the two in the name.
- Neither has blocked the other, as your plugin keeps it.
// The calls of the chats of two people, such as chat:34:42: the same names as their rooms.
wordplus_realtime()->calls( 'chat:{a}:{b}', function ( $user_id, $with, array $p ) {
// 1. Both people are the two in the name.
$named = array( (int) $p['a'], (int) $p['b'] );
if ( ! in_array( $user_id, $named, true ) || ! in_array( $with, $named, true ) ) {
return false;
}
// 2. Neither has blocked the other.
return ! my_chat_blocked( $user_id, $with );
} );
<chat-room room="chat:34:42" to="34" name="Ann" call style="height: 560px"></chat-room>
A value names another call: call="date:{pair}", {pair} being the page user and to in order. The chat names its call itself, so it takes the call over a <call-spot> of a pattern or of every call.
The call connects as every call between two people does, directly, through our relays or through our media servers, with no credits (calls).