Python Twilio making a call with Client - python

I am trying to make a call using twilio and python with the code below:
account_sid = "***"
auth_token = "***"
client = Client(account_sid, auth_token)
call = client.calls.create(to=phone_number, from_="+***", record=True, url="https://handler.twilio.com/twiml/***")
print call.sid
Here is my xml on that url:
<Response>
<Say>Hi, Thanks for accepting our call!</Say>
</Response>
The call connects, but after the xml triggers, the call ends.
Can someone point me out what I am doing wrong?
I can successfully make a call by doing the approach below, but I need the callsid right after dial for storing the callsid in the database to retrieve the recording later:
resp = VoiceResponse()
dial = Dial(caller_id='+1***', record="record-from-ringing")
dial.number(phone_number, url="https://handler.twilio.com/twiml/***")
resp.append(dial)
return HttpResponse(resp, mimetype='text/xml')
The url above is the same as the first example, but after playing the SAY tag, the call connects. Doing this approach doesn't allow me to get the callsid.
Any ideas?

The first call example ends because you run out of TwiML. You can place your in that TwiML to then connect the outbound-api call to another party.
For the second example using a instead of a REST API to the Calls resource,
You can use the recordingStatusCallbackEvent attribute to be informed of those details, once the recording is available.
https://www.twilio.com/docs/voice/twiml/dial#recordingstatuscallbackevent

Related

Twilio twiml instruction not executing within Flask.redirect

I cannot, for the life of me, get Twilio to execute the twiml instructions within a Flask.redirect. I cannot see anything wrong when I execute the query via Postman, so what am I missing? I can also see the redirect within the console outputs from Flask.
The expected behaviour is that when an outbound call is answered (CallStatus == 'in-progress') the call is redirected to a greeting message. What really happens is that the call lasts for 5 seconds——which is defined in dial() to ensure that Twilio has enough time to react——and the, hangs-up.
I have even tried incorporating a very long pause verb of a 100 seconds into the returned response within greeting(), but that was simply ignored.
So... what am I missing? Any insights would be appreciated.
#app.route("/call/dail/<number>", methods=['POST'])
def dial(number):
call = client.calls.create(
status_callback='http://<tunnel>.ngrok.io/call/status_update',
status_callback_method='GET',
status_callback_event=['initiated', 'answered', 'completed'],
twiml='<Response><Pause length="5"/></Response>',
to=number,
from_=from_number
)
return call.sid
#app.route("/call/status_update", methods=['GET'])
def call_status_update():
called_number = request.values.get("Called")
callsid = request.values.get("CallSid")
callstatus = request.values.get("CallStatus")
if callstatus == 'in-progress':
return redirect(url_for('greeting'))
return "Waiting for someone to pickup..."
#app.route("/call/greeting", methods=['GET', 'POST'])
def greeting():
response = VoiceResponse()
wait_message = 'This is a greeting.'
response.say(wait_message)
return Response(str(response), 200, mimetype="application/xml")
You're returning the following TwiML when the call is answered:
<Response><Pause length="5"/></Response> and then the call hangs up. You can either use TwiML to redirect to another URL or use the URL parameter of the calls resource and point to the /call/greeting URL.
When Twilio runs out of TwiML to execute, the call ends. You got to keep feeding it TwiML. Note, statusCallbacks do not control the call flow (so Twilio will not execute any TwiML returned by a statusCallback).
Side Note: typo here: /call/dail/<number> (dial)

Verify message was sent with Twilio - Python

I have a small script that sends text messages with Twilio using Python.
This is my code:
import os
from twilio.rest import Client
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
cell_number = os.environ.get('CELL_PHONE_NUMBER')
text_message = input("Enter a message to send: ")
send_message = client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
to=cell_number,
body=text_message
print(send_message)
And this is the response I get back:
<Twilio.Api.V2010.MessageInstance account_sid=MY_ACCOUNT_SID sid=SMc5e8f335198144b4b3c7f401af511f11>
I was wondering what the best way was to validate that the message was actually sent in code.
I thought of doing something like this:
if send_message:
print("Message sent.")
else:
print("Message not sent.")
And I was just wondering if there was a better way to do that.
I understand that this is a relatively old question and you might have figured out a way to achieve the desired behavior, but just wanted to post my thoughts so that it may help other learners like me in the future.
So basically, twilio provides developers with a functionality of webhooks using which the status of messages can be tracked. You will have to provide an extra parameter while creating the message wherein you will have to pass the callback url pointing to a server which will be logging the status of the sent messages.
When your python script sends a SMS by doing a POST request to twilio server, twilio will send the status of the message to the callback URL as a parameter by making a post or a get request.
This document describes how to achieve the above behavior with the help of example code snippets. In case you used another method to track the status of the messages, let us know so that it will help the community.

