#Make a bot counting a word on the server (v14.7.0)

166 messages · Page 1 of 1 (latest)

fathom radish
#

Hey guys, I want to make a bot for my server only just to show how many <word> are on the server (since the bot has been invited, not earlier it's ok), and to do a calculation with that value. So I need 2 commands.
For now, I followed the discord.js guide (very useful actually), but the guide don't indicate me what I want.
I swear I read lot of sites and discord posts to resolve my problems but I didn't find anything who works (it's always failing at one moment. Ah, and english is not my native language so I have some difficulty to understand absolutely all what is saying).
Well, here is my index.js, like on the discord.js guide, and my command file. As I said, I followed the guide at first and then I tried to find how can I do what I want.
I hope some nice people will help me, I really don't where to go at this point. Thanks.

small trail
#

• What's your exact discord.js npm list discord.js and node node -v version?
• Post the full error stack trace, not just the top part!
• Show your code!
• Explain what exactly your issue is.
• Not a discord.js issue? Check out #useful-servers.

fathom radish
#

I use v18.12.1 for node

#

Ah, and if there is a french person passing here, I will be very enchanted 👀

small trail
#

you need MessageContent intent

fathom radish
#

I think I need to back up the value "count" from index.js to dukou.js but idk how

fathom radish
small trail
#

also dont nest listeners

small trail
fathom radish
#

Yes but then ? Because I already did tests with MessageContent and Idk where I had to go with that so it always failed

small trail
#

same what you did with Guilds.

fathom radish
#

I have to create a new client ?

#

Anyway, counting is another problem, here my main problem is to take a value from index.js and export it to dukou.js, to show this value when we use this command

small trail
fathom radish
fathom radish
#

Say it if you're annoyed with me :')

small trail
#

set module.exports to the count

fathom radish
#

Yes ok but it does the same

#

My problem is to incremate count every time the bot sees the word AND the command has to show this value, but idk how to make the link between index.js and dukou.js.
My error in cmd is this :
[WARNING] The command at C:(blabla)\commands\dukou.js is missing a required "data" or "execute" property.

robust relic
#

you shouldnt use nested listeners instead push the count to the array and get the value

small trail
#

why push it to the array

robust relic
#

oh wait, i didnt read the last one

#

instead use a global variable from client and increment count every time

#

and you can access it from everywhere you want

small trail
#

bad practice

fathom radish
#

So now, this line :
await interaction.reply("du coup" has been used ${count} times from (date));
is still correct ?

#

the command replies " "du coup" has been used undefined times from (date)", so apparently there is something I still have to do

small trail
robust relic
#

its a best practice instead of exporting the value

small trail
#

its not

robust relic
#

its better to use a global variable like

client.count = 0;
robust relic
small trail
fathom radish
#

Actually, using exports and import always gave me errors like "fatal: Parsing error: 'import' and 'export' may only appear at the top level" or "(node:15612) Warning: Accessing non-existent property 'count' of module exports inside circular dependency", so I prefer global variable

small trail
#

...

robust relic
#

see

small trail
#

literally just read what the first error says

#

if yall cant deal with simplest error messages i cant help ya

robust relic
#

well i think you can use exports.count thing but you need to import it like this

import { count } from '...';
#

or you can use this and export the client then you can access it by client.count

client.count = 0;
fathom radish
robust relic
#

choose either one which one is better for you

small trail
#

why do people never use interaction.client

#

client is EVERYWHERE in djs

robust relic
#

^ this also can

robust relic
fathom radish
#

Ok so now I have this, but it says me "TypeError: Cannot read properties of undefined (reading 'count')"

fathom radish
#

I just changed that

robust relic
#

no bro

fathom radish
#

:(

robust relic
#

what your do is correct

exports.count = count;
fathom radish
#

I'm so sorry, it seems to be simple but it's an enigma for me

robust relic
#

but your importing it wrong
instead

// this a default import
import count from '...';

// use this instead
import { count } from '...';
fathom radish
#

But you said I had to use global values

robust relic
#

ya but thats not what i tell you to do it

#

if you're using a variable from client you dont have to export it so you can use it like this

client.count = client.count + 1;
fathom radish
robust relic
fathom radish
#

it says "fatal: Parsing error: 'import' and 'export' may appear only with 'sourceType: module'"

#

sorry

robust relic
#

show me the updated code

fathom radish
#

const { SlashCommandBuilder } = require('discord.js');
import { count } from '../index.js';

module.exports = {
data: new SlashCommandBuilder()
.setName('dukou')
.setDescription('Compte le nombre de "du coup" écrits dans le serveur'),
async execute(interaction, client) {
await interaction.reply("du coup" has been used ${client.count} times from (date));
},
};

robust relic
#

your index

fathom radish
#

client.count = 0;

client.on('ready', () => {
client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
client.on('message', (message) => {
if (message.content.includes('du coup')) {
client.count = client.count + 1;
exports.count = count;
}
});
});

robust relic
#

you dont have to export it

robust relic
fathom radish
robust relic
#

then no one is used it

fathom radish
#

If I reach what I want because of you, I will always remember you bro

fathom radish
robust relic
#

i think you need to use a collection

#
client.counts = new Collection();
robust relic
fathom radish
fathom radish
robust relic
#

can you show both updated code

fathom radish
#
client.counts = new Collection();

client.on('ready', () => {
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
    client.on('message', (message) => {
        if (message.content.includes('du coup')) {
            client.count = client.count + 1;
            console.log(client.count);
        }
    });
});
#

for my index

#
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('dukou')
        .setDescription('Compte le nombre de "du coup" écrits dans le serveur'),
    async execute(interaction) {
        await interaction.reply(`"du coup" has been used ${interaction.client.count} times from (date)`);
    },
};```
#

for my dukou

main parcelBOT
#

Codeblocks:
```js
const Discord = require("discord.js");
// further code
```
becomes

const Discord = require("discord.js"); 
// further code

Inline Code:
`console.log('inline!');` becomes console.log('inline!');

fathom radish
#

thanks

small trail
#

why collection....

#

@fathom radish do you have GuildMessages and MessageContent intents?

robust relic
#

the normal thing, its not working

#

oh wait

small trail
robust relic
small trail
#

also u cud just do client.count++ wesh

#

considering client.count is defined as a number

robust relic
#

well @fathom radish you need to know when your bot crashed or something it will reset back to 0 times

fathom radish
small trail
#

did you pass it to intents array

#

you didnt

robust relic
fathom radish
fathom radish
#

Okay I just saw where to put them, I'm sorry

#

Ok now I have a problem with something I didn't see until now : "RangeError [BitFieldInvalid]: Invalid bitfield flag or number: undefined."

#

Ew the new font hurt my eyes

robust relic
#

show the updated code

fathom radish
#
const fs = require('node:fs');
const path = require('node:path');

// Require the necessary discord.js classes
const { Client, Collection, GatewayIntentBits, ActivityType, GuildMessages, MessageContent } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds, GuildMessages, MessageContent] });

// Events
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    }
    else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}

// Commands
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    // Set a new item in the Collection with the key as the command name and the value as the exported module
    if ('data' in command && 'execute' in command) {
        client.commands.set(command.data.name, command);
    }
    else {
        console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
    }
}

// initialize count
client.counts.set('count', 0);

client.on('ready', () => {
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
    client.on('message', (message) => {
        if (message.content.includes('du coup')) {
            client.counts.set('count', client.counts.get('count') + 1);
            console.log(client.count);
        }
    });
});


// Log in to Discord with your client's token
client.login(token);
robust relic
fathom radish
#

aaahhhh

#

Ok but I have always this "TypeError: Cannot read properties of undefined (reading 'set')"

#

for this line client.counts.set('count', 0);

robust relic
#

define ```js
client.count = 0;

