Trouble using MessagingResponse class in Twilio library to receive and reply to SMS - twilio

I am having trouble using Twilio's MessagingResponse class to send and receive messages using a webhook. I am using flask and ngrok to create a temporary URL to test my app, but I am getting a 502 error and 11200 warning with this new implementation.
I can confirm that the number I am attempting to message back is verified in my Twilio account. Here is the new implementation that uses the Twilio MessagingResponse to create the response message instead of sending it directly using the Twilio REST API:
import os
from flask import Flask, request, session, make_response
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from chatbot import ask, append_interaction_to_chat_log
from secret_key import secret_key
app = Flask(__name__)
app.config['SECRET_KEY'] = secret_key
account_sid = os.environ.get('ACCOUNT_SID')
auth_token = os.environ.get('AUTH_TOKEN')
client = Client(account_sid, auth_token)
#app.route('/bot', methods=['POST'])
def bot():
incoming_msg = request.values['Body']
print(incoming_msg)
chat_log = session.get('chat_log')
answer = ask(incoming_msg, chat_log)
session['chat_log'] = append_interaction_to_chat_log(incoming_msg, answer, chat_log)
r = MessagingResponse()
r.message = answer
return make_response(r)
I have been able to successfully send and receive messages using a message object and explicitly stating the phone number I am sending to using this implementation:
import os
from flask import Flask, request, session
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from chatbot import ask, append_interaction_to_chat_log
from secret_key import secret_key
app = Flask(__name__)
app.config['SECRET_KEY'] = secret_key
account_sid = os.environ.get('ACCOUNT_SID')
auth_token = os.environ.get('AUTH_TOKEN')
client = Client(account_sid, auth_token)
#app.route('/', methods=['POST'])
def bot():
incoming_msg = request.values['Body']
print(incoming_msg)
chat_log = session.get('chat_log')
answer = ask(incoming_msg, chat_log)
session['chat_log'] = append_interaction_to_chat_log(incoming_msg, answer, chat_log)
# use the incoming message to generate the response here
message = client.messages.create(
body=answer,
from_='+12232107883', #Twilio number you purchased or verified
to='+19143182181' # The phone number you want to send the message to
)
print(message.sid)
return 'message sent'
Attached is a photo of my implementation of the ngrok URL to configure the webhook.
Essentially, I am trying to implement the new structures in hopes of creating a more secure and scalable bot. Any ideas here? I realize it could be something in my Twilio settings, but I haven't found the solution. Thank you all.
I thought my problem was from not having an ngrok account:
But that did not seem to resolve the issue:

Related

Error using 'send_at' with Twilio Schedule Beta

I'm trying to schedule an sms via Twilio. I'm referencing the demo found here: https://www.twilio.com/docs/sms/api/message-resource#schedule-a-message-resource
Per the demo, I set up messaging service via the Twilio Console.
Here is the code, with a dummy destination phone number and authorizations:
from datetime import datetime
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = [sid]
auth_token = [token]
client = Client(account_sid, auth_token)
message = client.messages \
.create(
messaging_service_sid= [msid],
body='This is a scheduled message',
send_at=datetime(2022, 6, 18, 20, 36, 27),
schedule_type='fixed',
# status_callback='https://webhook.site/xxxxx',
to='+15559698489'
)
print(message.sid)
I get the following error:
TypeError: create() got an unexpected keyword argument 'send_at'
What am I missing?
Check that your Twilio Helper Library version is current.

Twilio - Quick question (Unable to update record)

