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: messaging-auto-respond
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 0 additions & 14 deletions Pipfile

This file was deleted.

482 changes: 0 additions & 482 deletions Pipfile.lock

This file was deleted.

28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Auto-Respond to SMS
# Messaging Auto Respond

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

Expand All @@ -11,15 +11,17 @@
* [Running the Application](#running-the-application)
* [Environmental Variables](#environmental-variables)
* [Callback URLs](#callback-urls)
* [Ngrok](#ngrok)
* [Ngrok](#ngrok)

# Description

This app automatically responds to texts sent to the associated Bandwidth number. Any texts sent to the `BW_NUMBER` will be auto-responded to using the auto response map. Valid words are: `STOP`, `QUIT`, `HELP`, and `INFO`.
This sample app automatically replies to texts sent to your Bandwidth number. The reply depends on the text received: `STOP`, `QUIT`, `HELP` and `INFO` each get their own reply, and anything else gets a prompt to reply `HELP`. Keywords are matched against the whole message and are not case sensitive.

To use this app, you must check the "Use multiple callback URLs" box on the application page in Dashboard. Then in Dashboard, set the INBOUND CALLBACK to `/callbacks/inbound/messaging` and the STATUS CALLBACK to `/callbacks/outbound/messaging/status`. The same can be accomplished via the Dashboard API by setting InboundCallbackUrl and OutboundCallbackUrl respectively.
The `STOP` and `QUIT` replies are for demonstration only. This app doesn't keep track of opt-outs, so it will keep replying to a number that has sent `STOP`.

Inbound callbacks are sent notifying you of a received message on a Bandwidth number, this app sends a custom response to those messages based on their content. Outbound callbacks are status updates for messages sent from a Bandwidth number, this app has a dedicated response for each type of status update.
In order to use the correct endpoints, you must check the "Use multiple callback URLs" box on the application page in Dashboard. Then in Dashboard, set the INBOUND CALLBACK to `/callbacks/inbound/messaging` and the STATUS CALLBACK to `/callbacks/outbound/messaging/status`. The same can be accomplished via the Dashboard API by setting `InboundCallbackUrl` and `OutboundCallbackUrl` respectively.

Inbound callbacks are sent notifying you of a received message on a Bandwidth number. This app prints the phone numbers involved and the text received, then sends the reply. Outbound callbacks are status updates for messages sent from a Bandwidth number, this app has a dedicated response for each type of status update.

# Pre-Requisites

Expand All @@ -34,7 +36,7 @@ For more information about API credentials see our [Account Credentials](https:/
To install the required packages for this app, run the command:

```sh
pip install -r reaquirements.txt
pip install -r requirements.txt
```

Use the following command to run the application:
Expand All @@ -49,8 +51,8 @@ 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_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
BW_MESSAGING_APPLICATION_ID # Your Messaging Application Id created in the dashboard
LOCAL_PORT # The port number you wish to run the sample on
Expand All @@ -66,13 +68,11 @@ Below are the callback paths:

## Ngrok

A simple way to set up a local callback URL for testing is to use the free tool [ngrok](https://ngrok.com/).
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
```

You can view your public URL at `http://127.0.0.1:4040` after ngrok is running. You can also view the status of the tunnel and requests/responses here.

Once your public ngrok url has been created, you can use it as the `BASE_CALLBACK_URL` environmental variable and set it in the messaging application created in the [pre-requisites](#pre-requisites) section.
You can view your public URL at `http://127.0.0.1:4040` after ngrok is running. You can also view the status of the tunnel and requests/responses here. Once your public ngrok url has been created, use it as the base of the callback URLs in the messaging application created in the [Pre-Requisites](#pre-requisites) section.
4 changes: 3 additions & 1 deletion icon-messaging.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
112 changes: 58 additions & 54 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import http
import os
import sys
from typing import List, Optional

import bandwidth
from bandwidth import ApiException
from fastapi import FastAPI, Response
from typing import List, 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_CLIENT_ID = os.environ['BW_CLIENT_ID']
BW_CLIENT_SECRET = os.environ['BW_CLIENT_SECRET']
BW_MESSAGING_APPLICATION_ID = os.environ['BW_MESSAGING_APPLICATION_ID']
BW_NUMBER = os.environ['BW_NUMBER']
LOCAL_PORT = int(os.environ['LOCAL_PORT'])
except KeyError as e:
print(f"Please set the environmental v"
f"variables defined in the README\n\n{e}")
print(f"Please set the environmental variables defined in the README\n\n{e}")
sys.exit(1)
except ValueError as e:
print(f"Please set the LOCAL_PORT environmental variable to an integer\n\n{e}")
Expand All @@ -26,70 +25,75 @@
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_messages_api_instance = bandwidth.MessagesApi(bandwidth_api_client)

STATUS_MESSAGES = {
"message-sending": "message-sending type is only for MMS.",
"message-delivered": "Your message has been handed off to the Bandwidth's MMSC network, but has not been confirmed at the downstream carrier.",
"message-failed": "For MMS and Group Messages, you will only receive this callback if you have enabled delivery receipts on MMS.",
}

def auto_response(text: str):
match text.lower():
case "stop":
return "STOP: OK, you'll no longer receive messages from us."
case "quit":
return "QUIT: OK, you'll no longer receive messages from us."
case "info":
return "INFO: This is the test responder service. Reply STOP or QUIT to opt out."
case "help":
return "HELP: This is the test responder service. Reply STOP or QUIT to opt out."
case _:
return "AUTO-REPLY: Thank you for your message! Please respond with a valid word. Reply HELP for help."
REPLIES = {
"stop": "STOP: OK, you'll no longer receive messages from us.",
"quit": "QUIT: OK, you'll no longer receive messages from us.",
"help": "Valid words are: STOP, QUIT, HELP, and INFO. Reply STOP or QUIT to opt out.",
"info": "INFO: This is the test responder service. Reply STOP or QUIT to opt out.",
}
DEFAULT_REPLY = "Please respond with a valid word. Reply HELP for help."


@app.post("/callbacks/inbound/messaging", status_code=http.HTTPStatus.NO_CONTENT)
def handle_inbound_message(data: List[bandwidth.models.InboundMessageCallback]):
message_callback = data[0]
if message_callback.message.direction == "out" or message_callback.type != "message-received":
print(f"Unexpected callback received: {message_callback.type}")
return Response(content=None, status_code=http.HTTPStatus.BAD_REQUEST)
@app.exception_handler(RequestValidationError)
def invalid_request(request, exc):
return Response(status_code=http.HTTPStatus.BAD_REQUEST)


def auto_reply(text: Optional[str]) -> str:
return REPLIES.get((text or "").strip().lower(), DEFAULT_REPLY)

response_text = auto_response(message_callback.message.text)

def send_reply(to: str, text: str):
message_request = bandwidth.models.MessageRequest(
application_id=BW_MESSAGING_APPLICATION_ID,
to=[message_callback.message.var_from],
to=[to],
var_from=BW_NUMBER,
text=response_text,
text=text
)

try:
bandwidth_messages_api_instance.create_message(BW_ACCOUNT_ID, message_request)
except ApiException as e:
print(f"Error sending message: {e}")
return Response(content=None, status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR)
message = bandwidth_messages_api_instance.create_message(BW_ACCOUNT_ID, message_request)
print(f"Sent reply {message.id}\nTo: {to}\nText: {text}")
except Exception as e:
print(f"Failed to send reply: {e}")


@app.post("/callbacks/outbound/messaging/status", status_code=http.HTTPStatus.NO_CONTENT)
def handle_message_status(
data: Union[
List[bandwidth.models.MessageSendingCallback],
List[bandwidth.models.MessageDeliveredCallback],
List[bandwidth.models.MessageFailedCallback]
]):
match data[0].type:
case "message-sending":
print("message-sending type is only for MMS")
case "message-delivered":
print("your message has been handed off to the Bandwidth's SMSC network, but has not been confirmed at the downstream carrier.")
case "message-failed":
print(f"Your message has failed to be delivered to the downstream carrier. Error Code: {data[0].error_code}")
print("For MMS and Group Messages, you will only receive this callback if you have enabled delivery receipts on MMS.")
case _:
print(f"Unexpected callback received: {data[0].type}")
return Response(content=None, status_code=http.HTTPStatus.BAD_REQUEST)


if __name__ == '__main__':
uvicorn.run('main:app', port=LOCAL_PORT, reload=True)
def status_callback(callbacks: List[bandwidth.models.StatusCallback]):
if not all(callback.type.value in STATUS_MESSAGES for callback in callbacks):
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

for callback in callbacks:
print(STATUS_MESSAGES[callback.type.value])

return Response(status_code=http.HTTPStatus.NO_CONTENT)


@app.post("/callbacks/inbound/messaging", status_code=http.HTTPStatus.NO_CONTENT)
def inbound_callback(callbacks: List[bandwidth.models.InboundCallback]):
if not all(callback.type.value == "message-received" for callback in callbacks):
return Response(status_code=http.HTTPStatus.BAD_REQUEST)

for callback in callbacks:
message = callback.message
print(f"{callback.description}\nTo: {message.to[0]}\nFrom: {message.var_from}\nText: {message.text}")
send_reply(message.var_from, auto_reply(message.text))

return Response(status_code=http.HTTPStatus.NO_CONTENT)


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.109.1
h11==0.14.0 ; python_version >= '3.7'
httptools==0.6.1
idna==3.7 ; 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.36.2 ; 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.162.0
h11==0.16.0
idna==3.20
opentelemetry-api==1.45.1
pydantic==2.14.1
pydantic_core==2.50.1
python-dateutil==3.0.0
six==1.17.0
starlette==1.10.0
typing-inspection==0.4.4
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.54.0
Loading