Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Global rule:
* @Bandwidth-samples/band-swi @Bandwidth-samples/band-swi-github-repo-admin
* @Bandwidth-Samples/band-swi @Bandwidth-Samples/band-devx
19 changes: 19 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
version: 2

updates:
- package-ecosystem: pip
directory: /
schedule:
interval: monthly
open-pull-requests-limit: 5
ignore:
- dependency-name: "bandwidth-sdk"
update-types:
- version-update:semver-minor
- version-update:semver-patch
groups:
dependencies:
patterns:
- "*"
exclude-patterns:
- "bandwidth-sdk"
15 changes: 15 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: Test

on:
pull_request:
branches:
- main
schedule:
- cron: "0 9 * * 1"

jobs:
contract-test:
name: Contract Test
uses: Bandwidth-Samples/sample-app-tooling/.github/workflows/python.yml@main
with:
sample: voice-bridge
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2020 Bandwidth Samples
Copyright (c) 2026 Bandwidth Samples

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
14 changes: 0 additions & 14 deletions Pipfile

This file was deleted.

482 changes: 0 additions & 482 deletions Pipfile.lock

This file was deleted.

30 changes: 15 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Voice Gather
# Voice Bridge

<a href="https://dev.bandwidth.com/docs/voice/quickStart">
<a href="https://dev.bandwidth.com/docs/voice/programmable-voice/quickStart/">
<img src="./icon-voice.svg" title="Voice Quick Start Guide" alt="Voice Quick Start Guide"/>
</a>

Expand All @@ -17,7 +17,7 @@

This sample app masks a phone call through a Bandwidth phone number using Bandwidth's Bridge BXML verb. Once configured, anyone who calls your Bandwidth phone number will be bridged to the masked number without either party members knowing the other's phone number.

In the Bandwidth Dashboard, set the Application's `Call initiated callback URL` to `<BASE_CALLBACK_URL>/callbacks/inboundCall`. This can also be done via the Dashboard API by setting `CallInitiatedCallbackUrl`. Once configured, any calls made to a number associated with that application will cause this app to create a new call to the `USER_NUMBER`. This call will come from your `BW_NUMBER` and the original call will be bridged to this one once accepted.
In the Bandwidth Dashboard, set the Application's `Call initiated callback URL` to `<BASE_CALLBACK_URL>/callbacks/inbound/voice`. This can also be done via the Dashboard API by setting `CallInitiatedCallbackUrl`. Once configured, any calls made to a number associated with that application will cause this app to create a new call to the `USER_NUMBER`. This call will come from your `BW_NUMBER` and the original call will be bridged to this one once accepted.

Once the callee at `USER_NUMBER` confirms the call, the call flow will appear as such:

Expand Down Expand Up @@ -52,30 +52,30 @@ python main.py
The sample app uses the below environmental variables.

```sh
BW_ACCOUNT_ID # Your Bandwidth Account Id
BW_USERNAME # Your Bandwidth API Username
BW_PASSWORD # Your Bandwidth API Password
BW_NUMBER # Your Bandwidth Phone Number
USER_NUMBER # The phone number to be called with this application
BW_VOICE_APPLICATION_ID # Your Voice Application Id created in the dashboard
BASE_CALLBACK_URL # Your public base url
LOCAL_PORT # The port number you wish to run the sample on
BW_ACCOUNT_ID # Your Bandwidth Account Id
BW_CLIENT_ID # Your Bandwidth API OAuth Client Id
BW_CLIENT_SECRET # Your Bandwidth API OAuth Client Secret
BW_NUMBER # The Bandwidth phone number involved with this application
USER_NUMBER # The phone number to be called with this application
BW_VOICE_APPLICATION_ID # Your Voice Application Id created in the dashboard
BASE_CALLBACK_URL # Your public base url to receive Bandwidth Webhooks. No trailing '/'
LOCAL_PORT # The port number you wish to run the sample on
```

# Callback URLs

