WebSockets?

Jaxel

Well-known member
I'm writing some scripts for a Discord bot for my website. Almost everything I've done with the bot has worked perfectly fine. Unfortunately, in order to CREATE things with the API, you have to go over their REST endpoints. People on the Discord Dev server have informed me that in order to get access to the REST endpoints on the Discord API, I must have my bot connect to the Discord gateway at least once over websockets. Now I know nothing about websockets; its not anything I've ever done or had to use. But I need to send a single websocket heartbeat to the Discord gateway.

Someone on the Dev server, gave me this code to run on NodeJS:
Code:
"use strict";
var token="PUT YOUR TOKEN HERE",

WebSocket = require("ws"), ws = new WebSocket("wss://gateway.discord.gg/?encoding=json&v=6"), sequence = 0;
ws.onopen = function() {
    return console.log("OPEN!")
}, ws.onerror = function(a) {
    console.error(a), process.exit(1)
}, ws.onclose = function(a) {
    console.error(a), process.exit(1)
}, ws.onmessage = function(a) {
    try {
        var b = JSON.parse(a.data);
        if (0 === b.op) return;
        console.log(b), sequence = b.s, 10 === b.op && (ws.send(JSON.stringify({
            op: 2,
            d: {
                token: token,
                properties: {
                    $browser: "b1nzy is a meme"
                },
                large_threshold: 50
            }
        })), setInterval(function() {
            ws.send(JSON.stringify({
                op: 1,
                d: sequence
            }))
        }, b.d.heartbeat_interval))
    } catch (a) {
        console.error(a)
    }
};
I would like to convert this code to PHP. Does anyone know how this would be done?
 

Pierce

Well-known member
It doesn't look like it will get any simpler than this:

https://www.html5rocks.com/en/tutorials/websockets/basics/

I've looked at using curl - doesn't work with wss

A project which already wrote the whole bot in Php which you could read to pick out the bit you need.

A full library.

I understand it's over kill but maybe making a simple HTML page you have to visit once in chrome is the simplest option here?
 

EQnoble

Well-known member
I understand it's over kill but maybe making a simple HTML page you have to visit once in chrome is the simplest option here?
That is probably is not an option unless the project using the api can make use of this "slug" html page to send the heartbeat to the endpoint (if that is even valid and able to be done in this case) and then continue on with it's business.



@Jaxel I would seriously read the link below this considering you say you have not been acquainted with websockets...I believe if you read it and notice the fact that the reply marked as a solution has an edit made years after the original post where the author says he has something he is not comfortable putting it out there yet just to get a grip on what you are attempting (though it sounds simple).

http://stackoverflow.com/questions/14512182/how-to-create-websockets-server-in-php

Now he does share something (link below) which you may be able to frankenstein into a couple of blocks that do what you need below that but I would really recommend reading the entirety of the reply first just to get a handle on where you are.

https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php
 

Arty

Well-known member
Why not just install node.js and run script once? Its rather simple.

JS as in javascript as in client side...
That hasn't been true for a while. Almost all front end development tools are built with node.js.
 

Pierce

Well-known member
Can you explain what node js is is because all I get is:

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
 

Arty

Well-known member
Short version:

php - stuff that parses php files and executes them.
node.js - stuff that parses js files and executes them.

Longer version:

There are some massive differences from php though. All because JavaScript is asynchronous language.

In PHP you run stuff synchronously, which means it parses stuff line after line. JavaScript is asynchronous language, so things don't necessary run in same order as written. For example:
Code:
console.log('We are about to read foo.txt!');
fs.readFile('foo.txt', data => {
  console.log('Got foo.txt contents:', data);
});
console.log('foo.txt has been read, right? right????');
Without knowing how JavaScript works you'd expect this output:
Code:
We are about to read foo.txt!
Got foo.txt contents: some stuff
foo.txt has been read, right? right????
but actual output would be this:
Code:
We are about to read foo.txt!
foo.txt has been read, right? right????
Got foo.txt contents: some stuff
because second parameter of fs.readFile is asynchronous callback. It will be executed when content has been read in another process, while parser goes on executing code below that function call.

Google tutorials for asynchronous execution, I'm sure you'll find plenty of them.

PHP is tied to some web server software: apache, nginx or something else. It can run as standalone app, but something needs to call it.
But node.js isn't. Because of asynchronous nature of JavaScript, Node.js can do multiple tasks at the same time. That makes it very powerful. It can be used for
  • To create web server without needing to use apache, nginx or anything else.
  • Store shared data for multiple separate connections without using database. Everything is based on async callbacks, so there are plenty of possibilities.
  • You can use same code on client and server. There are minor differences, but overall its doable if your script is well written and does not rely on system stuff.
JavaScript cannot access files or processes or anything else that PHP can. But Node.js has built in support for that, like this: https://nodejs.org/api/fs.html

It can be ran on server, it can be used as build tool, it can be ran on client side.

I hope this short explanation is clear enough and it helps.
 

Robust

Well-known member
JavaScript has long since went on to do a lot more than scripts for a web page.

For example:
And of course node js as Arty mentioned above.
 

Jaxel

Well-known member
Several of my clients have tried the TAC and it seems buggy as all hell. That's why I was hoping you'd release yours. I know @Russ plans to put one out at some point, guess I'll just have to wait for that then.
Yeah, mines kinda hacky too... Not as polished as TAC's version... Maybe I'll consider cleaning it up a bit.
 

Pierce

Well-known member
OK so this js is server side and/or client side.

Hmm must look into it.

The problem I have with the libraries mentioned make it possible to do a lot but it's like using a 10lb sledge at full force to hammer in a tack in drywall.
 

Arty

Well-known member
Or you can look at it as using one universal tool to do multiple tasks instead of using dozen of tools. :)

Unfortunately its not mature enough to replace php yet, but I think it might be in future. Many websites are already using it.
 

Pierce

Well-known member
I've had a case that I needed to use angular to implement something.

I used to have one problem but then I had 2...

I just think the reality is that the "internet" is moving at an incredible pace forward. It's a lot for any individual to keep track of.

Thanks @Arty
 

NixFifty

Well-known member
Several of my clients have tried the TAC and it seems buggy as all hell. That's why I was hoping you'd release yours. I know @Russ plans to put one out at some point, guess I'll just have to wait for that then.
It's me that's about to release one, not @Russ. :)

Should be dropping a beta for that in the coming days.
 
Top