'How to Render live member count to ejs file
I'm trying to get the memberCount from my discord bot to be sent to my home.js file but I cannot find a way to send the live memberCount from the async arrow function to a variable in order to render it to my home.js file.
The error I get:
TypeError: Cannot read property 'memberCount' of undefined in discord.js
The code:
const express = require("express");
const bodyParser = require("body-parser");
const { Client, Guild, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const tracks = require(__dirname + '/tracks.js')
require("dotenv").config();
const app = express();
// members check up
const guild = client.guilds.cache.get('797158503247511592');
const memberCount = guild.memberCount;
const members = memberCount.toLocaleString();
console.log(members)
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.get("/", function(req, res){
res.render("home");
});
app.listen(3000, function(){
console.log("Server started on port 3000.");
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log(`${client.guild}`)
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(process.env.TOKEN);
Solution 1:[1]
This is because the you try to get the guild before the client is even logged in... Hope this helps
const express = require("express");
const bodyParser = require("body-parser");
const { Client, Guild, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const tracks = require(__dirname + '/tracks.js')
require("dotenv").config();
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.get("/", function(req, res){
res.render("home");
});
app.listen(3000, function(){
console.log("Server started on port 3000.");
});
let membercount = 0
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
membercount = client.guilds.cache.get('797158503247511592').memberCount
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(process.env.TOKEN);
console.log(membercount)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
