Skip to content

Instantly share code, notes, and snippets.

@RobertLucian
Created January 30, 2021 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertLucian/c19185d9ec3a3d0ac21878f22e862807 to your computer and use it in GitHub Desktop.
Save RobertLucian/c19185d9ec3a3d0ac21878f22e862807 to your computer and use it in GitHub Desktop.
Server to receive SMS notifications from Twilio
import json
import base64
notification = {
"type": "out",
"lp": "B-36-IHK",
"c": "orange",
"b": "dodge"
}
print("-----------------------------")
print("json input")
print(json.dumps(notification))
print("-----------------------------")
print("base64-encoded output")
notificationStr = json.dumps(notification)
encodedNotification = base64.b64encode(notificationStr.encode("utf-8"))
print(encodedNotification)
print("-----------------------------")
print("base64-decoded json")
notificationStr = base64.b64decode(encodedNotification).decode("utf-8")
notification = json.loads(notificationStr)
print(notification)
import urllib.parse as parse
import json
import base64
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
# Exemple of API request data
# {
# "ApiVersion": [
# "2010-04-01"
# ],
# "MessageSid": [
# "SM658596eb029fba176d9a2fc7e4f17463"
# ],
# "ToCountry": [
# "US"
# ],
# "Body": [
# "Hello World!"
# ],
# "AccountSid": [
# "ACd9b96fb957c557e7008b09e6ccaf9b85"
# ],
# "ToCity": [
# "HUNTINGTON"
# ],
# "FromCity": [
# "NORTH AUGUSTA"
# ],
# "SmsMessageSid": [
# "SM658596eb029fba176d9a2fc7e4f17463"
# ],
# "SmsStatus": [
# "received"
# ],
# "FromZip": [
# "29842"
# ],
# "To": [
# "+16317598243"
# ],
# "NumMedia": [
# "0"
# ],
# "FromState": [
# "SC"
# ],
# "FromCountry": [
# "US"
# ],
# "SmsSid": [
# "SM658596eb029fba176d9a2fc7e4f17463"
# ],
# "From": [
# "+18032921536"
# ],
# "NumSegments": [
# "1"
# ],
# "ToState": [
# "NY"
# ],
# "ToZip": [
# "11746"
# ]
# }
app = Flask(__name__)
@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
"""Receive SMS body."""
# parse the request
parsed = parse.parse_qs(request.get_data().decode("ascii"))
# write request data to file
with open(parsed["SmsSid"][0] + ".json", "w") as f:
# print(json.dumps(parsed, indent=2))
json.dump(parsed, f, indent=2)
notificationStr = base64.b64decode(parsed["Body"][0]).decode("utf-8")
notification = json.loads(notificationStr)
with open(parsed["SmsSid"][0] + "-notification" + ".json", "w") as f:
print("the notification is: {}".format(json.dumps(notification, indent=2)))
json.dump(notification, f, indent=2)
return str(MessagingResponse())
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=8080,
debug=True,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment