Invoke a twilio function without Studio Flow - twilio

I cannot seem to figure out how to call a Twilio function correctly. I tried calling it by passing data via POST:
url = "https://xxxx-dev.twil.io/voicemail"
data = {'event': {'id': '00141',
'RecordingUrl': 'https://api.twilio.com/2010-04-01/Accounts/ssssss/Recordings/xxxxxxx.mp3',
'From': '+12xxxxxxxxx',
'textTranslation': 'something here'}}
requests.post(url, data=data)
It doesn't seem to work. It returns 500 because it does not find the event object or the context object.
How do I pass event, context, callback when calling a function directly?

Turns out I was sending the data incorrectly.
You also don't need to include context nor callback, those are provided by twilio. You need to send only data as json to that endpoint.
url = "https://xxxx-dev.twil.io/voicemail"
data = {'id': '00141',
'RecordingUrl': 'https://api.twilio.com/2010-04-01/Accounts/ssssss/Recordings/xxxxxxx.mp3',
'From': '+12xxxxxxxxx',
'textTranslation': 'something here'}
requests.post(url, json=data)

Related

How do I make my for await loop do everything within its body before moving on to the next line of code in twilio serverless functions?

I have been working on this problem for a couple of days now, and feel like I'm extremely close to solving the issue. I need to cycle through an object and send a text message to each record in the object before moving on to the next line of code. The code to send works when isolated locally. But I'm having trouble getting it to work in Twilio Functions. All my code appears to work, but the text messages are not sent.
for await (const contact of allItems) {
client.messages
.create({
body: "Hey " + contact.name + "!" + " " + message,
messagingServiceSid: messaging_service,
to: contact.key
});
};
// End Send Message to Each Contact
I've attached the portion of code I believe I'm having issues with.
What I want to do, is for this piece of code to run completely before moving on to the next few lines and invoking a callback.
Any idea how I could do something like this?
Twilio developer evangelist here.
The issue here is that you are not awaiting the actual result of the asynchronous call. Locally, that doesn't matter, but within Twilio Functions once you call the callback function all asynchronous calls that have started are terminated.
To create a loop that makes asynchronous requests and waits for them all to complete you will want to use Promise.all in conjunction with map. In your example, it should look like this:
function SendMessages(allItems, message, client, messagingService) {
const apiRequests = allItems.map((contact) => {
let usersName = contact.name;
return client.messages.create({
body: `Hey ${usersName}! ${message}`,
messagingServiceSid: messagingService,
to: contact.key,
});
})
return Promise.all(apiRequests);
}
In this function we map over the list contacts returning the promise that is created when we try to send a message. The variable apiRequests becomes an array of promises that represent the requests to the API. We can then use this array of promises in Promise.all. Promise.all will only resolve once all the promises it is passed have resolved (or if a promise rejects).
I recommend you read my answer to your previous question as that brings up some further issues that you might have with this.

Twitter API v2 Streaming with Retrofit or OkHttp