It's posible to get a synchronous response using put method?

I'm connecting to a remote mq queue using pymqi. I'm using put method as normal but I would like to know if there are some way to set something symilar as JMSReplyTo on JMS system to get a synchronous response of my message.
The request queue and the response are created in the remote mq where I'm connecting.
Yes you can set ReplyToQ (JMSReplyTo) and No, there is no one-call function for getting synchronous response.
Look example page or example in source
Is short:
# Prepare a Message Descriptor for the request message.
md = pymqi.MD()
md.ReplyToQ = dyn_queue_name
# Send the message.
queue = pymqi.Queue(qmgr, request_queue)
queue.put(message, md)

Twilio Functions: Add Parameters In Function Call

I am new to Twilio's API, and for that matter, Twilio as a whole.
I'm using python to make an automated system in which, when an event happens, a call is placed to a particular number. Below is what I'm running (in Python):
from twilio.rest import Client
account_sid = 'ACxx...'
auth_token = 'xx...'
client = Client(account_sid, auth_token)
call = client.calls.create(
url='my/twilio/function'
to="+11111111111",
from="+12222222222",
)
print(call)
And the following is my function in my Twilio account:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
twiml.say("A call was placed on the following extension.");
callback(null, twiml);
};
This will successfully make the call to my test number, and plays the message "A call was placed on the following extension". However, what I would like is to be able to pass parameters to say on which extension the call was made, e.g., "A call was placed on extension 100". How do I accomplish passing this custom parameter?
Any query parameters or POST body parameters sent to your Function's URL should be available in the event argument to your Function. From your Python code, consider adding a query parameter to your Function URL with the data your Function will need (the extension dialed, it sounds like?). So instead of /my/function it would be /my/function?extension=100, which should then be available in your Function code as event.extension.

Google app engine python timeout sending email

My script grabs the content of an rss page gets the urls in that page saves them to a list then it grabs the content of each url and it emails the contents of the page to me. Everything is working very well accept I can't send every link in the list. Typically about 22 links in the list. I don't want to combine the contents of multiple links into one email. If I don't add a timeout I get an over quota error like this
<class 'google.appengine.runtime.apiproxy_errors.OverQuotaError'>: The API call mail.Send() required more quota than is available.
After I added "time.sleep(9)" to slow it down it gives me this error.
<class 'google.appengine.runtime.DeadlineExceededError'>:
Traceback (most recent call last):
Here is my code.. Any thoughts?
size = len(my_tabletest)
a=2
while a < size:
url = my_tabletest[a].split('html</link>')[0] + "print"
url_hhhhhh = urlfetch.fetch(url)
my_story = url_hhhhhh.content
my_story = my_story.split('<div class="printstory">')[1]
my_story_subject = my_story.split('<h1>')[1]
my_story_subject = my_story_subject.split('</h1>')[0]
my_story = ''.join(BeautifulSoup(my_story).findAll(text=True))
message = mail.EmailMessage(sender="me<me#someplace.com>",
subject=my_story_subject)
message.to = "Jim <me#someplace.com>"
message.body = my_story
message.html = my_story_html
message.send()
time.sleep(9)
a=a+1
Welcome to Stack Overflow!
The task queue is built to solve this problem. You can leverage it with minimal change to your existing code using the deferred library:
Instead of calling message.send(), do something like this:
def send_email(message):
message.send()
deferred.defer(send_email, message)
This will create a batch of ad-hoc tasks that send your emails in the background, after your main request handler has returned. Some of these tasks will probably fail on the first try as your app hits short term quota limits for outbound mail. That's OK; failed tasks will back off and retry automatically until they succeed.
Edit: Oh, and take the sleep out of your code. =)
Edit #2: You can speed things up further by moving the urlfetch into the task, so each task fetches one URL and then sends one email. Fetching 22 URLs in one request handler could be enough to cause timeouts, independent of sending mail.

Categories

Resources