לאפליקציות
API ו-SDK של צ׳אט לאפליקציה שלכם
הוסיפו צ׳אט ל-Next.js, ל-Laravel, ל-Django ולכל סטאק אחר: שיחות בין שני אנשים וצ׳אטים קבוצתיים, עם הקלדה, מי מחובר, סימוני קריאה, תגובות וקבצים. הצ׳אט המוכן עובד בדפדפן כמו שהוא, ההודעות מגיעות מיד לכל מי שבשיחה, והשרת שלכם שומר אותן במסד הנתונים שלכם.
או נסו את ההדגמה החיה: חנות קטנה שבה לקוח כותב לחנות, כל אחד בחלון משלו.
התמחור הטוב ביותר ל-WebSockets, שיחות אחד על אחד ללא הגבלה עם שרתי TURN ברחבי העולם, ושיחות קבוצתיות ושידור חי עם מכסה כלולה. החל מ-$11.99 לחודש עבור 1,000 חיבורים בו-זמניים, בחיוב שנתי, או $14.99 בחיוב חודשי.
Next.js בשרת ו-React בדף.
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);
} );// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)// Your /auth route asks this for each room a page wants.
func roomRule(room, user string) (*wordplus.Room, string) {
chat := wordplus.Room{
Emit: []string{"message", "typing", "read", "reaction"},
Webhook: []string{"message", "reaction"},
History: 50,
Info: profile(user),
}
part := strings.Split(room, ":")
// Two people, such as chat:34:42: the two in its name alone.
if len(part) == 3 && part[0] == "chat" {
if user != part[1] && user != part[2] {
return nil, "forbidden"
}
return &chat, ""
}
// A group, such as group:7: its members, who see each other.
if len(part) == 2 && part[0] == "group" {
if !isMemberOf(part[1], user) {
return nil, "forbidden"
}
chat.Presence = true
return &chat, ""
}
return nil, "no_rule"
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list><chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42" to={ 34 } name="Ann" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
$effect( () => { rt.current?.ui(); } );
</script>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>import {
Component, CUSTOM_ELEMENTS_SCHEMA, effect,
} from '@angular/core';
import { injectRealtime } from '@wordplus/realtime/angular';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>`,
} )
export class Conversation {
readonly rt = injectRealtime();
constructor() {
effect( () => void this.rt()?.ui() );
}
}// No ready-made chat on iOS: your own, on the same room.
let chat = rt.join("chat:34:42")
chat.on("message") { data, meta in
draw(meta.from, data["text"]?.string ?? "")
}
try await chat.emitWithAck("message", ["text": "Hi Ann"])// No ready-made chat on Android: your own, on the same room.
val chat = rt.join("chat:34:42")
chat.on("message") { data, meta ->
draw(meta.from, data.jsonObject["text"])
}
chat.emitWithAck("message", buildJsonObject { put("text", "Hi") })import { useRoom } from '@wordplus/realtime/react';
// No ready-made chat in React Native: your own, on the room.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.from, data.text ),
} );
const send = ( text ) => chat.emitWithAck( 'message', { text } );
return <SendBox onSend={ send } />;
}// No ready-made chat in Flutter: your own, on the same room.
final chat = rt.join('chat:34:42');
chat.on('message', (data, meta) => draw(meta.from, data['text']));
await chat.emitWithAck('message', {'text': 'Hi Ann'});
ההודעות שלכם
ההודעות שלכם נשארות במסד הנתונים שלכם
אנחנו מעבירים את השיחה, והשרת שלכם שומר אותה. חדר מחזיק את האירועים האחרונים שלו כחמש דקות, רק כדי שדף שמתחבר מחדש לא יפספס דבר, ומסד הנתונים שלכם מחזיק את השיחה עצמה.
מיד, בכל מכשיר
הודעה עוברת מדף לדף דרך השרתים שלנו ברגע שהיא נשלחת, בלי בקשה לשרת שלכם, לכל כרטיסייה ולכל אפליקציה של כל מי שבשיחה.
נשמרת בשרת שלכם
הווובהוק שלכם מקבל כל הודעה וכל תגובה ברגע שהן נשלחות ושומר אותן במסד הנתונים שלכם. הנתיב שלכם נותן לצ׳אט את ההיסטוריה שלו כשהוא נפתח, כך שהשיחה שלכם לחפש בה, לנהל אותה ולהציג אותה שוב.
חתומה בדרך
שיחה פרטית עוברת חתומה במפתחות שהשרת שלכם יוצר: ההודעות שלה, ההיסטוריה שלה ומי נמצא בה. הענן מעביר אותה בלי יכולת לקרוא אותה.
השרת שלכם מחליט
בונים צ׳אט, משימה אחר משימה
צ׳אט הוא חדר: chat:34:42 כשבן כותב לאן, שמוכרת, או group:7 לקבוצה. כלל אחד בשרת שלכם קובע מי נמצא בו, והדפים שולחים זה לזה דרכו הודעות, הקלדה וסימוני קריאה. הנה שניהם, מהצ׳אט המוכן ועד שיחה.
Next.js בשרת ו-React בדף.
הוסיפו את הצ׳אט המוכן
כלל אחד בשרת שלכם לכל סוג צ׳אט: צ׳אט בין שניים מכניס את שני האנשים שבשמו, וקבוצה את החברים בה, לפי הנתונים שלכם. אחר כך הצ׳אט נכנס לדף, עם הקלדה, סימוני קריאה ותגובות. isMemberOf היא בדיקה משלכם.
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);
} );// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)// Your /auth route asks this for each room a page wants.
func roomRule(room, user string) (*wordplus.Room, string) {
chat := wordplus.Room{
Emit: []string{"message", "typing", "read", "reaction"},
Webhook: []string{"message", "reaction"},
History: 50,
Info: profile(user),
}
part := strings.Split(room, ":")
// Two people, such as chat:34:42: the two in its name alone.
if len(part) == 3 && part[0] == "chat" {
if user != part[1] && user != part[2] {
return nil, "forbidden"
}
return &chat, ""
}
// A group, such as group:7: its members, who see each other.
if len(part) == 2 && part[0] == "group" {
if !isMemberOf(part[1], user) {
return nil, "forbidden"
}
chat.Presence = true
return &chat, ""
}
return nil, "no_rule"
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>{{-- In the page of Ben, writing to Ann. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// In the page of Ben, writing to Ann.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. In the page of Ben, writing to Ann. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- In the page of Ben, writing to Ann. -->
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- In the page of Ben, writing to Ann. -->
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}שליחה ושמירה של הודעה
הצ׳אט המוכן עושה את זה בעצמו. במסך משלכם, דף שולח הודעה לחדר, וכל מי שבו מקבל אותה מיד. הווובהוק שלכם שומר אותה לפי המזהה שלה ומודיע לצד השני, בכל דף שבו הוא נמצא. saveMessage היא פונקציה משלכם.
// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Each message pages send, kept once by its id, however often the webhook brings it.
$realtime->on( 'message', function ( array $e ) use ( $realtime ) {
Message::updateOrCreate( [ 'id' => $e['event_id'] ], [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
// A notice to the other of the two, on whatever page or app they have open.
[ $kind, $a, $b ] = explode( ':', $e['room'] ) + [ '', '', '' ];
if ( 'chat' === $kind ) {
$to = (string) $e['from'] === $a ? $b : $a;
$realtime->toUser( $to )->emit( 'new_message', [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
}
} );
} );// Each message pages send, kept once by its id, however often the webhook brings it.
$realtime->on( 'message', function ( array $e ) use ( $realtime ) {
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'] );
// A notice to the other of the two, on whatever page or app they have open.
[ $kind, $a, $b ] = explode( ':', $e['room'] ) + [ '', '', '' ];
if ( 'chat' === $kind ) {
$to = (string) $e['from'] === $a ? $b : $a;
$realtime->toUser( $to )->emit( 'new_message', [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
}
} );# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)// In your webhook route: app.Webhook() checks it and opens what each page sent.
for _, event := range events {
if event["type"] != "emit" || event["event"] != "message" {
continue
}
room, _ := event["room"].(string)
from := fmt.Sprint(event["from"])
data, _ := event["data"].(map[string]any)
// Kept once, by the id the pages saw, however often the webhook brings it.
saveMessage(event["event_id"], room, from, data["text"], event["at"])
// A notice to the other of the two, on whatever page or app they have open.
if part := strings.Split(room, ":"); len(part) == 3 && part[0] == "chat" {
to := part[1]
if from == part[1] {
to = part[2]
}
app.EmitToUser(to, "new_message", map[string]any{"room": room, "from": from, "text": data["text"]})
}
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );'use client'; // in Next.js
import { useRoom, useUserEvent } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text ); // this tab does not get its own back
};
return <SendBox onSend={ send } />;
}
// In your layout: a message in a chat that is not open there.
export function NewMessages() {
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
return null;
}<script setup>
import { useRoom, useUserEvent } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const { emitWithAck } = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
</script>
<template>
<SendBox @send="send" />
</template><script>
import { useRoom, useUserEvent } from '@wordplus/realtime/svelte';
import SendBox from './SendBox.svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
</script>
<SendBox onsend={ send } />import { Component } from '@angular/core';
import { injectRoom, injectUserEvent } from '@wordplus/realtime/angular';
import { SendBox } from './send-box';
// provideRealtime() once, in your application's providers.
@Component( {
selector: 'app-conversation',
imports: [ SendBox ],
template: '<app-send-box (send)="send( $event )" />',
} )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
constructor() {
// A message in a chat that is not open here.
injectUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
}
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
async send( text: string ) {
const { id } = await this.chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
}
}let chat = rt.join("chat:34:42")
// Every page and app in the conversation gets it at once.
chat.on("message") { data, meta in draw(meta.id, meta.from, data["text"]?.string ?? "") }
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
let ack = try await chat.emitWithAck("message", ["text": "Has my order left yet?"])
// A message in a chat that is not open here.
rt.on("new_message") { m, _ in showNotice(m["room"]?.string ?? "", m["text"]?.string ?? "") }val chat = rt.join("chat:34:42")
// Every page and app in the conversation gets it at once.
chat.on("message") { data, meta -> draw(meta.id, meta.from, data.jsonObject["text"]?.jsonPrimitive?.content ?: "") }
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
val ack = chat.emitWithAck("message", buildJsonObject { put("text", "Has my order left yet?") })
// A message in a chat that is not open here.
rt.on("new_message") { m, _ -> showNotice(m.jsonObject["room"]?.jsonPrimitive?.content ?: "", m.jsonObject["text"]?.jsonPrimitive?.content ?: "") }import { useRoom, useUserEvent } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
return <SendBox onSend={ send } />;
}final chat = rt.join('chat:34:42');
// Every page and app in the conversation gets it at once.
chat.on('message', (data, meta) => draw(meta.id, meta.from, data['text']));
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
final ack = await chat.emitWithAck('message', {'text': 'Has my order left yet?'});
// A message in a chat that is not open here.
rt.on('new_message', (m, _) => showNotice(m['room'], m['text']));מי מחובר ומי מקליד
הקלדה היא אירוע חולף, שלעולם לא נכנס לתור ולא נשמר. מי מחובר עובד בכל מקום באפליקציה שלכם, וקבוצה מציגה מי נמצא בה עכשיו. הצ׳אט המוכן מציג את שניהם, ורשימה מוכנה מציגה את האנשים בקבוצה.
Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );'use client'; // in Next.js
import { OnlineList, useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );
// draw them your way
}
// Who is in the group now: [ { id, info } ], or the ready-made list.
export function GroupMembers() {
const members = usePresence( 'group:7' );
return <OnlineList room="group:7" title="In the group" />;
}<script setup>
import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
const members = usePresence( 'group:7' ); // who is in the group now: [ { id, info } ]
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room.value?.volatile.emit( 'typing', { on: true } );
</script><script>
import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // typing.current: the ids typing now
const status = useOnline( [ 34 ] ); // status.online[ 34 ], status.lastSeen[ 34 ]
const members = usePresence( 'group:7' ); // members.current: who is in the group now
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );
</script>import { Component } from '@angular/core';
import { injectOnline, injectPresence, injectRoom, injectTyping } from '@wordplus/realtime/angular';
// provideRealtime() once, in your application's providers.
@Component( {
selector: 'app-conversation',
template: `
<p>Ann is {{ status.online()[ 34 ] ? 'online' : 'away' }}</p>
@if ( typing().length > 0 ) { <p>Typing…</p> }
<input (input)="chat.room()?.volatile?.emit( 'typing', { on: true } )">
`,
} )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42' );
readonly typing = injectTyping( this.chat ); // the ids typing now, gone as they stop
readonly status = injectOnline( [ 34 ] ); // Ann online, or when she was last
readonly members = injectPresence( 'group:7' ); // who is in the group now
}let chat = rt.join("chat:34:42")
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", ["on": true])
chat.on("typing") { data, meta in showTyping(meta.from, data["on"]?.bool ?? false) }
// Ann online now, or when she was last.
rt.online.watch(["34"]).on("change") { change in showOnline(change["id"]?.string, change["online"]?.bool ?? false) }
// Who is in the group now, as its rule says presence: true.
let group = rt.join("group:7")
group.on("join") { member, _ in addMember(member["id"]?.string ?? "") }
group.on("leave") { member, _ in removeMember(member["id"]?.string ?? "") }val chat = rt.join("chat:34:42")
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", buildJsonObject { put("on", true) })
chat.on("typing") { data, meta -> showTyping(meta.from, data.jsonObject["on"]) }
// Ann online now, or when she was last.
rt.online.watch(listOf("34")).on("change") { change -> showOnline(change.jsonObject["id"], change.jsonObject["online"]) }
// Who is in the group now, as its rule says presence: true.
val group = rt.join("group:7")
group.on("join") { member, _ -> addMember(member.jsonObject["id"]) }
group.on("leave") { member, _ -> removeMember(member.jsonObject["id"]) }import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
const members = usePresence( 'group:7' ); // who is in the group now
// Volatile: dropped rather than queued while offline, and never kept.
const onChangeText = () => chat.room?.volatile.emit( 'typing', { on: true } );
// draw them your way
}final chat = rt.join('chat:34:42');
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit('typing', {'on': true});
chat.on('typing', (data, meta) => showTyping(meta.from, data['on']));
// Ann online now, or when she was last.
rt.online.watch(['34']).on('change', (change) => showOnline(change['id'], change['online']));
// Who is in the group now, as its rule says presence: true.
final group = rt.join('group:7');
group.on('join', (member, _) => addMember(member['id']));
group.on('leave', (member, _) => removeMember(member['id']));היסטוריה כשהצ׳אט נפתח
השיחה נמצאת במסד הנתונים שלכם, לא אצלנו. נתיב משלכם מחזיר את 50 ההודעות האחרונות שלה, ואת 50 הקודמות כשהקורא גולל למעלה, למי שהכלל שלכם מכניס. החדר משלים את מה שהגיע מאז. messagesOf היא שאילתה משלכם.
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
export async function GET( request: Request ) {
const me = await currentUserId();
const query = new URL( request.url ).searchParams;
const room = query.get( 'room' ) ?? '';
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
return new Response( null, { status: 403 } );
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
return Response.json( await messagesOf( room, query.get( 'before' ) ) );
}// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
app.get( '/api/messages', async ( req, res ) => {
const me = userOf( req );
const { room = '', before } = req.query;
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
return res.sendStatus( 403 );
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
res.json( await messagesOf( room, before ) );
} );// In your createServer(): GET /api/messages?room=chat:34:42, and &before=<id>.
if ( url.pathname === '/api/messages' ) {
const me = userOf( req );
const room = url.searchParams.get( 'room' ) ?? '';
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
res.writeHead( 403 );
return res.end();
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
const page = await messagesOf( room, url.searchParams.get( 'before' ) );
res.writeHead( 200, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( page ) );
}use Illuminate\Http\Request;
use WordPlus\Realtime\Laravel\Facades\Realtime;
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
Route::get( '/api/messages', function ( Request $request ) {
$room = (string) $request->query( 'room' );
// The room's own rule: whoever may be in the conversation may read it.
abort_unless( Realtime::mayJoin( $room, $request->user()->id ), 403 );
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as [ 'messages' => [ [ 'id', 'from', 'text', 'at', 'files', 'reactions' ] ], 'more' ].
return messages_of( $room, $request->query( 'before' ) );
} )->middleware( 'auth' );require __DIR__ . '/../../src/realtime.php';
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
$me = current_user_id();
$room = (string) ( $_GET['room'] ?? '' );
// The room's own rule: whoever may be in the conversation may read it.
if ( ! $me || ! $realtime->mayJoin( $room, $me ) ) {
http_response_code( 403 );
exit;
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as [ 'messages' => [ [ 'id', 'from', 'text', 'at', 'files', 'reactions' ] ], 'more' ].
header( 'Content-Type: application/json' );
echo json_encode( messages_of( $room, $_GET['before'] ?? null ) );from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden, JsonResponse
from .realtime import realtime
# In urls.py: path("api/messages", views.messages)
@login_required
def messages(request):
room = request.GET.get("room", "")
# The room's own rule: whoever may be in the conversation may read it.
if not realtime.may_join(room, request.user.id):
return HttpResponseForbidden()
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return JsonResponse(messages_of(room, request.GET.get("before")))from fastapi import Depends, HTTPException
from realtime import realtime
# GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
@app.get("/api/messages")
def messages(room: str, before: str | None = None, me: int = Depends(current_user_id)):
# The room's own rule: whoever may be in the conversation may read it.
if not me or not realtime.may_join(room, me):
raise HTTPException(403)
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return messages_of(room, before)from flask import abort, request, session
from realtime import realtime
# GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
@app.get("/api/messages")
def messages():
me = session.get("user_id")
room = request.args.get("room", "")
# The room's own rule: whoever may be in the conversation may read it.
if not me or not realtime.may_join(room, me):
abort(403)
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return messages_of(room, request.args.get("before"))// http.HandleFunc("GET /api/messages", messages)
func messages(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
room := r.URL.Query().Get("room")
// The room's own rule: whoever may be in the conversation may read it.
if allowed, _ := roomRule(room, me); me == "" || allowed == nil {
w.WriteHeader(403)
return
}
// Your own query: the newest 50, or the 50 before that id, oldest first.
list, more := messagesOf(room, r.URL.Query().Get("before"))
reply(w, map[string]any{"messages": list, "more": more})
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );{{-- The conversation from your route as it opens, and the page before as the reader scrolls up. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// The conversation from your route as it opens, and the page before as the reader scrolls up.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}// No ready-made chat on iOS: ask your route as the screen opens,
// and with before: as the reader scrolls up.
let page = try await api.messages(room: "chat:34:42", before: oldest?.id) // your own request
drawAll(page.messages)
// Back after more than the room keeps: some were missed, so ask your route again.
chat.on("error") { error, _ in if error["code"]?.string == "gap" { reload() } }// No ready-made chat on Android: ask your route as the screen opens,
// and with before = as the reader scrolls up.
val page = api.messages(room = "chat:34:42", before = oldest?.id) // your own request
drawAll(page.messages)
// Back after more than the room keeps: some were missed, so ask your route again.
chat.on("error") { error, _ -> if (error.jsonObject["code"]?.jsonPrimitive?.content == "gap") reload() }import { useEffect } from 'react';
import { useRoom } from '@wordplus/realtime/react';
// Your server, in full, as an app has no address of its own.
const API = 'https://app.example.com/api';
export function Conversation() {
// Back after more than the room keeps: some were missed, so ask your route again.
useRoom( 'chat:34:42', { error: ( e ) => e.code === 'gap' && reload() } );
// No ready-made chat in React Native: ask your route as the screen opens,
// and with &before= as the reader scrolls up.
useEffect( () => {
fetch( API + '/messages?room=chat:34:42', { headers: { Authorization: 'Bearer ' + session.token } } )
.then( ( answer ) => answer.json() )
.then( ( { messages } ) => drawAll( messages ) );
}, [] );
// draw them your way
}// No ready-made chat in Flutter: ask your route as the screen opens,
// and with before as the reader scrolls up.
final page = await api.messages(room: 'chat:34:42', before: oldest?.id); // your own request
drawAll(page.messages);סימוני קריאה ותגובות
הצ׳אט המוכן שולח את שניהם ומציג אותם. סימון קריאה הוא חולף: הוא מגיע לדפים הפתוחים עכשיו ומעדכן את הסימונים אצל השולח. תגובה מגיעה עם אישור, והווובהוק שלכם שומר אותה.
// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Each reaction, by the message and the person: an empty key takes it back.
$realtime->on( 'reaction', fn ( array $e ) => save_reaction( $e['data']['id'], $e['from'], $e['data']['key'] ) );
} );// Each reaction, by the message and the person: an empty key takes it back.
$realtime->on( 'reaction', fn ( array $e ) => save_reaction( $e['data']['id'], $e['from'], $e['data']['key'] ) );# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))// In your webhook route, beside the messages.
// Each reaction, by the message and the person: an empty key takes it back.
if event["type"] == "emit" && event["event"] == "reaction" {
data, _ := event["data"].(map[string]any)
saveReaction(data["id"], event["from"], data["key"])
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );'use client'; // in Next.js
import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
// draw them your way
}<script setup>
import { useRoom } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room.value?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
</script><script>
import { useRoom } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
</script>import { Component } from '@angular/core';
import { injectRoom } from '@wordplus/realtime/angular';
// provideRealtime() once, in your application's providers.
@Component( { selector: 'app-conversation', template: '<!-- your messages -->' } )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
this.chat.room()?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
react( id: string ) {
return this.chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
}
}// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on("message") { data, meta in
draw(meta.id, meta.from, data["text"]?.string ?? "")
chat.volatile.emit("read", ["id": .string(meta.id ?? "")])
}
// Ann has seen up to this one: tick it, and every message before it.
chat.on("read") { data, meta in markSeen(meta.from, data["id"]?.string ?? "") }
// One reaction each, by its code point: 👍, or "" to take it back.
_ = try await chat.emitWithAck("reaction", ["id": .string(messageId), "key": "1f44d"])// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on("message") { data, meta ->
draw(meta.id, meta.from, data.jsonObject["text"]?.jsonPrimitive?.content ?: "")
chat.volatile.emit("read", buildJsonObject { put("id", meta.id) })
}
// Ann has seen up to this one: tick it, and every message before it.
chat.on("read") { data, meta -> markSeen(meta.from, data.jsonObject["id"]?.jsonPrimitive?.content) }
// One reaction each, by its code point: 👍, or "" to take it back.
chat.emitWithAck("reaction", buildJsonObject { put("id", messageId); put("key", "1f44d") })import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages and apps open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
// draw them your way
}// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on('message', (data, meta) {
draw(meta.id, meta.from, data['text']);
chat.volatile.emit('read', {'id': meta.id});
});
// Ann has seen up to this one: tick it, and every message before it.
chat.on('read', (data, meta) => markSeen(meta.from, data['id']));
// One reaction each, by its code point: 👍, or '' to take it back.
await chat.emitWithAck('reaction', {'id': messageId, 'key': '1f44d'});שליחת קבצים
הצ׳אט שולח כל קובץ לנתיב שלכם, ששומר אותו באחסון שלכם, וההודעה נושאת רק את המיקום שלו. הקובץ לעולם לא נמצא אצלנו. שמרו עם הודעה רק את הקבצים שהנתיב שלכם קיבל עבור החדר שלה, ופתחו קובץ רק למי שנמצא בשיחה שלו.
// POST /api/files: a form of the file and the room, sent as the file is picked.
export async function POST( request: Request ) {
const me = await currentUserId();
const form = await request.formData();
const room = String( form.get( 'room' ) ?? '' );
const file = form.get( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! ( file instanceof File ) || ! await realtime.mayJoin( room, me ) ) {
return Response.json( { error: 'Not for this conversation.' }, { status: 403 } );
}
if ( file.size > 10_000_000 ) {
return Response.json( { error: 'Larger than 10 MB.' }, { status: 413 } );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
return Response.json( await saveFile( room, me, file ), { status: 201 } );
}// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// POST /api/files: a form of the file and the room, sent as the file is picked.
// upload is multer: multer( { limits: { fileSize: 10_000_000 } } )
app.post( '/api/files', upload.single( 'file' ), async ( req, res ) => {
const me = userOf( req );
const room = req.body.room ?? '';
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! req.file || ! await realtime.mayJoin( room, me ) ) {
return res.status( 403 ).json( { error: 'Not for this conversation.' } );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
res.status( 201 ).json( await saveFile( room, me, req.file ) );
} );// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// In your createServer(): POST /api/files, a form of the file and the room.
// import { Readable } from 'node:stream';
if ( url.pathname === '/api/files' && req.method === 'POST' ) {
const me = userOf( req );
const headers = { 'Content-Type': req.headers[ 'content-type' ] ?? '' };
const form = await new Response( Readable.toWeb( req ), { headers } ).formData();
const room = String( form.get( 'room' ) ?? '' );
const file = form.get( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! ( file instanceof File ) || ! await realtime.mayJoin( room, me ) ) {
res.writeHead( 403, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( { error: 'Not for this conversation.' } ) );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
res.writeHead( 201, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( await saveFile( room, me, file ) ) );
}// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// POST /api/files: a form of the file and the room, sent as the file is picked.
Route::post( '/api/files', function ( Request $request ) {
$room = (string) $request->input( 'room' );
$file = $request->file( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! $file || ! Realtime::mayJoin( $room, $request->user()->id ) ) {
return response()->json( [ 'error' => 'Not for this conversation.' ], 403 );
}
if ( $file->getSize() > 10_000_000 ) {
return response()->json( [ 'error' => 'Larger than 10 MB.' ], 413 );
}
// Your own storage: keep it, and answer [ 'id', 'url', 'name', 'type', 'size' ].
return response()->json( save_file( $room, $request->user()->id, $file ), 201 );
} )->middleware( 'auth' );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
$realtime->on( 'message', function ( array $e ) {
$files = files_of( $e['room'], array_column( $e['data']['files'] ?? [], 'id' ) );
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'], $files );
} );
} );require __DIR__ . '/../../src/realtime.php';
// POST /api/files: a form of the file and the room, sent as the file is picked.
header( 'Content-Type: application/json' );
$me = current_user_id();
$room = (string) ( $_POST['room'] ?? '' );
$file = $_FILES['file'] ?? null;
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! $me || ! $file || ! $realtime->mayJoin( $room, $me ) ) {
http_response_code( 403 );
exit( json_encode( [ 'error' => 'Not for this conversation.' ] ) );
}
if ( $file['size'] > 10_000_000 ) {
http_response_code( 413 );
exit( json_encode( [ 'error' => 'Larger than 10 MB.' ] ) );
}
// Your own storage: keep it, and answer [ 'id', 'url', 'name', 'type', 'size' ].
http_response_code( 201 );
echo json_encode( save_file( $room, $me, $file ) );// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
$realtime->on( 'message', function ( array $e ) {
$files = files_of( $e['room'], array_column( $e['data']['files'] ?? [], 'id' ) );
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'], $files );
} );# In urls.py: path("api/files", views.files)
@login_required
def files(request):
room = request.POST.get("room", "")
file = request.FILES.get("file")
# The room's own rule: whoever may be in the conversation may send it a file.
if file is None or not realtime.may_join(room, request.user.id):
return JsonResponse({"error": "Not for this conversation."}, status=403)
if file.size > 10_000_000:
return JsonResponse({"error": "Larger than 10 MB."}, status=413)
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return JsonResponse(save_file(room, request.user.id, file), status=201)# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)from fastapi import File, Form, UploadFile
from fastapi.responses import JSONResponse
# POST /api/files: a form of the file and the room, sent as the file is picked.
@app.post("/api/files")
def files(room: str = Form(...), file: UploadFile = File(...), me: int = Depends(current_user_id)):
# The room's own rule: whoever may be in the conversation may send it a file.
if not me or not realtime.may_join(room, me):
return JSONResponse({"error": "Not for this conversation."}, status_code=403)
if file.size and file.size > 10_000_000:
return JSONResponse({"error": "Larger than 10 MB."}, status_code=413)
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return JSONResponse(save_file(room, me, file), status_code=201)# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)# POST /api/files: a form of the file and the room, sent as the file is picked.
@app.post("/api/files")
def files():
me = session.get("user_id")
room = request.form.get("room", "")
file = request.files.get("file")
# The room's own rule: whoever may be in the conversation may send it a file.
if not me or file is None or not realtime.may_join(room, me):
return {"error": "Not for this conversation."}, 403
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return save_file(room, me, file), 201# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)// http.HandleFunc("POST /api/files", files)
func files(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
room := r.FormValue("room")
file, header, err := r.FormFile("file")
// The room's own rule: whoever may be in the conversation may send it a file.
if allowed, _ := roomRule(room, me); me == "" || err != nil || allowed == nil {
w.WriteHeader(403)
reply(w, map[string]string{"error": "Not for this conversation."})
return
}
defer file.Close()
// Your own storage: keep it, and answer {id, url, name, type, size}.
w.WriteHeader(201)
reply(w, saveFile(room, me, file, header))
}
// In your webhook route: the files with their message, those your route took
// for this room alone, as a page may write anything into a message of its own.
if event["type"] == "emit" && event["event"] == "message" {
data, _ := event["data"].(map[string]any)
files := filesOf(event["room"], data["files"])
saveMessage(event["event_id"], event["room"], event["from"], data["text"], event["at"], files)
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>{{-- Each file goes to your route as it is picked, and the message carries where it is. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// Each file goes to your route as it is picked, and the message carries where it is.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files"
accept="image/*,.pdf"
maxFileSize={ 10_000_000 } />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. Each file goes to your route as it is picked, and the message carries where it is. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- Each file goes to your route as it is picked, and the message carries where it is. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- Each file goes to your route as it is picked, and the message carries where it is. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}השתקה, הוצאה וחסימה
הכלל שלכם קורא את השורות שלכם, כך שהשתקה, הרחקה וחסימה הן שינוי בנתונים שלכם. ה-SDK שואל אז את הכלל שלכם שוב מיד, או מוציא מישהו עכשיו. הודעה שדווחה יוצאת ממסד הנתונים שלכם וממה שהחדר שומר.
// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
$realtime->room( 'chat:{pair}', fn ( $user, array $p ) => ! Block::where( [ 'by' => $p['other'], 'user' => $user ] )->exists(), $chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
$realtime->room( 'group:{id}', function ( $user, array $p ) {
$member = GroupMember::where( [ 'group_id' => $p['id'], 'user_id' => $user ] )->first();
if ( ! $member || $member->banned ) {
return false;
}
return $member->muted ? [ 'readOnly' => true ] : true;
}, [ ...$chat, 'presence' => true ] );
} );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
GroupMember::where( [ 'group_id' => 7, 'user_id' => 56 ] )->update( [ 'muted' => true ] );
Realtime::room( 'group:7' )->recheck( 56 );
// Out now. She is still a member, so she may come back.
Realtime::room( 'group:7' )->remove( 56 );
// Ban her: your rule says no from now on, then out now.
GroupMember::where( [ 'group_id' => 7, 'user_id' => 56 ] )->update( [ 'banned' => true ] );
Realtime::room( 'group:7' )->remove( 56 );
// Ann blocks Ben in their chat.
Block::create( [ 'by' => 34, 'user' => 42 ] );
Realtime::room( 'chat:34:42' )->remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
Message::whereKey( $eventId )->delete();
Realtime::room( 'group:7' )->forget( $eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
$realtime->room( 'chat:{pair}', fn ( $user, array $p ) => ! has_blocked( $p['other'], $user ), $chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
$realtime->room( 'group:{id}', function ( $user, array $p ) {
$member = member_of( $p['id'], $user );
if ( ! $member || $member['banned'] ) {
return false;
}
return $member['muted'] ? [ 'readOnly' => true ] : true;
}, [ ...$chat, 'presence' => true ] );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted( 7, 56, true );
$realtime->room( 'group:7' )->recheck( 56 );
// Out now. She is still a member, so she may come back.
$realtime->room( 'group:7' )->remove( 56 );
// Ban her: your rule says no from now on, then out now.
set_banned( 7, 56, true );
$realtime->room( 'group:7' )->remove( 56 );
// Ann blocks Ben in their chat.
block( 34, 42 );
$realtime->room( 'chat:34:42' )->remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
delete_message( $event_id );
$realtime->room( 'group:7' )->forget( $event_id );# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# In a def route, as these calls block.
# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)// In roomRule, the rows of your own: the one blocked by the other is kept out,
// a ban keeps them out of a group, and a mute lets them read alone.
if len(part) == 3 && part[0] == "chat" {
other := part[1]
if user == part[1] {
other = part[2]
}
if (user != part[1] && user != part[2]) || hasBlocked(other, user) {
return nil, "forbidden"
}
return &chat, ""
}
if len(part) == 2 && part[0] == "group" {
member := memberOf(part[1], user)
if member == nil || member.Banned {
return nil, "forbidden"
}
chat.Presence = true
chat.ReadOnly = member.Muted
return &chat, ""
}# Mute Cara: she reads on and sends nothing. recheck asks your rule again at once.
# In your database: UPDATE members SET muted = 1 WHERE group_id = 7 AND user_id = 56
wordplus POST /wordplus/realtime/rooms/group%3A7/recheck '{"user":"56"}'
# Out now. She is still a member, so she may come back.
wordplus POST /wordplus/realtime/rooms/group%3A7/kick '{"user":"56"}'
# Ban her: your rule says no from now on, then out now.
# In your database: UPDATE members SET banned = 1 WHERE group_id = 7 AND user_id = 56
wordplus POST /wordplus/realtime/rooms/group%3A7/kick '{"user":"56"}'
# Ann blocks Ben in their chat.
# In your database: INSERT INTO blocks (by_user, user_id) VALUES (34, 42)
wordplus POST /wordplus/realtime/rooms/chat%3A34%3A42/kick '{"user":"42"}'
# A message reported: out of your database, and out of what the room keeps.
# In your database: DELETE FROM messages WHERE id = '<its event id>'
wordplus DELETE "/wordplus/realtime/rooms/group%3A7/history?id=$EVENT_ID"שיחה מתוך הצ׳אט
עם נתיב לטוקן שלו, לצ׳אט יש כפתור לשיחת וידאו וכפתור לשיחה קולית, והשיחה מוצגת בצ׳אט, לצד ההודעות. הנתיב שלכם מאשר שיחה כששני האנשים נמצאים בשיחה.
// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
export async function GET( request: Request ) {
const me = await currentUserId();
const query = new URL( request.url ).searchParams;
const to = query.get( 'to' ) ?? '';
const name = query.get( 'name' ) ?? '';
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
return new Response( null, { status: 403 } );
}
// The call takes the chat's name, so it shows in the chat.
const type = query.get( 'type' ) === 'audio' ? 'audio' : 'video';
return Response.json( { token: await realtime.callToken( me, to, { type, name } ) } );
}// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
app.get( '/api/chat-call-token', async ( req, res ) => {
const me = userOf( req );
const { to = '', name = '' } = req.query;
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
return res.sendStatus( 403 );
}
// The call takes the chat's name, so it shows in the chat.
const type = req.query.type === 'audio' ? 'audio' : 'video';
res.json( { token: await realtime.callToken( me, to, { type, name } ) } );
} );// In your createServer(): GET /api/chat-call-token?to=34&type=video&name=chat:34:42.
if ( url.pathname === '/api/chat-call-token' ) {
const me = userOf( req );
const to = url.searchParams.get( 'to' ) ?? '';
const name = url.searchParams.get( 'name' ) ?? '';
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
res.writeHead( 403 );
return res.end();
}
// The call takes the chat's name, so it shows in the chat.
const type = url.searchParams.get( 'type' ) === 'audio' ? 'audio' : 'video';
const token = await realtime.callToken( me, to, { type, name } );
res.writeHead( 200, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( { token } ) );
}// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
Route::get( '/api/chat-call-token', function ( Request $request ) {
$me = $request->user()->id;
$to = (string) $request->query( 'to' );
$name = (string) $request->query( 'name' );
// Both in the conversation, as its room's own rule says. The name comes from the page.
abort_unless( Realtime::mayJoin( $name, $me ) && Realtime::mayJoin( $name, $to ), 403 );
// The call takes the chat's name, so it shows in the chat.
return [ 'token' => Realtime::callToken( $me, $to, [
'type' => $request->query( 'type' ) === 'audio' ? 'audio' : 'video',
'name' => $name,
] ) ];
} )->middleware( 'auth' );require __DIR__ . '/../../src/realtime.php';
// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
$me = current_user_id();
$to = (string) ( $_GET['to'] ?? '' );
$name = (string) ( $_GET['name'] ?? '' );
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! $me || ! $realtime->mayJoin( $name, $me ) || ! $realtime->mayJoin( $name, $to ) ) {
http_response_code( 403 );
exit;
}
// The call takes the chat's name, so it shows in the chat.
header( 'Content-Type: application/json' );
echo json_encode( [
'token' => $realtime->callToken( $me, $to, [
'type' => ( $_GET['type'] ?? '' ) === 'audio' ? 'audio' : 'video',
'name' => $name,
] ),
] );# In urls.py: path("api/chat-call-token", views.chat_call_token)
@login_required
def chat_call_token(request):
me = request.user.id
to = request.GET.get("to", "")
name = request.GET.get("name", "")
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not realtime.may_join(name, me) or not realtime.may_join(name, to):
return HttpResponseForbidden()
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if request.GET.get("type") == "audio" else "video"
return JsonResponse({"token": realtime.call_token(me, to, type=kind, name=name)})# GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
@app.get("/api/chat-call-token")
def chat_call_token(to: str, name: str, type: str = "video", me: int = Depends(current_user_id)):
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not me or not realtime.may_join(name, me) or not realtime.may_join(name, to):
raise HTTPException(403)
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if type == "audio" else "video"
return {"token": realtime.call_token(me, to, type=kind, name=name)}# GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
@app.get("/api/chat-call-token")
def chat_call_token():
me = session.get("user_id")
to = request.args.get("to", "")
name = request.args.get("name", "")
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not me or not realtime.may_join(name, me) or not realtime.may_join(name, to):
abort(403)
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if request.args.get("type") == "audio" else "video"
return {"token": realtime.call_token(me, to, type=kind, name=name)}// http.HandleFunc("GET /api/chat-call-token", chatCallToken)
func chatCallToken(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
to := r.URL.Query().Get("to")
name := r.URL.Query().Get("name")
// Both in the conversation, as its room's rule says. The name comes from the page.
mine, _ := roomRule(name, me)
theirs, _ := roomRule(name, to)
if me == "" || mine == nil || theirs == nil {
w.WriteHeader(403)
return
}
// The example's CallToken names no call of its own, so this call
// rings and opens in the call window, over the chat.
kind := r.URL.Query().Get("type")
reply(w, map[string]string{"token": app.CallToken(me, to, kind, profile(me))})
}Hooks ורכיבים לכל אפליקציית React, עם כל אחד מהשרתים למעלה.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>{{-- The call buttons on its bar ask your route, and the call shows in the chat. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
<script type="module">
// The chat and its calls: the ring and the call window too.
await window.Echo.connector.rt.callScreen();
</script>'use client'; // in Next.js
import { Chat, CallScreen } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// The call buttons on its bar ask your route, and the call shows in the chat.
export function Conversation() {
return (
<>
<CallScreen />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42"
tokenUrl="/api/chat-call-token" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat and its calls: the ring and the call window too.
watchEffect( () => rt.value?.callScreen() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. The call buttons on its bar ask your route, and the call shows in the chat. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat and its calls: the ring and the call window too.
$effect( () => { rt.current?.callScreen(); } );
</script>
<!-- The call buttons on its bar ask your route, and the call shows in the chat. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- The call buttons on its bar ask your route, and the call shows in the chat. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
}
}שיחה מתוך הצ׳אט היא שיחה בין שני אנשים: ה-API שלנו לשיחות וידאו כולל את כל מה ששיחה עושה.
צ׳אט בכל סטאק, עם כל ההגדרה:
איפה זה עובד
הצ׳אט המוכן בדפדפן, הצ׳אט שלכם בטלפונים
אותן שיחות מגיעות לדפדפן, ל-iOS ול-Android, דרך אותם חדרים. זה מה שיש לכל אחד.
בדפדפן
הצ׳אט המוכן, מי מחובר ומי מקליד, כאלמנטים לכל דף וכרכיבי React. או אותם אירועים במסך משלכם, עם כלי עזר ל-React, ל-Vue, ל-Svelte ול-Angular.
ב-iOS וב-Android
חדרים, הודעות, הקלדה, מי מחובר וההיסטוריה שהנתיב שלכם נותן, ב-Swift וב-Kotlin, עם מסכי שיחה מוכנים. אין מסך צ׳אט מוכן: האפליקציה שלכם מציירת מסך משלה, בעיצוב שלה, על אותם חדרים.
ב-React Native וב-Flutter
חדרים, הודעות, הקלדה ומי מחובר ב-iOS וב-Android, במסך צ׳אט שהאפליקציה שלכם מציירת.
בשרת שלכם
Node.js, PHP ו-Python, עם Laravel, Django, FastAPI ו-Flask, וה-API של HTTP לכל שפה אחרת: הכללים, הווובהוק, הודעות מהשרת שלכם והוצאה של מישהו משיחה.
שימושים
מה בונים עם צ׳אט
כל אחד מהם הוא אפליקציה שלמה בתיעוד, עם השרת שלה ב-Node.js, PHP ו-Python.
צ׳אט
שיחות בין שני אנשים ובקבוצות, עם הקלדה, סימוני קריאה ותגובות, שנשמרות במסד הנתונים שלכם.
צ׳אט למרקטפלייס
קונה שואל את המוכר על מודעה, המוכר מחובר או שרואים מתי היה מחובר לאחרונה, ומי שלא נמצא מקבל התראה או אימייל.
מוקד תמיכה עם נציגים
כל שיחה חדשה מגיעה לנציג במשמרת, האחרים קוראים יחד איתו, ונציג מתקשר ללקוח מתוך השיחה.
צ׳אט עם בינה מלאכותית, ואז אדם
עוזר שעונה בשיחה תוך כדי שהמודל שלכם כותב, ואדם מהתמיכה שממשיך באותו הצ׳אט.
מי מחובר ומי כאן
נקודה על כל אווטאר, האנשים בחדר עם התפקידים שלהם, וכמה אנשים צופים בדף.
צפייה משותפת
וידאו שמתנגן, נעצר וקופץ לכולם בבת אחת כמו אצל המארח, ולצדו צ׳אט ושיחה של כל החבורה.
מחירים
מחיר לפי חיבורים, אף פעם לא לפי הודעות
החל מ-$11.99 לחודש עבור 1,000 חיבורים בו-זמניים, בחיוב שנתי, או $14.99 בחיוב חודשי.
התמחור לפי חיבורים בו-זמניים, החל מ-1,000, בחיוב חודשי או שנתי. הודעות ורוחב פס אף פעם לא מחויבים, ומה שהשרת שלכם שולח לא משתמש באף אחד מהחיבורים שלכם.
אותה תוכנית ואותו SDK מביאים גם שיחות וידאו וגם שידור חי, על אותו חיבור.
שאלות
שאלות נפוצות
האם אתם שומרים את ההודעות שלנו?
לא. חדר שומר את האירועים האחרונים שלו כחמש דקות, רק כדי שדף שמתחבר מחדש לא יפספס דבר. השרת שלכם שומר את השיחה במסד הנתונים שלכם, מהווובהוק או מנתיב משלו, והצ׳אט טוען אותה מהנתיב שלכם כשהוא נפתח.
האם אני צריך שרת צ׳אט משלי?
לא. דפים שולחים זה לזה הודעות דרך השרתים שלנו, בלי בקשה לשרת שלכם, וכל מי שבשיחה מקבל אותן מיד, בכל כרטיסייה ובכל מכשיר. השרת שלכם קובע מי רשאי להיות בכל שיחה ושומר את מה שנשלח אליו.
האם יש צ׳אט מוכן?
כן, בדפדפן: שיחה עם הקלדה, סימוני קריאה, תגובות, קבצים ושיחות, כאלמנט לכל דף וכרכיב React, לצד רשימות של מי מחובר. אפליקציות iOS ו-Android מציירות מסך צ׳אט משלהן על אותם חדרים, עם הקלדה ומי מחובר.
באילו סטאקים אפשר להשתמש ב-SDK של הצ׳אט?
Next.js ו-Express, Laravel ו-PHP רגיל, Django, FastAPI ו-Flask, Capacitor, iOS ו-Android, לכל אחד מדריך. גם באפליקציות React Native ו-Flutter יש חדרים ונוכחות. שרת בכל שפה אחרת משתמש ב-HTTP API.
האם אתם יכולים לקרוא את ההודעות שלנו?
לא בשיחה פרטית. ההודעות שלה, ההיסטוריה שלה ומי נמצא בה עוברים חתומים במפתחות שהשרת שלכם יוצר, והענן מעביר אותם בלי יכולת לקרוא אותם. השרת שלכם פותח את מה שהווובהוק שלו מביא, כדי לשמור אותו.
מי מחליט מי רשאי לכתוב למי?
השרת שלכם, עם כלל לכל סוג שיחה שקורא את הנתונים שלכם: מי נמצא בה, מי רשאי רק לקרוא ומי נשאר בחוץ. הענן אוכף כל תשובה, והשרת שלכם יכול להוציא מישהו משיחה מיד.
האם אפשר לשלוח קבצים ותמונות?
כן. הצ׳אט שולח כל קובץ לנתיב שלכם, ששומר אותו באחסון שלכם, וההודעה נושאת רק את המיקום שלו, את השם, הסוג והגודל שלו. הקובץ לעולם לא נמצא בענן.
האם אפשר לבנות מסך צ׳אט משלי?
כן. הצ׳אט המוכן הוא אופציונלי. שנו את הצבעים והמילים שלו, או ציירו את השיחה בעצמכם על אותם אירועים, כך שהמסך שלכם והצ׳אט המוכן מדברים זה עם זה.
כמה עולה צ׳אט?
התמחור של צ׳אט לפי חיבורים בו-זמניים, החל מ-1,000, בחיוב חודשי או שנתי. הודעות, הקלדה, סימוני קריאה וקבצים אף פעם לא מחויבים, ומה שהשרת שלכם שולח לא משתמש באף אחד מהחיבורים שלכם.
שאלות על האינטגרציה שלכם? כתבו לנו: אנחנו עוזרים עם ה-SDK, מסך השיחה וה-stack שלכם.