Discord.js Confusion (G4F Api)

37 views Asked by At

I'm trying to make a discord chatbot using discord.js and g4f library. I mostly work with python so I'm not familiar with node.js. When I tried making the bot, I got the login and stuffs working but the bot doesn't send the message. Can anyone please review the code and tell me what I'm doing wrong?

g4f docs: https://www.npmjs.com/package/g4f

Code:

const { Client, Events, GatewayIntentBits } = require('discord.js');
const token = 'Discord-Token';
const { G4F } = require('g4f');
const g4f = new G4F();

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once(Events.ClientReady, readyClient => {
    console.log(`Succesfully logged in as ${readyClient.user.tag}`);
});

client.on('message', async (message) => {
    const userMessage = message.content;

    const messages = [
        { role:"user", content: userMessage }
    ];

    try {
        const response = await g4f.chatCompletion(messages);
        console.log(response);
        message.channel.send(response);
    } catch (error) {
        console.error("Error from g4f: ", error);
    }
})

client.login(token);

I tried the client.on("message") thing but it just doesn't send the message even with the message.channel.send(). I expected it to atleast send an error in the console but no output what so ever.

1

There are 1 answers

3
Gamelean On

Check the Permissions if he can send messages

const { Client, GatewayIntentBits } = require('discord.js');
const { G4F } = require('g4f');

const token = 'Discord-Token';
const g4f = new G4F();
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once('ready', () => {
    console.log(`${client.user.tag} online`);
});

client.on('message', async (message) => {
    
    if (message.author.bot) return;

    const userMessage = message.content;

    const messages = [
        { role: "user", content: userMessage }
    ];

    try {
        const response = await g4f.chatCompletion(messages);
        console.log(response);
        message.channel.send(response);
    } catch (error) {
        console.error("Error g4f: ", error);
        console.error("Error sending message : ", error.message);
    }
});

client.login(token);