hope you are doing it right these days.
To summarize my problem, I think this is not working becuase I am using a free Twilio account instead of a paid one. But that's just my beginner theory. Now, the issue:
I have tried an official Twilio tutorial (https://www.twilio.com/blog/automating-ngrok-python-twilio-applications-pyngrok, I shared the link in case someone finds it interesting or needs it), which allows us to automate SMS webhook (sms_url) configuration by using Client (twilio) and pyngrok (ngrok).
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url + '/bot')
I can't explain all the things that I tried in the last 4 days, with no success. I keep getting the same error:
client.incoming_phone_numbers.list(phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(sms_url=url + '/bot')
IndexError: list index out of range
Something is not working with the list, it comes empty, although environment variables are working properly. I will work with just one phone_number, so there no need for list, indeed, so I started to change that line to avoid different errors and ended up with this:
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers("my_number").update(sms_url=str(url) + '/bot')
Then I got the final error that I can't solve by my self:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py", line 442, in update
payload = self._version.update(method='POST', uri=self._uri, data=data, )
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/base/version.py", line 106, in update
raise self.exception(method, uri, response, 'Unable to update record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json
Twilio returned the following information:
Unable to update record: The requested resource /2010-04-01/Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I tried all different phone numbers combinations/formats: nothing works.
Thanks for your time reading all this!
Looks like something changed since the blog was written or there was a mistake.
Try the below:
The only difference is adding .public_url to the url object. Also allowed a GET to /bot for testing.
from dotenv import load_dotenv
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
app = Flask(__name__)
#app.route('/bot', methods=['POST','GET'])
def bot():
user = request.values.get('From', '')
resp = MessagingResponse()
resp.message(f'Hello, {user}, thank you for your message!')
return str(resp)
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print('This is',url)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url.public_url + '/bot')
if __name__ == '__main__':
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
start_ngrok()
app.run(debug=True)

Problem with from twilio.rest import client error?

I'm trying to use the Twilio sandbox to message to my Whatsapp number but I'm repeatedly getting this
ImportError...
My code is as followed...
import os
from twilio.rest import Client
client = Client()
from_whatsapp_number = 'whatsapp:Twilio number'
to_whatsapp_number = 'whatsapp:Own number'
client.messages.create(body= 'Ahoy World!',
from_= from_whatsapp_number,
to=to_whatsapp_number)

Why Am I Getting An Error When Connecting To Google Search Console API Via Flask Dance?

Im creating a flask app that retrieves data from Google Search Console API.
However I'm having hard times implementing Google OAuth with Flask-Dance.
I am getting the following error:
Here is my code:
from flask import Flask, render_template, request, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
import os
def create_app(config_name):
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
print(config_name)
blueprint = make_google_blueprint(
client_id={MY CLIENT ID},
client_secret={MY SECRET},
scope=["profile", "email"])
app = Flask(__name__)
app.config.from_object(config[config_name])
google_bp = make_google_blueprint(scope=["profile","email","https://www.googleapis.com/auth/webmasters"])
#app.route("/search")
def search():
if not google.authorized:
return redirect(url_for("google.login"))
request = {
'startDate': '2019-01-01',
'endDate': '2019-01-31','dimensions': ['query']}
resp = google.post("/webmasters/v3/sites/https%3A%2F%2Fwww.mysite.com/searchAnalytics/query", json=request)
amt=resp['rows'][0]['clicks']
return '<h1>'+amt+'</h1>'
return app
I have also set up the application in Google Developers Console following the below steps, outlined here:
https://flask-dance.readthedocs.io/en/v0.8.0/quickstarts/google.html
Any ideas what might be the issue?
Many thanks in advance
From the screenshot, client_id=None, it looks like you have some misconfiguration. In your code, there are two make_google_blueprint.
You can review your code again to fix this problem.

Trying to use Twitter API but my code wont run anything

I am trying to use the twitter API in order to stream all tweets that include Michigan State, Spartans, and MSU. After I can figure this out I want to use different big10 key words. However, I run this code and I can't get past
ln (*) no matter how long I wait nothing is happening. Is there any issue with my code? Or how to I get the display of this information so I can analyze it?
THANK YOU!
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authentification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'MichiganState', 'Spartans', 'MSU'
stream.filter(track=['MichiganState', 'Spartans', 'MSU'])'
Use on_status(self, status) in the listener class:
class StdOutListener(tweepy.StreamListener):
def on_status(self, status):
print status.text
print status.id

Resources