Failure Callback Whatsapp API Twilio - twilio

i've just copied the example of a whatsapp bot in the post to test whatsapp API: https://www.twilio.com/blog/php-twilio-whatsapp
script for Send message is working properly (i'm using sandbox). But the callback is not working. i get the 11200 - HTTP retrieval failure. Someone could analyse my code below? note that i downloaded the SDK not via composer.
<?php
require __DIR__ . '/twilio-php-main/src/Twilio/autoload.php';
use Twilio\Twiml;
$response = new Twiml;
$guess = $_REQUEST['Body'];
$pick = rand(1,5);
if (!in_array($guess, [1,2,3,4,5])) {
$response->message("Hiya! I'm thinking of a number between 1 and 5 - try to guess it!");
} elseif ($guess == $pick) {
$response->message("Yes! You guessed it!");
} else {
$response->message("Nope, it was actually $pick - Pick a new number to play again!");
}
print $response;

Related

how to detect voice messages on whatsapp with whatsapp-web.js

how to detect voice messages on whatsapp with whatsapp-web.js
I tried this but it seems like it doesn't work
client.on('voice', async (msg) => {}
I'm working on a project that saves the various types of files/content sent to my phone which is connected to whatsapp-web.js library.
I suggest you test the solution with some logs on the incoming message type.
You could solve this problem directly from the message reply (msg):
client.on('message', async msg => {
if(msg.type == 'ptt'){
// is a voice message
}
});
also with the mimetype of downloadMedia():
client.on('message', async msg => {
if(msg.hasMedia) {
const media = await msg.downloadMedia();
var mmtype = media.mimetype;
if(media.mimetype.contains('audio/ogg')){
// is a voice message
// don't know if .contains() is the solution try other comparators
}
}
});

The dialer is not showing full ussd code eg: *123*1#

I am using the url_launcher plugin for call, but the dialer is not showing the # character:
String url = 'tel:*123#';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
You need to use URL encoding for special character in a URL.
So # equals %23
This will work launch('tel:\*123\%23');
Other Way is to encode the number typed by user and pass it through Uri.encodeFull(urlString) or Uri.encodeComponent(urlString)
Like this.
launch("tel:" + Uri.encodeComponent('*123#'));
Disclaimer: plugin author here.
Do you want the phone call user interface to open or would you rather make the request silently? If you prefer to do it without popping the phone call UI, Android introduced in API level 26 the method sendUssdRequest.
I made a Flutter plugin called ussd_service to be able to easily access it from dart in a Flutter application. It can be used in the following manner:
import 'package:ussd_service/ussd_service.dart';
makeMyRequest() async {
int subscriptionId = 1; // sim card subscription Id
String code = "*21#"; // ussd code payload
try {
String ussdSuccessMessage = await UssdService.makeRequest(subscriptionId, code);
print("succes! message: $ussdSuccessMessage");
} on PlatformException catch (e) {
print("error! code: ${e.code} - message: ${e.message}");
}
};
makeMyRequest();
Hope this helps! Let me know on the Github repo's issues if you have any issue with it.

Send MMS using Twilio.TwimlResponse()

I'm using a node server with a webhook for handling receiving Twilio messages to one of my numbers. I use this number to forward communications between users, essentially anonymizing things for them (they communicate with our number so they don't have to give theirs to the other user).
In my handler, I currently basically do this:
var sendTo = /* other user's number */;
var sendFrom = /* sender number in received message */;
var body = /* body of message received */;
twimlResponse(body, {
to: sendTo,
from: sendFrom
});
response.send(twimlResponse.toString());
This works perfect for text messages. However, my debug log is showing errors for media messages with no body (also not forwarding the media in general, since I'm not currently telling it to).
So, I'm trying to update to send the media messages as well. This is not working well.
I found this documentation: https://www.twilio.com/docs/guides/how-to-receive-and-reply-in-node-js#respond-with-media-mms-message
However, it doesn't work. I get an error saying 'this' has no method 'To'.
I tried modifying my code a bit,
var sendTo = /* other user's number */;
var sendFrom = /* sender number in received message */;
var body = /* body of message received */;
var mediaUrl = /* mediaUrl0 of the received message */
if( body && mediaUrl ) {
twimlResponse(body, {
to: sendTo,
from: sendFrom,
mediaUrl: mediaUrl
});
}
else if( body ) {
twimlResponse(body, {
to: sendTo,
from: sendFrom
});
}
else if( mediaUrl ) {
twimlResponse(nil, {
to: sendTo,
from: sendFrom,
mediaUrl: mediaUrl
});
}
response.send(twimlResponse.toString());
I haven't yet verified that last one is correct for sending a message with no body, but my issue is that I can't figure out how to tell the twiml response to include the media. I've tried Media, media, MediaUrl, MediaUrl0, mediaUrl0, and mediaUrl. Each time I get a warning in my debugger saying it was an invalid noun. The Twiml Documentation says the nouns should be case sensitive and capitalized, though for some reason to and from are taken lower case. That part all works fine. I just can't figure out how to attach the media url.
Any tips are appreciated!
Edit -
Here is one attempt based on the linked documentation, which I thought wasn't working at all, but re-arranging the order of properties I set, I see I'm just not setting the to / from number appropriately. I know a twiml without those passed in automatically responds to the number that sent a message, from the number that received it. I need to specify both those values since I'm forwarding one user's message to another.
twimlResp.message(function() {
this.body(body);
this.media(media0);
this.to(sendTo);
this.from(sendFrom);
});
This snippet works fine for body and media, similar to the documentation, but crashes when setting to
Edit - I've tried changing this.to and this.from to this.To and this.From, but those don't work.
I've also tried this:
twimlResp.message(function() {
this.body(body);
this.media(media0);
});
twimlResp.to = sendTo;
twimlResp.from = sendFrom;
Which also does not work - .to and .from are ignored, causing the response to go back to the sending user from the number that received the original message.
I think you've gotten confused between the 2.0 and the 3.0 SDK. You can change between SDK versions by clicking in the top right of the example screen.
With your example provided, using the 3.0 SDK you can achieve this by:
var MessagingResponse = require('twilio').twiml.MessagingResponse;
var twiml = new MessagingResponse();
// Place your constraints here
var message = twiml.message({ to: sendTo, from: sendFrom });
if( body && mediaUrl ) {
message.body(body);
message.media(mediaUrl);
}
else if( body ) {
messsage.body(body);
}
else if( mediaUrl ) {
messsage.media(mediaUrl);
}
response.send(twiml.toString());
If you need a more in-depth detail on how I formulated this code, check out the MessagingResposne.js source. I'm assuming you have no restrictions on switching SDK versions, the reason I gave an example with the 3.0 SDK is because Twilio will be ending support for the 2.0 SDK as of 8/31/2017.
Howto with SDK 2.0
Since some users will need to migrate a large part of their codebase, here is how you can set a different to and from numbers with the SDK 2.0.
twimlResp.message(function() {
this.body(body);
this.media(media0);
}, {
to: sendTo,
from: sendFrom
});

Laravel PubSubHubbub i have subscribed but couldn't receive updates

I am trying to get real time feed updates using the Pubsubhubbup and Laravel, i have created 2 functions one for subscribe and the other one is a callback function.
when the subscribe function called it worked and the callback function receives a confirmation from the hub and respond with the hub_challenge code, all this works OK but the callback function doesn't receive any feed updates after that although it should receive it from the hub when there are updates but this is not happen !!
can you help to find what is the problem ??
thanks for your time.
the functions
public function subscribe(Feed $feed)
{
$hub_url = "http://pubsubhubbub.appspot.com";
$callback_url = url('feed/getFeedUpdates');
$subscriber = new Subscriber($hub_url, $callback_url);
$subscriber->subscribe($feed->feed_url);
Flash::success('Feed has been saved.');
return redirect('feed');
}
public function getFeedUpdates(Request $request)
{
// Subscribe Confirmation
if ($request->has('hub_mode') && $request->hub_mode == 'subscribe') {
$response = new Response($request->hub_challenge, 200);
$response->header('Content-Type', 'text/plain');
return $response;
} else { // Receive Updates
$updates = file_get_contents("php://input");
// put the updates to the database
}
}

Trigger.io PHP session expires

folks!
I'm trying to run an HTML app in Trigger.io. This app calls ajax to load some data from a PHP page. At this moment, I authenticate the user and start the session. After this, I have to call another PHP page. So, I check for the session started, and I found that the session is not active anymore. The second call is made right after the first one.
This happens when I try to run the app from the Trigger.io ToolKit, using iOS Simulator ( I'm using a Mac - OS X Mountain Lion ). When I test the same app in the Safari, it works perfectly: my PHP server recognizes the session started earlier, and the second page is loaded by ajax.
Is there any parameter I have to set? Or Trigger.io does not support PHP sessions?
Thank you.
Marcio
You should use forge.request.ajax(params) to make ajax requests, this is because of cross domain restrictions, as Forge apps are loaded as file:// urls on iOS.
forge.ajax.request takes a similar input to jQuery's $.ajax so you can easily switch between them if you want to use the same code on a website as well as in your Forge app.
More documentation is available in our docs: http://docs.trigger.io/en/v1.4/modules/request.html#ajax
#Connorhd , thank you so much for helping!
First of all, I do an ajax request to "app_authUser.php" to authenticate user. Then, if Ok, I do another ajax request to "app_loadFeed.php" to load data from server.
In the first ajax request, I pass, in the post parameters, the user data ( login and password ) to authenticate the user on database. The first command I call on the php file "app_authUser.php" is "session_start()", as follow:
CODE FOR "app_authUser.php" ON THE SERVER SIDE:
<?php
session_start();
// Just for test;
$idSession = session_id();
echo $idSession;
/*
Test user authenticate. If ok, then I assign idUser to $_SESSION['idUser'] variable.
*/
if( $loginOk == true ){
$_SESSION[ 'idUser' ] = $User->idUser;
}
?>
In the code above, the user is authenticated and $_SESSION['idUser'] is correctly initiated. In the second ajax request, I test if the variable $_SESSION[ 'idUser' ] is set. That's the point: it isn't set anymore. Again, I call "session_start()" at first:
CODE FOR "app_loadFeed.php" ON THE SERVER SIDE:
<?php
session_start();
// Just for test;
$idSession = session_id();
echo $idSession;
if( isset( $_SESSION[ 'idUser' ] ) ){
/* Load data from database to return to user.... */
echo ...
}
else{
echo '0';
}
?>
The test above always return false when I call my app from Trigger.io compiler. But, when I call my app from Safari, it always returns true.
I found out that the function "session_id()" returns different values in both ajax requests when the call is made from app running on Trigger.io compiler, but the same value when app is running on Sarari:
Example:
Requests from Trigger.io:
First request: echo $idSession returns "m7dbsv7qqem92os39lv5ao2ta1"
Second request: echo $idSession returns "h49pble06n7ao9pum06kt4dph0"
Requests from Safari:
First request: echo $idSession returns "2cbhin1185fm5ehvbb15k6n0b1"
Second request: echo $idSession returns "2cbhin1185fm5ehvbb15k6n0b1"
That means the session isn't the same at the first example. Why does this happen?
I'm not using forge.request.ajax in my app. That's my ajax code, in my javascript:
<script>
function openAjax()
{
try
{
var ajax = new XMLHttpRequest();
}
catch(e)
{
try
{
var ajax = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ee)
{
try
{
var ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(eee)
{
var ajax = false;
alert("Seu navegador não suporta AJAX!")
}
}
}
return ajax;
}
// This is the function called at second time, just after I authenticate my user and have session opened.
function loadFeed(){
var url = CT_URLBase + 'app_loadFeed.php'; // CT_URLBase = 'http://192.168.1.100/' in my local environment.
var parameters = '';
var ajax = openAjax();
ajax.open('POST', url, true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
ajax.onreadystatechange = function(){
if (ajax.readyState == 4){
if (ajax.status == 200){
var retorno = ajax.responseText;
if( retorno != '0' ){
/* Return OK!!! */
}
else{
/* Error: return is 0 (zero), that means session is not started.
}
}
}
}
ajax.send(parameters);
}
</script>
What most makes me in a misunderstanding is that the same code works perfectly in Safari, but not in Trigger.io.
By the way, I visited your website, connorhd.co.uk ! Great job! It's a great place to find "Interesting stuff"! Congratulations!
Thank you so much for your help!!!
Marcio Clume

Resources