For a detailed introduction, check out our [Bandwidth Voice Callbacks](https://dev.bandwidth.com/docs/voice/quickStart#configuring-callback-urls) page.
For a detailed introduction, check out our [Bandwidth Voice Callbacks](https://dev.bandwidth.com/docs/voice/webhooks) page.

Below are the callback paths:
* `/callbacks/inboundCall`
* `/callbacks/outboundCall`
* `/callbacks/outbound/voice`
* `/callbacks/inbound/voice`

## Ngrok

A simple way to set up a local callback URL for testing is to use the free tool [ngrok](https://ngrok.com/).
After you have downloaded and installed `ngrok` run the following command to open a public tunnel to your port (`$LOCAL_PORT`)

```cmd
```sh
ngrok http $LOCAL_PORT
```

Expand Down
20 changes: 10 additions & 10 deletions icon-voice.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 44 additions & 27 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@

import bandwidth
from bandwidth.models.bxml import Response as BxmlResponse
from bandwidth.models.bxml import SpeakSentence, Ring, Bridge
from bandwidth.models.bxml import SpeakSentence, Ring, Bridge, Hangup
from fastapi import FastAPI, Response
from fastapi.exceptions import RequestValidationError
import uvicorn

try:
BW_USERNAME = os.environ['BW_USERNAME']
BW_PASSWORD = os.environ['BW_PASSWORD']
BW_ACCOUNT_ID = os.environ['BW_ACCOUNT_ID']
BW_CLIENT_ID = os.environ['BW_CLIENT_ID']
BW_CLIENT_SECRET = os.environ['BW_CLIENT_SECRET']
BW_VOICE_APPLICATION_ID = os.environ['BW_VOICE_APPLICATION_ID']
BW_NUMBER = os.environ['BW_NUMBER']
USER_NUMBER = os.environ['USER_NUMBER']
LOCAL_PORT = int(os.environ['LOCAL_PORT'])
BASE_CALLBACK_URL = os.environ['BASE_CALLBACK_URL']
LOCAL_PORT = int(os.environ['LOCAL_PORT'])
except KeyError as e:
print(f"Please set the environmental variables defined in the README\n\n{e}")
sys.exit(1)
Expand All @@ -27,44 +28,60 @@
app = FastAPI()

bandwidth_configuration = bandwidth.Configuration(
username=BW_USERNAME,
password=BW_PASSWORD
client_id=BW_CLIENT_ID,
client_secret=BW_CLIENT_SECRET
)

bandwidth_api_client = bandwidth.ApiClient(bandwidth_configuration)
bandwidth_calls_api_instance = bandwidth.CallsApi(bandwidth_api_client)


@app.post('/callbacks/inboundCall', status_code=http.HTTPStatus.OK)
def inbound_call(inbound_callback: bandwidth.models.AnswerCallback):
call_body = bandwidth.models.CreateCall(
to=USER_NUMBER,
from_=BW_NUMBER,
answer_url=f"{BASE_CALLBACK_URL}/callbacks/outboundCall",
@app.exception_handler(RequestValidationError)
def invalid_request(request, exc):
return Response(status_code=http.HTTPStatus.BAD_REQUEST)


@app.post("/callbacks/inbound/voice", status_code=http.HTTPStatus.OK)
def inbound_voice(initiate_callback: bandwidth.models.InitiateCallback):
if initiate_callback.event_type != "initiate":
print(f"Unexpected event type {initiate_callback.event_type} received")
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

create_call_body = bandwidth.CreateCall(
application_id=BW_VOICE_APPLICATION_ID,
tag=inbound_callback.call_id
to=USER_NUMBER,
var_from=BW_NUMBER,
answer_url=f"{BASE_CALLBACK_URL}/callbacks/outbound/voice",
tag=initiate_callback.call_id
)

try:
bandwidth_calls_api_instance.create_call(BW_ACCOUNT_ID, call_body=call_body)
except bandwidth.ApiException as e:
print(f"Error creating call: {e}")
bandwidth_calls_api_instance.create_call(BW_ACCOUNT_ID, create_call_body)
bxml = BxmlResponse([SpeakSentence(text="Hold while we connect you."), Ring(duration=30)])
except Exception as e:
print(f"Failed to create call: {e}")
bxml = BxmlResponse([SpeakSentence(text="An error occurred. Ending call."), Hangup()])

speak_sentence = SpeakSentence(text="Hold while we connect you.")
ring = Ring(duration=30)
bxml_response = BxmlResponse([speak_sentence, ring])
return Response(content=bxml.to_bxml(), media_type="application/xml")

return Response(content=bxml_response.to_bxml(), media_type="application/xml")

@app.post("/callbacks/outbound/voice", status_code=http.HTTPStatus.OK)
def outbound_voice(answer_callback: bandwidth.models.AnswerCallback):
bxml = BxmlResponse()

@app.post('/callbacks/outboundCall', status_code=http.HTTPStatus.OK)
def outbound_call(inbound_callback: bandwidth.models.AnswerCallback):
speak_sentence = SpeakSentence(text="Hold while we connect you. We will begin to bridge you now.")
bridge = Bridge(target_call=inbound_callback.tag)
bxml_response = BxmlResponse([speak_sentence, bridge])
match answer_callback.event_type:
case "answer":
speak_sentence = SpeakSentence(text="Hold while we connect you. We will begin to bridge you now.")
bridge = Bridge(target_call=answer_callback.tag)
bxml.add_verb(speak_sentence)
bxml.add_verb(bridge)
case "disconnect":
print(f"Call {answer_callback.call_id} has disconnected")
case _:
print(f"Unexpected event type {answer_callback.event_type} received")

return Response(content=bxml_response.to_bxml(), media_type="application/xml")
return Response(content=bxml.to_bxml(), media_type="application/xml")


if __name__ == '__main__':
if __name__ == "__main__":
uvicorn.run("main:app", port=LOCAL_PORT, reload=True)
41 changes: 18 additions & 23 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
-i https://pypi.org/simple
aenum==3.1.15
anyio==4.2.0 ; python_version >= '3.8'
bandwidth-sdk==15.0.1
click==8.1.7 ; python_version >= '3.7'
fastapi==0.108.0
h11==0.14.0 ; python_version >= '3.7'
httptools==0.6.1
idna==3.6 ; python_version >= '3.5'
pydantic==1.10.13 ; python_version >= '3.7'
python-dateutil==2.8.2 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
python-dotenv==1.0.0
pyyaml==6.0.1
setuptools==69.0.3 ; python_version >= '3.8'
six==1.16.0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
sniffio==1.3.0 ; python_version >= '3.7'
starlette==0.32.0.post1 ; python_version >= '3.8'
typing-extensions==4.9.0 ; python_version >= '3.8'
urllib3==2.0.7 ; python_version >= '3.7'
uvicorn[standard]==0.25.0
uvloop==0.19.0
watchfiles==0.21.0
websockets==12.0
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
bandwidth-sdk==23.3.1
click==8.5.0
fastapi==0.143.3
h11==0.16.0
idna==3.20
opentelemetry-api==1.45.1
pydantic==2.14.1
pydantic_core==2.50.1
python-dateutil==2.9.0.post0
six==1.17.0
starlette==1.8.0
typing-inspection==0.4.4
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.54.0
Loading