SMS Template creation in Twilio - node.js

I am using Twilio node.js API in microsoft azure for sending SMS. I want to create some predefined template like 'Dear customer your account balance is Rs 55555'.
Is it possible to create SMS Template in Twilio account ? Is Twilio supports Transaction SMS ?

You will need to define your dynamic content in a manner similar to the following example where you respond to a sender by name (shown in Python) from the Quickstarts:
https://www.twilio.com/docs/quickstart/python/sms/replying-to-sms-messages
from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
# Try adding your own number to this list!
callers = {
"+14158675309": "Curious George",
"+14158675310": "Boots",
"+14158675311": "Virgil",
}
#app.route("/", methods=['GET', 'POST'])
def hello_monkey():
"""Respond and greet the caller by name."""
from_number = request.values.get('From', None)
if from_number in callers:
message = callers[from_number] + ", thanks for the message!"
else:
message = "Thanks for the message!"
resp = twilio.twiml.Response()
resp.message(message)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)

Related

How can I host a dynamic flask app that acts as a listener for a twilio phone number?

I made a simple flask app that acts as a listener connected to twilio via a webhook. The logic within the app generates a response and returns the response. I'm stuck trying to deploy and host this app. Anyone have experience with this and suggestions?
Below is similar my python file some things are changed such has account info. This is all I have at the moment:
# IMPORTS =============================================================
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
# FIELD VARIBALES ===========================================================
account_sid = 'ACCOUNT_SID'
auth_token = 'AUTH_TOKEN'
twilio_number = 'TWILIO_NUMBER'
# FUNCTIONS =======================================================
# Functions to be used in generating response. These are left out for this thread.
# APP =================================================================
app = Flask(__name__)
#app.route("https://mywebhook.com/sms", methods=['GET', 'POST'])
def sms():
"""Send a dynamic reply to an incoming text message"""
# Get the message the user sent our Twilio number
body = request.values.get('Body', None)
# Start our TwiML response
resp = MessagingResponse()
# Determine the right reply for this message
if body == 'hello':
resp.message("Hi!")
elif body == 'bye':
resp.message("Goodbye")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I've tried using Netlify and expected a response when texting my twilio number. However there is no response.

YouTube Push Notifications via Webhooks & PubSubHubbub (Python3) returning 200 on subscription, but nothing on video upload

I've added a Webhooks listener to a Discord bot, and I'm trying to use that to post notifications to a text channel when a new video is uploaded (trying to eliminate my reliance on MEE6). When I subscribe to notifications at https://pubsubhubbub.appspot.com/subscribe, I get a 200 response, and my server's console prints
66.249.84.174 - - [27/Apr/2021 05:23:51] "GET /webhooks?hub.topic=https://www.youtube.com/xml/feeds/videos.xml%3Fchannel_id%<THE_CHANNEL_ID_I_WANT_NOTIFICATIONS_FOR>&hub.challenge=<A_BUNCH_OF_NUMBERS>&hub.mode=subscribe&hub.lease_seconds=432000 HTTP/1.1" 200 -
However, when a video gets uploaded nothing happens.
I've tried manually triggering a POST request from PostMan to the same endpoint (with the XML body found here https://developers.google.com/youtube/v3/guides/push_notifications as the raw->xml body text), and that seems to hit my console and return a 200, but I'm at a loss as to why I'm not getting any indication when an upload goes up. Code below:
from flask import Flask, Response, request
app = Flask(__name__)
#app.route('/webhooks', methods=['POST'])
def respond():
print(request.json);
return Response(status=200)
#app.route('/webhooks')
def index():
print(('request', request))
print('args:', request.args) # display text in console
print('form:', request.form)
print('data:', request.data)
print('json:', request.json)
print('files:', request.files)
return request.args.get('data', 'none') # send text to web browser
if __name__ == '__main__':
app.run(host='0.0.0.0', port=<MY_PORT>)
I'm hosting on PebbleHost, which is why the host is set to 0.0.0.0; there's a separate IP I'm connecting to for the subscriptions, mapped to a dedicated port. I'm quite new to Webhooks, and this is my first time interacting with the YouTube API, so I'm certain there's something really obvious I'm overlooking.
You have to return hub.challenge for confirmation on subscription.
A Working Example that I made earlier.
from flask import Flask, request
import xmltodict
app = Flask(__name__)
#app.route("/callback", methods=['POST', 'GET'])
def callback():
if request.method == 'POST':
data = xmltodict.parse(request.data)
print(data)
return request.data
else:
return request.args.get('hub.challenge')
app.run('0.0.0.0')

Way to extract the integer values from twilio inbound sms’?

Would you know how to select only the int (number) variables from the inbound sms in the twilio api. At the moment all of my inbound sms' are printing in the terminal after I run this code
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
from_number = request.form['From']
to_number = request.form['To']
body = request.form['Body']
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("")
print(str(body))
return str(resp)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=70, debug=True)
Would you know how I could make the numbers from the body of an inbound sms a variable that I could manipulate and use. To put things into perspective, I'm trying to automate a login process that uses an OTP for authentication. I plan to use selenium to insert this code (number) I recieve through my twilio number

How to submit a query to Google Dialogflow using Flask

I have the following python script that is connecting to Google Dialogflow using Flask and is using a webhook to retrieve the response from Google Dialogflow.
The limitation is that I currently only enter the query in to the Google Dialogflow frontend, with the result returned here in variable result
However how can I use this same script to submit the query to Google Dialogflow, instead of entering in the front end?
Any help appreciated, thanks!
import json
import os
from flask import Flask
from flask import request
from flask import make_response`
`enter code here # Flask app should start in global layout
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
res = processRequest(req)
res = json.dumps(res, indent=4)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
result = req.get("queryResult")
result_message = result['fulfillmentText']
print(result_message)
#app.route('/test', methods=['GET'])
def test():
return "Hello there my friend !!"
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
app.run(debug=True, port=port, host='0.0.0.0')`
I discovered shortly after posting this that a webhook is whats known as a reverse API, and only shows results as opposed to two way interactions.

Connect to API and send back a message with Flask app

I have a flask app deployed to Heroku and would like to receive text from Chatfuel (bot building platform) and send back texts in return.
Now, what I did is to use my heroku app as a web-hook, so that Chatfuel can make a simple GET or POST query to my API. The problem is that I have no experience with Flask or APIs, so I am not sure about how my app can receive information (in json format) and send it back to chatfuel.
This is what I wrote so far:
import os
import sys
import json
import requests
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def verify():
# when the endpoint is registered as a webhook, it must echo back
# the 'hub.challenge' value it receives in the query arguments
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello world", 200
#app.route("/json", methods=['GET','POST'])
def json():
url = "chatfuel_api"
data = json.load(urllib2.urlopen(url))
if request.json:
mydata = request.json
return "Thanks",200
else:
return "no json received"
#app.route('/hello', methods = ['GET','POST'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n",200
if __name__ == '__main__':
app.run(debug=True)
The verify() function works, as I see an 'Hello world' message if I run the app locally. However, both json() and api_echo() don't work, and when my server receives a get or post request from chatfuel, it returns a 404 error.
As you can see, I really have a lot of confusion, and your help would be really invaluable.
Thanks
You need to make sure you have registered the proper webhook url with Chatfuel. For the code you currently have, to hit the json endpoint the url would be https://www.your_server.com/json
The verify route looks like the hub challenge FB sends, so you would have to register the root of your site (that is, with your current code) with FB to hit the verify function. That url would look like this https://www.your_site.com/

Resources