#

and also what is your discord.js version ?

main parcelBOT
#

Determining your discord.js version:
npm list discord.js
• Make sure you use the right documentation for your installed verison (selector on the left)

fathom radish
#

Well, with "${interaction.client.counts}" it always shows me "undefined"

fathom radish
robust relic
#

change it to interaction.client.count

robust relic
fathom radish
#

It's always 0 now ;w;

#
// initialize count
client.count = 0;

client.on('ready', () => {
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
    client.on('message', (message) => {
        if (message.content.includes('du coup')) {
            client.count++;
            console.log(client.count);
        }
    });
});```
#
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('dukou')
        .setDescription('Compte le nombre de "du coup" écrits dans le serveur'),
    async execute(interaction) {
        await interaction.reply(`"du coup" has been used ${interaction.client.count} times from (date)`);
    },
};
robust relic
#

your event name change from message to messageCreate

#

and also dont nested listeners instead do this

client.on('ready', ...);

client.on('messageCreate', ...);
fathom radish
robust relic
#

make sure your syntax is correct

fathom radish
#

I try multiple things, like that

client.on('ready', () => {
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
    client.on('message', (messageCreate),
        if (messageCreate.content.includes('du coup')) {
            client.count++;
            console.log(client.count);
        }
    ));
));```
#

shit no

#

uh

robust relic
#

no bro

fathom radish
#
client.on('ready',
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing }),
    client.on('message', (messageCreate),
        if (messageCreate.content.includes('du coup')) {
            client.count++;
            console.log(client.count);
        }
    ));
));```
fathom radish
#

Yes but it changed nothing

client.on('ready', ...);
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
    client.on('messageCreate', ...);
        if (messageCreate.content.includes('du coup')) {
            client.count++;
            console.log(client.count);
        }
    });
});```
robust relic
#

what

#

thats a wrong syntax

#
client.on('ready', () => {
  client.user.setActivity('calculer des trucs', { type : ActivityType.Playing });
});

you need to learn how syntax work on javascript

#

i suggest you to read the guide before code

main parcelBOT
fathom radish
robust relic
fathom radish
#

Ok I just understood what you mean...
But now I have this

client.on('messageCreate',
    if (messageCreate.content.includes('du coup')) {
        client.count++;
        console.log(client.count);
    }
);```
And it says "fatal: Parsing error: Unexpected token if"
fathom radish
#

not for voice but the others

robust relic
#
client.on('messageCreate', (messageCreate) => {
// rest code here
});
fathom radish
#

I thought you told to not do that...
Anyway, now I have this again "TypeError: Cannot read properties of null (reading 'setActivity')"

#

I tried to do client.on('ready', () => { again but it didn't work

robust relic
#

updated code ?

fathom radish
#
client.count = 0;

client.on('ready',
    client.user.setActivity('calculer des trucs', { type : ActivityType.Playing }),
);

client.on('messageCreate', (messageCreate) => {
    if (messageCreate.content.includes('du coup')) {
        client.count++;
        console.log(client.count);
    }
});
robust relic
#

the ready is wrong syntax

fathom radish
#

Yea I saw but Idk where

robust relic
#

it should be a same thing like messageCreate but without the messageCreate parameter

(messageCreate) -> ()
fathom radish
#

Ok I just saw there was the problem

#

AND IT WORKS

#

Omg I will stop here for tonight

#

Thank you very very much, you were my savior @robust relic

rugged veldt
#

do note that this isn't really a server for basic javascript support

fathom radish
#

I didn't know it was a "basic javascript" problem sorry

rugged veldt
#

syntax issues are very much lack of knowledge of the language

fathom radish
#

Ok bro I understood don't be rude wtf

rugged veldt
#

i'm not rude