Stream de Conversas
curl --request GET \
--url https://api.example.com/backend/conversations/streamimport requests
url = "https://api.example.com/backend/conversations/stream"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/backend/conversations/stream', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/backend/conversations/stream",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/backend/conversations/stream"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://api.example.com/backend/conversations/stream")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/backend/conversations/stream")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
response = http.request(request)
puts response.read_bodyConversas
Stream de Conversas
Conexão SSE para atualizações em tempo real
GET
/
backend
/
conversations
/
stream
Stream de Conversas
curl --request GET \
--url https://api.example.com/backend/conversations/streamimport requests
url = "https://api.example.com/backend/conversations/stream"
response = requests.get(url)
print(response.text)const options = {method: 'GET'};
fetch('https://api.example.com/backend/conversations/stream', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.example.com/backend/conversations/stream",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.example.com/backend/conversations/stream"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://api.example.com/backend/conversations/stream")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.example.com/backend/conversations/stream")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
response = http.request(request)
puts response.read_bodyVisão Geral
Use Server-Sent Events (SSE) para receber atualizações em tempo real das conversas. Ideal para dashboards e interfaces de chat.Este endpoint retorna um stream de eventos SSE, não uma resposta JSON tradicional.
Conectando
const eventSource = new EventSource(
'https://api.leavo.ai/backend/conversations/stream',
{
headers: {
'Authorization': 'Bearer sua_chave_aqui'
}
}
);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Nova atualização:', data);
};
eventSource.onerror = (error) => {
console.error('Erro no stream:', error);
};
Tipos de Eventos
new_message
Novo mensagem recebida ou enviada.
{
"type": "new_message",
"data": {
"lead_id": "uuid",
"message": {
"id": "uuid",
"content": "Olá!",
"role": "user",
"timestamp": "2024-01-15T10:30:00Z"
}
}
}
conversation_update
Atualização de status da conversa.
{
"type": "conversation_update",
"data": {
"lead_id": "uuid",
"is_ai_active": false,
"unread_count": 0
}
}
typing
Indicador de digitação.
{
"type": "typing",
"data": {
"lead_id": "uuid",
"is_typing": true
}
}
Exemplo Completo
class ConversationStream {
constructor(apiKey) {
this.apiKey = apiKey;
this.eventSource = null;
this.listeners = new Map();
}
connect() {
this.eventSource = new EventSource(
'https://api.leavo.ai/backend/conversations/stream',
{
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
}
);
this.eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
this.emit(data.type, data.data);
};
this.eventSource.onerror = (error) => {
console.error('Stream error:', error);
// Reconectar após 5 segundos
setTimeout(() => this.connect(), 5000);
};
}
on(eventType, callback) {
if (!this.listeners.has(eventType)) {
this.listeners.set(eventType, []);
}
this.listeners.get(eventType).push(callback);
}
emit(eventType, data) {
const callbacks = this.listeners.get(eventType) || [];
callbacks.forEach(cb => cb(data));
}
disconnect() {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
}
}
// Uso
const stream = new ConversationStream('sua_chave_aqui');
stream.on('new_message', (data) => {
console.log('Nova mensagem de', data.lead_id);
updateChatUI(data.message);
});
stream.on('typing', (data) => {
showTypingIndicator(data.lead_id, data.is_typing);
});
stream.connect();
Considerações
Reconexão
Implemente lógica de reconexão automática em caso de desconexão.
Heartbeat
O servidor envia eventos de heartbeat a cada 30 segundos para manter a conexão ativa.
Filtros
Use query parameters para filtrar eventos por canal ou lead específico.
Autenticação
O token é validado na conexão inicial. Conexões com token inválido são rejeitadas.