Ben Botvinick
Ben Botvinick

Reputation: 3335

Discord.js in an Express RESTful API

I am trying to use the Discord.js library in an Express RESTful API. I'm wondering how I should share the client between controllers, because the client is initialized asynchronously and apparently it is bad practice to call client.login(...) multiple times. In other words, I have an asynchronous initialization method that I cannot call multiple times and I need to access this client across multiple controllers. Here's what I'm doing right now:

discord.helper.js

const Discord = require('discord.js');

const client = new Discord.Client();
client.login(process.env.DISCORD_BOT_TOKEN);

export default client;

My issue is that because the client.login() is asynchronous but can only be called one time, I cannot import this file with the assumption that the bot has already been initialized. Any ideas on how I should structure this module so that I can import it multiple times with the assumption that it has already been initialized?

Upvotes: 1

Views: 2652

Answers (1)

user13103906
user13103906

Reputation:

Client#login is asynchronous but it does not return a Client instance once resolved, See here

You can safely assume the client is available as long as it was able to login, however if possible I would make your Express server accept a instance of the client instead.

import { createServer } from "./server"
import { Client } from "discord.js"

const client = new Client()
const app = startServer(client)

client.login(process.env.DISCORD_BOT_TOKEN)

app.listen(3000, () => {
  console.log("Express server is listening on port 3000")
});

Example of createServer

import express from "express"

export const createServer = client => {
  const app = express()

  app.get("/", (_, res) => {
    res.send(`${client.user.username} says hello`)
  })

  return app
}

Upvotes: 1

Related Questions