I wonder if there is any way to access a Discord.Client
instance from another file.
What I've tried:
posts.js
const express = require('express')
const router = express.Router()
router.post('/checkRole', function (req, res) {
const guild = client.guilds.find(guild => guild.id === '688678156374044803');
let member = guild.members.get(req.body.id); // member ID
// Here I get an error which says the 'guild' is undefined.
res.send(response);
});
module.exports = router
index.js
const Discord = require("discord.js");
global.client = new Discord.Client();
const express = require('express');
const postsRoute = require('./routes/posts')
app = express()
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/posts', postsRoute)
/* ... some other code ... */
client.login(config.token);
app.listen(8080);
module.exports = { client }
I've also tried a similar approach like this but it didn't work either. Lastly I tried to store the client instance as a global variable but still no luck. Is there any way to achieve this?
It seems like the problem is not the fact that you can't properly export the client, but that the code that you want to use it with runs when the client is not ready yet: in fact, you're getting an error that says that no guild was found with the .find
method, but it means that the client has the .guilds
property and a .find
method.
The client exists, the problem is that your code run before the ready
event is fired: to avoid that, you can require your module inside the ready
event handler. Here's an example:
// index.js
client.on('ready', () => {
const postsRoute = require('./routes/posts')
let app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use('/posts', postsRoute)
app.listen(8080);
})