Making an discord bot with web support

Hi im making an discordbot with web support i wanted to make a websocket om my pc it works fine but when i upload it it doesnt work anymore.
the problem is that glitch keeps giving the startup menu

bot.js:

const express = require('express');
const app = express();
const WS = require('./ws/ws')



bot.config = config

var ws = new WS(config.ws.token, config.ws.port, bot)


bot.on('ready', () => {
    console.log(`Connected as ${bot.user.tag}`)
})

ws.js: in folder ws

const express = require('express')
const hbs = require('express-handlebars')
const bodyParser = require("body-parser");
const path = require('path')

/**
 * Websocket class.
 * @param {string}         token  Token to authenticate at the web interface
 * @param {number}         port   Port to access web interface
 * @param {discord.Client} client Discord client instance to access the discord bot
 */
class WebSocket {

    constructor(token, port, client) {
        this.token = token
        this.port = port
        this.client = client
        this.app = express()

        // Register Handlebars instance as view engine
        this.app.engine('hbs', hbs({
            extname: 'hbs',                     // Extension (*.hbs Files)
            defaultLayout: 'layout',            // Main layout -> layouts/layout.hbs
            layoutsDir: __dirname + '/layouts'  // Layouts directory -> layouts/
        }))
        // Set folder views/ as location for views files
        this.app.set('views', path.join(__dirname, 'views'))
        // Set hbs as view engine
        this.app.set('view engine', 'hbs')
        // Set public/ as public files root
        this.app.use(express.static(path.join(__dirname, 'public')))
        // Register bodyParser as parser for Post requests body in JSON-format
        this.app.use(bodyParser.urlencoded({ extended: false }));
        this.app.use(bodyParser.json());

        this.registerRoots()

        // Start websocket on port defined in constructors arguments
        this.server = this.app.listen(port, () => {
            console.log("Websocket API set up at port:" + this.server.address().port)
        })
    }
  


  
  
  
    /**
     * Compare passed token with the token defined on
     * initialization of the websocket
     * @param {string} _token Token from request parameter 
     * @returns {boolean} True if token is the same
     */
    checkToken(_token) {
        return (_token == this.token)
    }

    /**
     * Register root pathes
     */
    registerRoots() {
        this.app.get('/', (req, res) => {
            var _token = req.query.token
            if (!this.checkToken(_token)) {
                // Render error view if token does not pass
                res.render('error', { title: "Wrong inlog token." })
                return
            }

            // Collect all text channels and put them into an
            // array as object { id, name }
            var chans = []
            this.client.guilds.first().channels
                .filter(c => c.type == 'text')
                .forEach(c => {
                    chans.push({id: c.id, name: c.name})
                })
    
            // Render index view and pass title, token
            // and channels array
            res.render('index', { 
                title: "Main menu", 
                token: _token, 
                chans 
            })
        })
    
        this.app.post('/sendMessage', (req, res) => {
            var _token = req.body.token
            var channelid = req.body.channelid
            var text = req.body.text

            if(!_token || !channelid || !text)
                return res.sendStatus(400);
    
            if (!this.checkToken(_token))
                return res.sendStatus(401)
    
            var chan = this.client.guilds.first().channels.get(channelid)
    
            // catch post request and if token passes,
            // send message into selected channel
            if (chan) {
                chan.send(text)
                res.sendStatus(200)
            } else
                res.sendStatus(406)
        })
    }

}

module.exports = WebSocket

MOD EDIT: formatting

BTW im using handlebars too

Hey @WeasselDW it’s a little hard to get a sense of the flow of these disconnected pieces, but in general that constant starting problem indicates that your app’s not listening to the open port that Glitch provides. Glitch NodeJS projects look for listeners on that port and Glitch keeps trying to start your project until it sees one.

Do you see this log message output in your logs?

If so, can you tell us what it says? If not, that’s the first place to look - why is that listener not connecting?

it says the websocket us up but it doesnt work like you see at the top its loading the whole time

Yep! The port that was shown in your first image isn’t one of the ports that’s going to be open to the outside world, so it’s listening there but will never get any data from anything outside of your project and doesn’t look “up” to Glitch. By the way, I wouldn’t have enough information in the current image you have in your post - I only was able to catch this because I caught your image before you changed it.

We only expose a single port to the outside. It’s typically 3000, but can change under certain circumstances. Node’s process.env.PORT will contain the currently open port by default (as long as you haven’t overridden that env variable elsewhere in your code). If you use that when you call new WebSocket() that might help.

thanks i put the port at 3000 and it works!

1 Like