-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_app.py
More file actions
73 lines (55 loc) · 2.14 KB
/
websocket_app.py
File metadata and controls
73 lines (55 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Speech Echo - WebSocket example.
Listens for speech input and echoes it back to the caller.
Demonstrates actionHook event handling with session.on() and session.reply().
Usage:
python websocket_app.py
"""
import asyncio
from jambonz_sdk.websocket import create_endpoint
async def main():
make_service, server = await create_endpoint(port=3000)
svc = make_service(path="/")
async def handle_session(session):
print(f"Incoming call: {session.call_sid}")
# Register event handlers BEFORE sending verbs
session.on("close", lambda code, reason: print(f"Session closed: {code}"))
session.on("error", lambda err: print(f"Session error: {err}"))
async def handle_echo(evt):
reason = evt.get("reason", "")
if reason == "speechDetected":
transcript = (
evt.get("speech", {})
.get("alternatives", [{}])[0]
.get("transcript", "nothing")
)
session.say(text=f"You said: {transcript}.").gather(
input=["speech"],
actionHook="/echo",
timeout=10,
say={"text": "Please say something else."},
)
await session.reply()
elif reason == "timeout":
session.gather(
input=["speech"],
actionHook="/echo",
timeout=10,
say={"text": "Are you still there? I didn't hear anything."},
)
await session.reply()
else:
await session.reply()
session.on("/echo", handle_echo)
# Send initial verbs
session.pause(length=1).gather(
input=["speech"],
actionHook="/echo",
timeout=10,
say={"text": "Please say something and I will echo it back to you."},
)
await session.send()
svc.on("session:new", handle_session)
print("Speech echo WebSocket app listening on port 3000")
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())