WebSocket protocol
Build a custom chat UI or native mobile client using DGbot's real-time WebSocket protocol.
When to use WebSocket
Use the WebSocket API when:
- You're building a custom chat UI that doesn't use the DGbot widget
- You're building a native mobile app (iOS, Android, React Native)
- You need a server-side chat integration (e.g., handling chat in your own backend)
- You want to build a headless chatbot that triggers actions without UI
For standard website chat, use the widget embed — it handles the WebSocket internally.
Connection
Endpoint: wss://dgbot.dgtech.co.in/ws
Required query parameters:
| Parameter | Description |
|---|---|
key | Your chatbot ID (same as data-chatbot-id in the widget) |
visitor_id | A unique ID for the visitor session (UUID v4 recommended). Generate on first connect; persist per session. |
Example connection:
js
const visitorId = sessionStorage.getItem('dgbot_visitor_id')
|| crypto.randomUUID()
sessionStorage.setItem('dgbot_visitor_id', visitorId)
const ws = new WebSocket(
`wss://dgbot.dgtech.co.in/ws?key=YOUR_CHATBOT_ID&visitor_id=${visitorId}`
)
ws.onopen = () => console.log('Connected to DGbot')
ws.onclose = () => console.log('Disconnected')
ws.onerror = (err) => console.error('WebSocket error', err)Message types
Send a visitor message:
json
{
"type": "message",
"content": "What are your shipping times?"
}Ping (keep-alive):
json
{ "type": "ping" }Send a ping every 25–30 seconds to keep the connection alive.
Streaming responses
DGbot streams AI responses as a sequence of events. The message arrives in chunks:
json
{ "type": "stream_start", "message_id": "msg_abc123" }
{ "type": "stream_chunk", "message_id": "msg_abc123", "content": "Standard" }
{ "type": "stream_chunk", "message_id": "msg_abc123", "content": " shipping" }
{ "type": "stream_chunk", "message_id": "msg_abc123", "content": " takes 5–7" }
{ "type": "stream_chunk", "message_id": "msg_abc123", "content": " business days." }
{ "type": "stream_end", "message_id": "msg_abc123" }Concatenate chunks in order to assemble the full message. Render progressively for a real-time streaming UX.
Python example:
python
import asyncio, websockets, json
async def chat():
uri = "wss://dgbot.dgtech.co.in/ws?key=YOUR_ID&visitor_id=test_001"
async with websockets.connect(uri) as ws:
await ws.send(json.dumps({
"type": "message",
"content": "What are your shipping times?"
}))
response_parts = []
async for raw in ws:
event = json.loads(raw)
if event["type"] == "stream_chunk":
response_parts.append(event["content"])
print(event["content"], end="", flush=True)
elif event["type"] == "stream_end":
break
full_response = "".join(response_parts)
print("\n\nFull response:", full_response)
asyncio.run(chat())Events
Additional events you may receive:
| Type | When | Payload | |
|---|---|---|---|
tool_action | Bot is calling a tool | { tool: string, status: "calling" } | |
tool_action_result | Tool returned a result | `{ tool: string, status: "done" \ | "error" }` |
handoff_offered | Bot offers human handoff | { message: string } | |
agent_joined | Human agent joined the conversation | { agent_name: string } | |
agent_message | Human agent sent a message | { content: string, agent_name: string } | |
agent_left | Human agent left | — |
Example — show tool call indicator:
js
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
if (data.type === 'tool_action') {
showTypingIndicator(`Looking up ${data.tool}…`)
} else if (data.type === 'stream_start') {
hideTypingIndicator()
}
}