I am trying integrate the new Twitter API specifically the streaming tweets part in my android app, I am using Retrofit for my http calls.
When I try to make the call to get the streaming tweets it just hangs and does not return anything.
this is my retrofit call
#Streaming
#GET("tweets/search/stream")
suspend fun getFilteredStream(#Header("Authorization") token:String)
I then tried making a call with just OkHttp as shown in the documentation I get a successful response but I dont know how to stream the data.
I can make the call successfully via a curl call and see the data no problem.
How do I stream the data via retrofit or OkHttp
Update:
With OkHttp I was able to get data by doing this
val client: OkHttpClient = OkHttpClient().newBuilder()
.build()
val request: Request = Request.Builder()
.url("https://api.twitter.com/2/tweets/search/stream")
.method("GET", null)
.build()
val response: Response = client.newCall(request).execute()
val source = response.body?.source()
val buffer = Buffer()
while(!source!!.exhausted()){
response.body?.source()?.read(buffer, 8192)
val data = buffer.readString(Charset.defaultCharset())
}
data holds the string data representation of multiple tweet objects but how do I read one tweet at a time, or parse the response like this?
From the docs, I think you'll need to combine the two examples you have.
https://github.com/square/retrofit/blob/108fe23964b986107aed352ba467cd2007d15208/retrofit/src/main/java/retrofit2/http/Streaming.java
Treat the response body on methods returning {#link ResponseBody ResponseBody} as is, i.e. without converting the body to {#code byte[]}.
And example calling code
https://github.com/square/retrofit/blob/108fe23964b986107aed352ba467cd2007d15208/retrofit/src/test/java/retrofit2/CallTest.java#L599
I suspect, dependending on the JSON API you use you may be able to use a Streaming API from the response body. But if not you could split on either just newline or newline followed by { on next line and parse individually. Sorry I can't help here.
See https://en.wikipedia.org/wiki/JSON_streaming#Concatenated_JSON

Twilio PHP SDK - Did twilio receive my request?

We are using the Twilio PHP SDK and the Notify Client. When I make a request how do I get the status of that request. Did it return a good 2XX, an error 4XX? And to be clear, I don't mean, what is the status of the messages. I simply mean, did twilio get my API call?
When testing in Postman with the REST API I typically get a 200 or 201 response if everything went well.
$twilio = new Client($acct_sid, $token);
$Addresses = array("+12015551234");
$toBindingAttributes = array();
foreach ($Addresses as $Address) {
array_push($toBindingAttributes, '{"binding_type":"sms","address":"' . $Address . '"}');
}
$notification = $twilio->notify->services($notify_sid)
->notifications->create([
"toBinding" => $toBindingAttributes,
"body" => "Twilio Test."
]);
I've tried to return $notification and I just get [Twilio.Notify.V1.NotificationInstance]
-----Edit-----
ok I realize now that [Twilio.Notify.V1.NotificationInstance] is an object. I was able to print_r($notification) and see that there is a statusCode property.
I tried to echo that property print_r(#notification->statusCode) but I get "Unknown Property".
Is it because it's "protected"?
[statusCode:protected] => 201
Thanks
Since the result is the [Twilio.Notify.V1.NotificationInstance] object.
The problem is all the properties within the object are protected we cannot access them directly.
We were able to get to them with a bunch of strpos, substr, and regex but found a much easier way using a getter.
By doing this way
print($twilio->getHttpClient()->lastResponse->getStatusCode());
More info in the Twilio-PHP library
https://github.com/twilio/twilio-php/blob/650f42647c9b3039e03ae075785164ec97203e94/src/Twilio/Http/Response.php

ios swift 2.1 - unable to send Patch request with body

I'm trying to write a http rest client for my webservice and i need to send some PATCH requestes with data in the body.
I'm using the JUST library for sending requests ( https://github.com/JustHTTP/Just )
My express application just doesn't see the request.
Here's some code (i'm testing in playground, and everything went fine with other kind of requests like put, post...)
headers = ["accept":"application/json","content-type":"application/json","authorization":"key"] //key is ok
var data = ["id":3, "quantity":6]
var r = Just.patch("http://api.marketcloud.it/v0/carts/1233", headers:headers, data:data) //1233 is a cart Id
print(r)
print(r.json)
The method Just.patch returns an HTTPResult Object.
this says 'OPTIONS http://api.marketcloud.it/v0/carts/13234 200'
Also this object should contain a json, but it's 'nil'.
On the server-side, my express applications doesn't receive the request (it just logs an 'OPTION', but nothing else).
Could this be a playground-related problem? Or a just-related one?
Thanks for any suggestion
I managed to contact the library's author via twitter and he fixed the bug and answered me in less than 24h!
Here's the new release of the library.
https://github.com/JustHTTP/Just/releases

Sencha Touch- Retrieving XML data from server and store it in object

I was looking a way to get a xml data from the server and parse it in a object so i can access that data anywhere in my app. I found many code doing this by creating a model, Store and setting a proxy with XMLReader. Yeah this is good but there is a compulsion of creating store and proxies. Is there any way i can say this is my URL of xml data, get me the parsed xml in an object. I think for getting JSON we have a way like below.
Ext.util.JSONP.request({
url: '<XYZ_URL>',
callbackKey: 'Successcallback',
Successcallback: function(result) {
console.log(result.data);
// Do your thing here
}});
Here we get a JSON data from the server and in the Successcallback function we get the JSON data as an Object in result. I can then save this result object globally and use it or travers through anywhere.
Can i do same thing with the XML data or i will get the XML data as string and then i need to parse it manually?
you can send Ajax request to the given Url and in success report method you can get your Desired data
e.g.
Ext.Ajax.request({
url: 'some_url',
success: function(response, opts) {
// parse the responseText
var data = Ext.util.JSON.decode(response.responseText);
// save the username
localStorage.setItem("name", data.name);
localStorage.setItem("id", data.id);
}
});

Resources