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-redirect-loop
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
15 changes: 0 additions & 15 deletions Pipfile

This file was deleted.

490 changes: 0 additions & 490 deletions Pipfile.lock

This file was deleted.

26 changes: 13 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Voice Redirect Loop

<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 @@ -16,9 +16,9 @@
# Description
This sample app indefinitely redirects an inbound call to itself until an interruption is sent to end the call.

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, inbound calls to your `BW_NUMBER` will be redirected every 30 seconds and ring indefinitely. The `callId` of the inbound call is saved to an `active_calls` array, which can be accessed via a GET request to the `/calls` endpoint provided by the app.
In the Bandwidth Dashboard, set the Application's `Call initiated callback URL` to `<BASE_CALLBACK_URL>/callbacks/inbound/voice`. Also set the `Call status callback URL` to `<BASE_CALLBACK_URL>/callbacks/inbound/voice/disconnect` so calls that hang up on their own are removed from the active list. These can also be done via the Dashboard API by setting `CallInitiatedCallbackUrl` and `CallStatusCallbackUrl`. Once configured, inbound calls to a number associated with that application will be redirected every 30 seconds and ring indefinitely. The `callId` of the inbound call is saved to a list of active calls, which can be accessed via a GET request to the `/calls` endpoint provided by the app.

To stop a call, make a DELETE request to the `/calls/{callId}` endpoint, replacing `{callId}` with that of the call you wish to end. This endpoint will redirect the call to the `/callbacks/callEnded` endpoint, which breaks the redirect loop and speaks a sentence to let you know the call has been ended before hanging up.
To stop a call, make a DELETE request to the `/calls/{callId}` endpoint, replacing `{callId}` with that of the call you wish to end. This endpoint will redirect the call to the `/callbacks/inbound/voice/callEnded` endpoint, which breaks the redirect loop and speaks a sentence to let you know the call has been ended before hanging up.

# Pre-Requisites

Expand Down Expand Up @@ -46,28 +46,28 @@ 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_VOICE_APPLICATION_ID # Your Voice Application Id created in the dashboard
LOCAL_PORT # The port number you wish to run the sample on
BASE_CALLBACK_URL # The public base url
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
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/callEnded`
* `/callbacks/inbound/voice`
* `/callbacks/inbound/voice/callEnded`
* `/callbacks/inbound/voice/disconnect`

## 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.
102 changes: 58 additions & 44 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import http
import json
import os
import sys
from typing import Union

import bandwidth
from bandwidth.models.bxml import Response as BxmlResponse
from bandwidth.models.bxml import SpeakSentence, Hangup, Ring, Redirect
from fastapi import FastAPI, Response
from typing import Union
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_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'])
BW_CLIENT_ID = os.environ['BW_CLIENT_ID']
BW_CLIENT_SECRET = os.environ['BW_CLIENT_SECRET']
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 @@ -29,62 +26,79 @@
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)

active_calls = []
active_calls = set()


@app.exception_handler(RequestValidationError)
def invalid_request(request, exc):
return Response(status_code=http.HTTPStatus.BAD_REQUEST)


@app.post('/callbacks/inboundCall', status_code=http.HTTPStatus.OK)
def inbound(callback: Union[bandwidth.models.InitiateCallback, bandwidth.models.RedirectCallback]):
if callback.event_type == "initiate" or callback.event_type == "redirect":
active_calls.append(callback.call_id)
@app.post("/callbacks/inbound/voice", status_code=http.HTTPStatus.OK)
def inbound_voice(callback: Union[bandwidth.models.InitiateCallback, bandwidth.models.RedirectCallback]):
if callback.event_type not in ("initiate", "redirect"):
print(f"Unexpected event type {callback.event_type} received")
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

speak_sentence = SpeakSentence(text="Redirecting call, please wait.")
ring = Ring(duration=30)
redirect = Redirect(redirect_url="/callbacks/redirectedCall")
bxml = BxmlResponse([speak_sentence, ring, redirect])
if callback.event_type == "initiate":
active_calls.add(callback.call_id)

return Response(content=bxml.to_bxml(), media_type="application/xml")
else:
speak_sentence = SpeakSentence(text="Invalid event. Hanging up")
hangup = Hangup()
bxml = BxmlResponse([speak_sentence, hangup])
speak_sentence = SpeakSentence(text="Redirecting call, please wait.")
ring = Ring(duration=30)
redirect = Redirect(redirect_url="/callbacks/inbound/voice")
bxml = BxmlResponse([speak_sentence, ring, redirect])

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


@app.post('/callbacks/callEnded', status_code=http.HTTPStatus.OK)
def goodbye():
speak_sentence = SpeakSentence(text="The call has been ended. Goodbye.")
hangup = Hangup()
bxml = BxmlResponse([speak_sentence, hangup])
@app.post("/callbacks/inbound/voice/callEnded", status_code=http.HTTPStatus.OK)
def call_ended(redirect_callback: bandwidth.models.RedirectCallback):
if redirect_callback.event_type != "redirect":
print(f"Unexpected event type {redirect_callback.event_type} received")
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

bxml = BxmlResponse([SpeakSentence(text="The call has been ended. Goodbye."), Hangup()])
return Response(content=bxml.to_bxml(), media_type="application/xml")


@app.delete('/calls/{call_id}', status_code=http.HTTPStatus.NO_CONTENT)
@app.post("/callbacks/inbound/voice/disconnect", status_code=http.HTTPStatus.NO_CONTENT)
def disconnect(disconnect_callback: bandwidth.models.DisconnectCallback):
if disconnect_callback.event_type != "disconnect":
print(f"Unexpected event type {disconnect_callback.event_type} received")
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

active_calls.discard(disconnect_callback.call_id)
return Response(status_code=http.HTTPStatus.NO_CONTENT)


@app.get("/calls", status_code=http.HTTPStatus.OK)
def get_calls():
return list(active_calls)


@app.delete("/calls/{call_id}", status_code=http.HTTPStatus.NO_CONTENT)
def delete_call(call_id: str):
if call_id in active_calls:
redirect = Redirect(redirect_url="/callbacks/redirectedCall")
bxml = BxmlResponse([redirect])
if call_id not in active_calls:
return Response(status_code=http.HTTPStatus.NOT_FOUND)

bandwidth_calls_api_instance.update_call_bxml(BW_ACCOUNT_ID, call_id, bxml.to_bxml())
active_calls.remove(call_id)
return Response(content=None)
else:
return Response(content=None, status_code=http.HTTPStatus.NOT_FOUND)
update_call = bandwidth.UpdateCall(redirect_url=f"{BASE_CALLBACK_URL}/callbacks/inbound/voice/callEnded")

try:
bandwidth_calls_api_instance.update_call(BW_ACCOUNT_ID, call_id, update_call)
except Exception as e:
print(f"Failed to update call: {e}")
return Response(status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR)

@app.get('/activeCalls', status_code=http.HTTPStatus.OK)
def get_active_calls():
data = json.dumps(active_calls)
return Response(content=data, media_type="application/json")
active_calls.discard(call_id)
return Response(status_code=http.HTTPStatus.NO_CONTENT)


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.146.0
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.9.0
typing-inspection==0.4.4
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.54.0
Loading