Pubblicare eventi
Pubblica dal tuo server usando la chiave Bird API e la chiave e il segreto dell'app Realtime. Non includere mai il segreto dell'app nel codice client. Per consentire ai client iscritti di scambiarsi segnali temporanei, usa gli eventi client sui canali private o presence.
Una pubblicazione minimale
Un evento richiede un nome e almeno un canale. Il payload opzionale può contenere qualsiasi oggetto, array o scalare JSON.
import { BirdClient } from "@messagebird/sdk";
const bird = new BirdClient({
apiKey: process.env.BIRD_API_KEY,
realtime: {
key: process.env.BIRD_REALTIME_KEY,
secret: process.env.BIRD_REALTIME_SECRET,
},
});
await bird.realtime.publish("rap_01krdgeqcxet5s7t44vh8rt9mg", {
event: "order-updated",
channels: ["orders"],
data: { id: 42, status: "shipped" },
});import os
from bird import Bird
client = Bird(
api_key=os.environ["BIRD_API_KEY"],
realtime_key=os.environ["BIRD_REALTIME_KEY"],
realtime_secret=os.environ["BIRD_REALTIME_SECRET"],
)
client.realtime.publish(
"rap_01krdgeqcxet5s7t44vh8rt9mg",
event="order-updated",
channels=["orders"],
data={"id": 42, "status": "shipped"},
)client, err := bird.NewClient(
option.WithAPIKey(os.Getenv("BIRD_API_KEY")),
option.WithRealtimeCredentials(os.Getenv("BIRD_REALTIME_KEY"), os.Getenv("BIRD_REALTIME_SECRET")),
)
if err != nil {
log.Fatal(err)
}
_, err = client.Realtime.Publish(context.Background(), "rap_01krdgeqcxet5s7t44vh8rt9mg", bird.RealtimePublishParams{
Event: "order-updated",
Channels: []string{"orders"},
Data: map[string]any{"id": 42, "status": "shipped"},
})use MessageBird\Bird;
use MessageBird\RealtimeOptions;
use MessageBird\Wire\Model\RealtimePublish;
$bird = new Bird(
getenv('BIRD_API_KEY') ?: '',
realtime: new RealtimeOptions(
key: getenv('BIRD_REALTIME_KEY') ?: '',
secret: getenv('BIRD_REALTIME_SECRET') ?: '',
),
);
$bird->realtime->publish('rap_01krdgeqcxet5s7t44vh8rt9mg', (new RealtimePublish())
->setEvent('order-updated')
->setChannels(['orders'])
->setData(['id' => 42, 'status' => 'shipped']));curl -X POST https://us1.platform.bird.com/v1/realtime/apps/rap_01krdgeqcxet5s7t44vh8rt9mg/events \
-H "Authorization: Bearer $BIRD_API_KEY" \
-H "X-Realtime-Key: $BIRD_REALTIME_KEY" \
-H "X-Realtime-Secret: $BIRD_REALTIME_SECRET" \
-H "Content-Type: application/json" \
-d '{
"event": "order-updated",
"channels": ["orders"],
"data": { "id": 42, "status": "shipped" }
}'I client associati a order-updated su orders ricevono l'evento. Il API rifiuta i nomi pubblicati dal server che iniziano con i prefissi di protocollo bird: o bird_internal:. I nomi degli eventi originati dal client devono iniziare con client-.
La richiesta e la risposta complete, con tutti i campi, si trovano nel riferimento pubblicare un evento.
Cosa significa un 200
La pubblicazione si completa quando l'edge Realtime accetta l'evento. La consegna è asincrona e non prevede conferma per singolo client. Un client che si disconnette durante la consegna può perdere l'evento, e Realtime non lo riproduce dopo la riconnessione.
Salva lo stato durevole nel tuo database. Usa gli eventi per annunciare i cambiamenti, poi fai ricaricare ai client lo stato corrente dopo la riconnessione.
Broadcast verso più canali
Una singola chiamata può inviare lo stesso evento a un massimo di 100 canali. Un canale private-encrypted- deve essere l'unico canale nella sua pubblicazione, perché ogni canale crittografato usa una chiave diversa. Il API rifiuta un fan-out crittografato con E23000. Vedi Canali crittografati.
await bird.realtime.publish(appId, {
event: "price-changed",
channels: ["ticker-btc", "ticker-eth", "ticker-sol"],
data: { at: "2026-07-31T09:00:00Z" },
});client.realtime.publish(
app_id,
event="price-changed",
channels=["ticker-btc", "ticker-eth", "ticker-sol"],
data={"at": "2026-07-31T09:00:00Z"},
)_, err := client.Realtime.Publish(context.Background(), appID, bird.RealtimePublishParams{
Event: "price-changed",
Channels: []string{"ticker-btc", "ticker-eth", "ticker-sol"},
Data: map[string]any{"at": "2026-07-31T09:00:00Z"},
})$bird->realtime->publish($appId, (new RealtimePublish())
->setEvent('price-changed')
->setChannels(['ticker-btc', 'ticker-eth', 'ticker-sol'])
->setData(['at' => '2026-07-31T09:00:00Z']));curl -X POST "https://us1.platform.bird.com/v1/realtime/apps/$APP_ID/events" \
-H "Authorization: Bearer $BIRD_API_KEY" \
-H "X-Realtime-Key: $BIRD_REALTIME_KEY" \
-H "X-Realtime-Secret: $BIRD_REALTIME_SECRET" \
-H "Content-Type: application/json" \
-d '{
"event": "price-changed",
"channels": ["ticker-btc", "ticker-eth", "ticker-sol"],
"data": { "at": "2026-07-31T09:00:00Z" }
}'Ogni canale di destinazione conta come un messaggio separato ai fini dell'utilizzo. Questo esempio conta come tre messaggi. Una pubblicazione verso 10.000 canali per utente conta quindi come 10.000 messaggi.
Raggruppare eventi non correlati in batch
Un broadcast invia un evento a molti canali. Un batch invia fino a 10 eventi diversi, ciascuno verso un canale, in un'unica richiesta.
await bird.realtime.publishBatch(appId, {
events: [
{ event: "order-updated", channels: ["orders-42"], data: { status: "shipped" } },
{ event: "stock-changed", channels: ["inventory-99"], data: { left: 3 } },
],
});client.realtime.publish_batch(
app_id,
events=[
{"event": "order-updated", "channels": ["orders-42"], "data": {"status": "shipped"}},
{"event": "stock-changed", "channels": ["inventory-99"], "data": {"left": 3}},
],
)_, err := client.Realtime.PublishBatch(context.Background(), appID, bird.RealtimePublishBatchParams{
Events: []bird.RealtimeBatchEventParams{
{Event: "order-updated", Channel: "orders-42", Data: map[string]any{"status": "shipped"}},
{Event: "stock-changed", Channel: "inventory-99", Data: map[string]any{"left": 3}},
},
})$bird->realtime->publishBatch($appId, (new RealtimeBatchPublish())
->setEvents([
(new RealtimeBatchEvent())->setEvent('order-updated')->setChannel('orders-42')->setData(['status' => 'shipped']),
(new RealtimeBatchEvent())->setEvent('stock-changed')->setChannel('inventory-99')->setData(['left' => 3]),
]));curl -X POST "https://us1.platform.bird.com/v1/realtime/apps/$APP_ID/batch-events" \
-H "Authorization: Bearer $BIRD_API_KEY" \
-H "X-Realtime-Key: $BIRD_REALTIME_KEY" \
-H "X-Realtime-Secret: $BIRD_REALTIME_SECRET" \
-H "Content-Type: application/json" \
-d '{
"events": [
{ "event": "order-updated", "channel": "orders-42", "data": { "status": "shipped" } },
{ "event": "stock-changed", "channel": "inventory-99", "data": { "left": 3 } }
]
}'Usa un batch per combinare aggiornamenti non correlati in un'unica richiesta. Ogni evento conta comunque separatamente ai fini dell'utilizzo, e un batch accetta al massimo 10 eventi. Vedi Pubblicare un batch.
Escludere il client che ha agito
Se un client ha già applicato la sua azione localmente, passa il suo ID di connessione per impedire che la pubblicazione risultante applichi di nuovo la stessa modifica. L'edge esclude solo quella connessione.
await bird.realtime.publish(appId, {
event: "message.created",
channels: ["presence-room-1"],
data: { body: "hello" },
exclude_connection_id: "26896.319537",
});client.realtime.publish(
app_id,
event="message.created",
channels=["presence-room-1"],
data={"body": "hello"},
exclude_connection_id="26896.319537",
)_, err := client.Realtime.Publish(context.Background(), appID, bird.RealtimePublishParams{
Event: "message.created",
Channels: []string{"presence-room-1"},
Data: map[string]any{"body": "hello"},
ExcludeConnectionID: "26896.319537",
})$bird->realtime->publish($appId, (new RealtimePublish())
->setEvent('message.created')
->setChannels(['presence-room-1'])
->setData(['body' => 'hello'])
->setExcludeConnectionId('26896.319537'));curl -X POST "https://us1.platform.bird.com/v1/realtime/apps/$APP_ID/events" \
-H "Authorization: Bearer $BIRD_API_KEY" \
-H "X-Realtime-Key: $BIRD_REALTIME_KEY" \
-H "X-Realtime-Secret: $BIRD_REALTIME_SECRET" \
-H "Content-Type: application/json" \
-d '{
"event": "message.created",
"channels": ["presence-room-1"],
"data": { "body": "hello" },
"exclude_connection_id": "26896.319537"
}'Leggi l'ID dalla connessione corrente del client e includilo nella richiesta che attiva la modifica. Le altre schede usano connessioni separate e continuano a ricevere l'evento.
Leggere lo stato del canale durante la pubblicazione
Usa include per ottenere lo stato di ogni canale di destinazione al momento della pubblicazione ed evitare una richiesta separata per lo stato del canale:
const result = await bird.realtime.publish(appId, {
event: "order-updated",
channels: ["presence-lobby"],
data: { id: 42 },
include: ["member_count", "connection_count"],
});result = client.realtime.publish(
app_id,
event="order-updated",
channels=["presence-lobby"],
data={"id": 42},
include=["member_count", "connection_count"],
)result, err := client.Realtime.Publish(context.Background(), appID, bird.RealtimePublishParams{
Event: "order-updated",
Channels: []string{"presence-lobby"},
Data: map[string]any{"id": 42},
Include: []bird.RealtimeChannelInclude{bird.RealtimeIncludeMemberCount, bird.RealtimeIncludeConnectionCount},
})$result = $bird->realtime->publish($appId, (new RealtimePublish())
->setEvent('order-updated')
->setChannels(['presence-lobby'])
->setData(['id' => 42])
->setInclude(['member_count', 'connection_count']));curl -X POST "https://us1.platform.bird.com/v1/realtime/apps/$APP_ID/events" \
-H "Authorization: Bearer $BIRD_API_KEY" \
-H "X-Realtime-Key: $BIRD_REALTIME_KEY" \
-H "X-Realtime-Secret: $BIRD_REALTIME_SECRET" \
-H "Content-Type: application/json" \
-d '{
"event": "order-updated",
"channels": ["presence-lobby"],
"data": { "id": 42 },
"include": ["member_count", "connection_count"]
}'member_count funziona solo sui canali presence. connection_count richiede il conteggio delle connessioni sull'app. Richiedere questi attributi conta come un messaggio aggiuntivo ai fini dell'utilizzo.
Limiti
| Limite | Valore |
|---|---|
| Canali per pubblicazione | 100 |
| Eventi per batch | 10 |
| Payload dell'evento | 10 KB serializzati |
| Nome del canale | 164 caratteri, lettere, cifre e _ - = @ , . ; |
| Nome dell'evento | 200 caratteri |
Superare qualsiasi limite restituisce un errore di validazione. Il API non tronca la richiesta.
Riprovare in sicurezza
Riprova una pubblicazione con lo stesso Idempotency-Key per evitare consegne duplicate. Gli SDK TypeScript e Go generano una chiave e la riutilizzano per i tentativi automatici. Se la tua applicazione riprova una richiesta, fornisci e riutilizza una chiave propria. Vedi Idempotenza.
Prossimi passi
- Autorizzare i canali è ciò di cui un canale private- o presence- ha bisogno prima che un client possa iscriversi.
- Panoramica di Realtime spiega canali, membri e connessioni, e dove compare l'utilizzo.
- Escludere i destinatari degli eventi impedisce al client che ha agito di ricevere la propria modifica.
Risorse correlate
Prosegui con la documentazione, le guide e gli esempi per questo argomento. Le risorse sono in inglese.
Esplora la funzionalitàRealtimeSegui il percorso di apprendimentoBuild your first integrationGuida all'implementazioneSend your first realtime event
Prova l'esercitazione e ottieni un brief di implementazione