WebSocket protocol

Build a custom chat UI or native mobile client using DGbot's real-time WebSocket protocol.

~20 minutes Starter

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:

ParameterDescription
keyYour chatbot ID (same as data-chatbot-id in the widget)
visitor_idA 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:

TypeWhenPayload
tool_actionBot is calling a tool{ tool: string, status: "calling" }
tool_action_resultTool returned a result`{ tool: string, status: "done" \"error" }`
handoff_offeredBot offers human handoff{ message: string }
agent_joinedHuman agent joined the conversation{ agent_name: string }
agent_messageHuman agent sent a message{ content: string, agent_name: string }
agent_leftHuman 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()
  }
}