My question is specific to using slack rtm on ratchetphp/Pawl. I have below code which connects fine but dies eventually.
<?php
require_once "response.php";
//first make authenticated call to rtm.start
use \Curl\Curl;
$curl = new Curl();
$rtmStartUrl = "https://slack.com/api/rtm.start?token=xx-xx-xx-xx-xx&pretty=1";
$curl->get($rtmStartUrl);
$wsUrl = $curl->response->url;
$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);
$connector($wsUrl)
->then(function(Ratchet\Client\WebSocket $conn) {
$conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "Received: {$msg}\n";
// $conn->close();
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
Upon running, the output is:
root#ip-172-31-45-75:/var/www/html/slack# php pawl.php
Received: {"type":"hello"}
Received: {"type":"reconnect_url","url":"wss://mpmulti-qpau.slack-msgs.com/websocket/jDkgDysXfZspRj10zqdcrshHK6PhPLItYx2HEkdXy47RPCAJwKgI_NLq0bhS4uMjIT7iRtOoCDUJffcxcr7YdiqMbITUZYqnTmT39Et5a8JeuPLFfCUUzan4MCz34p0jcfAKaQW9G9HpIWrYH4CTqyICZuhgWHnzo8K7dO2zXFc="}
Received: {}
Connection closed (1006 - Underlying connection closed)
root#ip-172-31-45-75:/var/www/html/slack#
The websocket is part of slack rtm api (https://api.slack.com/rtm). It seems like when reading on empty websocket, the connection is closed. I think it might be like we listen to slack events (https://api.slack.com/events) sent over websocket for working to avoid disconnect.
Currently, this does not work because of disconnection error.
Hello World! is not a valid message for this API, so Slack is closing the connection when it receives that message. Try sending something valid (or nothing at all).
Related
connection.on('incoming', function(conn) {}) function not called.
I am trying to implement the incoming call in the browser. What I tried is a javascript code
var number = $("#number").val();
params = {
"PhoneNumber": number,
"CallerId": "+13604924000",
"AgentName": "Noman Javed",
};
Twilio.Device.setup(token);
Twilio.Device.ready(function(device) {
console.log('Ready');
// ---------------------------------------------------
// Explicitly create a new outgoing connection
var connection = Twilio.Device.connect(params);
console.log('PhoneNumber: ' + params.PhoneNumber);
$('#hangup_btn_span').show();
$("#hangup_btn").show();
connection.on('error', function(error) {
console.log(error);
});
connection.on('accept', function(conn) {
});
connection.on('incoming', function(conn) {
console.log("incoming call connection object log");
console.log(conn);
console.log('Incoming connection from ' + conn.parameters.From);
// accept the incoming connection and start two-way audio
// conn.accept();
});
}
For outgoing calls, I had to add the URL of the Twiml App outgoing call URL and dial the call using rest API to hit twiml page.
For incoming calls, I had add incoming call URL in the phone number incoming call URL that is
mydomain.com/Welcome/incoming_call
The incoming call urls code is:
header('Content-Type: application/xml');
// Load the required files
require APPPATH . 'libraries/vendor/autoload.php';
use Twilio\Jwt\ClientToken;
use Twilio\Rest\Client;
use Twilio\TwiMl;
use Twilio\TwiML\VoiceResponse;
file_put_contents('request.log', "\n" . "incoming call - : " . json_encode($_REQUEST) . "\n", FILE_APPEND);
?>
<Response>
<Pause length="2"/>
<Say voice="woman">Dialing number</Say>
<Dial callerId="<?php echo $_REQUEST['From']; ?>" >
<?php echo $_REQUEST['To']; ?>
</Dial>
</Response>
How I will receive the call in the browser in this function with parameters
connection.on('incoming', function(conn) {
console.log("incoming call connection object log");
console.log(conn);
console.log('Incoming connection from ' + conn.parameters.From);
// accept the incoming connection and start two-way audio
// conn.accept();
});
Do I need to add an incoming call URL in Twiml App too or just add in the phone number incoming URL?
Thanks in advance for helping and guiding.
First, in the twiml app you have to add the url for your backend api where you have your php code and add that twiml app to your incoming number.
Now, while generating the token for your user you must have used an 'identity'. We need to use that identity value to connect the incoming call to the user. Something like below:
$response = new VoiceResponse();
$dial = $response->dial('');
$dial->client(IDENTITY_VALUE);
this dial->client will connect the incoming call to the browser.
If you have not used identity attribute in your token generation, check this url:
https://www.twilio.com/docs/iam/access-tokens?code-sample=code-creating-an-access-token-voice-2&code-language=PHP&code-sdk-version=5.x
I'm creating a sample application that will post alerts to the website in the event of a hurricane or service outage. I'm not using Laravel.
I set the URL of the page in my account settings. The first time I sent a message I received a HTTP error that it had timed out without being given a reponse. I edited the XML and tried again.
I'm not getting anything in the database and I'm not getting the response. I also wrote a sample page that posts a value to see if it would work and it did. It posted it into the database and showed correctly formatted XML.
<?php
$response = 'This number cannot handle automated replies...';
$twiml1 = '<response><sms>';
$twiml2 = '</sms></response>';
require_once '../settings/db.php';
if (isset($_POST['body'])) {
$body = strip_tags($_POST['body']);
$sql = "INSERT INTO alerts (message) VALUES ('$body')";
$result = $db->query($sql);
if ($result) {
$response = 'Thanks. Your message was posted on the website.';
} else {
$response = 'There was a query error.';
}
}
header('Content-type: application/xml');
echo $twiml1;
echo $response;
echo $twiml2;
Twilio developer evangelist here.
Parameters that are sent via webhooks from Twilio are case sensitive and start with a capital letter. The text for an incoming message is sent as the Body parameter so checking for $_POST['body'] won't work.
I'd update your conditional to:
if (isset($_POST['Body'])) {
$body = strip_tags($_POST['Body']);
// The rest
}
Also, just to note, the <Sms> element has been deprecated. I'd use the <Message> element instead. The tags are case sensitive too, so I'd update the TwiML section to this:
$twiml1 = '<Response><Message>';
$twiml2 = '</Message></Response>';
Let me know if that helps at all.
I am new in MQTT so can someone help me for connecting MQTT with Mosquitto using javascript i am using this code but it give error...
Connection failed: AMQJS0007E Socket error:undefined.
My Code is :
<script type='text/javascript' src='jquery-1.10.1.js'></script>
<script type='text/javascript' src="mqttws31.js"></script>
var client = new Messaging.Client("ns.testingindia.tld", 1883, "myclientid_" + parseInt(Math.random() * 100, 10));
//Gets called if the websocket/mqtt connection gets disconnected for any reason
client.onConnectionLost = function (responseObject) {
//Depending on your scenario you could implement a reconnect logic here
alert("connection lost: " + responseObject.errorMessage);
};
//Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function (message) {
//Do something with the push message you received
$('#messages').append('Topic: ' + message.destinationName + ' | ' + message.payloadString + '');
};
//Connect Options
var options = {
timeout: 3,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
document.write("Connection failed: " + message.errorMessage);
alert("Connection failed: " + message.errorMessage);
}
};
//Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
var publish = function (payload, topic, qos) {
//Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
client.send(message);
}
//]]>
You are connecting to port 1883 which is the default MQTT port. I assume you mean to use Websockets, and that would typically be configured on a different port number. If the broker you're using has Websocket support, ensure you connect to the correct port with Messaging.Client().
If you're using the Mosquitto broker, you'll need version 1.4 from its bitbucket repository for Websocket support, but note that Mosquitto 1.4 hasn't yet been released.
A quick way to test that your broker isn't causing the problem is to connect to broker.mqttdashboard.com port:8000 if that doesn't work my next guess is that you have just mosquitto installed and no websockets server, which you need if you want to use JS to connect directly to the broker over the web.
Another, but quicker way to get up and running now is downloading hivemq (trial version supports 25 connections) it has a mqtt broker with websockets built in and will run on windows and will be up and running in 5 mins.
Which version of Mosquitto are you using?
The current release version (1.3.4) does not natively support Websockets (next version will)
You can use something like lighttpd with mod_websockets to supply websocket support (instructions for linux are linked to from here: http://test.mosquitto.org/ws.html) or you can build a new version of Mosquitto from the head of the source tree
I work with socket.io 1.0 and maybe I'm wrong with my conception.
Actually, I open a namespace server side with
var nsp = io.of('/myNamespace');
And clients connect with
var socket = io.connect('http://localhost/myNamespace');
I can start communication without problems.
Server side I catch signals with
nsp.on('connection', function(socket){
socket.on('disconnect', function(){
//problem here
});
});
In the disconnect I would like to disconnect all sockets connected to my namespace, so i tried to do
for(var myParticipantID in io.sockets.adapter.nsp.connected)
{
io.sockets.adapter.nsp.connected[myParticipantID].disconnect();
}
but it doesn't work ... I don't have error but clients still connecting
I tried with
io.sockets.nsp.clients();
but I have error since socket.io 1.0
I don't want to create room, but maybe it's my mistake?
Thanks for your help,
MagicDenver
If it would help somebody,
I work with node js so I created a value:
app.set(idNameSpace,[]);
and push socket when I have a new connection
You should use the io.of(namespace) function to get connected clients.
for (var id in io.of('/namespace').connected) {
var s = io.of('/namespace').connected[id];
s.disconnect();
}
If you don't know the namespace and you are in a socket.on statement, you can use socket.nsp.connected instead of io.of('/namespace').connected
I'm having a strange problem with ZeroMQ, in which some messages get stuck, and just get unstuck when new messages arrive. It's like the new messages push the stuck messages on the door (terrible comparison, i know).
My code is quite simple:
rep.php
$context = new ZMQContext;
$receiver = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver->connect("tcp://localhost:8022");
$receiver2 = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver2->connect("tcp://localhost:8024");
for (;;) {
echo $receiver->recv() . PHP_EOL;
echo $receiver2->recv() . PHP_EOL;
}
cnt.php and cnt2.php (same code, different ports)
$context = new ZMQContext;
$work = new ZMQSocket($context, ZMQ::SOCKET_PUSH);
$work->bind('tcp://*:8022');
$work->send('Hello World');
cnt.php sends to 8022 and cnt2.php to 8024. They get executed from time to time and send messages to rep.php. However, some messages get stuck. If i sent 4 messages from cnt.php, nothing is received, but when i send 1 from cnt2.php, i get 5 messages at once. Any ideas?
I am no PHP expert here but guessing the syntax and functionality. Please correct me if I am wrong
echo $receiver->recv() . ' - ' . $receiver2->recv();
recv() should be a blocking call.
$receiver->recv() blocks until some message is received.
But echo does not echo the message immediately
You are again blocked on $receiver2->recv()
Only when you send message from the other file does echo work because it is waiting on $receiver2->recv()
Since you want to process the socket recv() independently, you should use polling or event based asynchronous I/O.
[Attempted solution]
$poll = new ZMQPoll();
$poll->add($receiver, ZMQ::POLL_IN);
$poll->add($receiver2, ZMQ::POLL_IN);
$readable = $writeable = array();
while(true) {
$events = $poll->poll($readable, $writeable);
foreach($readable as $socket) {
$message = $socket->recv();
echo $message, PHP_EOL;
}
}
Adapted from : http://zguide.zeromq.org/php:rrbroker