realcoloride/node_characterai

Error: Already authenticated

Closed this issue · 10 comments

I've been trying to use the package on a project that I have, however, I still get the "Already authenticated" error.
Here is my code snippet.

const CharacterAI = require("node_characterai")
const characterAI = new CharacterAI()
const pogger = require("pogger")
const config = require("../../config.json")
module.exports = async (message, client) => {
    await characterAI.authenticateWithToken(process.env.CHARACTERAI_TOKEN)

    if (!message.channel.id === config.characters.jax.channel) return message.reply("You can't do this in this channel")
    if (!characterAI.isAuthenticated()) pogger.error("Can't process your request. Unauthenticated.")
    const chat = await characterAI.createOrContinueChat(config.characters.jax.id) 
    const res = await chat.sendAndAwaitResponse(message.content, true)
    message.reply(res.text)
        
  };

"Already authenticated" happens when you call authenticateWithToken() twice without using unauthenticate().
Make sure you are calling authenticateWithToken() once.

Note: if you are executing this function everytime you receive a message (from what I seem to understand), then you are authenticating and creating/continuing chats everytime which is unefficient but also wrong to use.
Make sure to use an initialize part to setup cai properly before using it

So, if I understand properly, I can initiate it in my index.js once, and that is it?

Should be. I don't have your full code but yes. Initialize your client and chat once (or only when needed) and use chat.sendAndAwaitResponse anytime to send a message to your ai.

You need to think of it as if you were on the website.

You are exporting the module as one function, to send a message. Instead of sending the message first, it authenticates first, multiple times when using the function. Move that authenticateWithToken function outside of your module.exports scripts so it only authenticates once.

Update :: I did put my Token Authentication in my index file, but, somehow, it doesnt authenticate anymore. Could it be my token who's expired?

Also, tried to export functions in a ./utils/CharacterFunc.js since, if I init a new CharacterAI() I don't find a way to use it through my whole command/event handler

Hello, do you still have issues?

Affirm! Tried to export it, but didn't figured out yet

Exported it as functions, init in "index", but stays as Already Authenticated/Unauthenticated

Could you send your code again please?

Deleted it and started from scratch, didn't went back on it yet

Ok, make sure you dont authenticate more than once. Happy coding!