(Need help) Discord Bot using Open AI API - node.js

Hi, this is my first time coding. I have an ecosystem I want to build but coding this discord bot is my proof of concept. I have deployed my code to google firebase and getting my bot come online in discord works fine. In my code I also have it set to where my bot only listens after you use a specific phrase to “wake it up”. You can also “put it to sleep”. However it keeps throwing errors when it comes to interfacing with the api. My api key is correct for both discord and openai. I’ve narrowed it down to the code that is actually supposed to generate the prompt, but I can’t figure out what I’m doing wrong. Any help would be greatly appreciated.

Not listing all the dependencies or setup variables because all of those work so far.

Code for completions:

 client.on("ready", () => {
    console.log(`Logged in as ${client.user.tag}!`);
  });
 client.on("messageCreate", async function (message) {
    if (message.content.toLowerCase() == 'hi jarvis') {
      listening = true;
      message.reply("Hello. Jarvis is operational. All systems go.");
      return;
    }
    if (message.content.toLowerCase() == 'bye jarvis') {
      listening = false;
      message.reply("Goodbye sir.");
      return;
    }
  });

  client.on("messageCreate", async function (message) {
    if (message.author.bot) return;
 if(listening){
    try {
      const prompt = message.content;
      const completionRequest = {
        model: "text-davinci-003",
        prompt,
        max_tokens: 1025,
        temperature: 0.7,
        top_p: 1,
        stream: true,
    };
  
    const completion = await openai.createCompletion ({
      completionRequest,
    }); 
    message.channel.send(completion.choices[0].text);
  } catch (error) {
      if (error.response) {
          console.log(error.response.status);
          console.log(error.response.data);
      } else {
          console.log(error.message)
          message.reply(error.response.data);
      }
  }
}
})

What is the error you are getting?

No clue why you are getting an error, it would probably be easier to debug with vanilla JS

Here is a low tech example:

async function openAi(apiKey, method, data) {
  let requestOptions = {
    method  : 'POST',
    headers : {
	  'Content-Type' : 'application/json',
      'Authorization': `Bearer ${apiKey}`,
    },
    body: JSON.stringify(data)
  };
  
  return await fetch(`https://api.openai.com/v1/${method}`, requestOptions).then((response) => response.json());
}


let request = {
  "model"      : "text-davinci-003",
  "prompt"     : "<input text>",
  "temperature": 0,
  "max_tokens" : 1000
}

let result = await openAi(localStorage.getItem('myApiKey'), 'completions', request);
console.log(result.choices[0].text);

PS: didn’t test this code, i ripped it out of one of my abstraction layers and edited it for easy understanding …milage may vary ^^

Did you open the web developer console in your browser and look at the JS errors in the console?

See, for example, this tutorial:

See also:

I updated my code to be this:

exports.startBot = functions.https.onRequest(async (req, res) => {
try {
await client.login(process.env.DISCORD_TOKEN);
res.send(‘BotStarted!’);
client.on(“messageCreate”, async function (message) {
if (message.content.startsWith(‘/hijarvis’)) {
listening = true;
message.reply(“Hello. Jarvis is operational. All systems go.”);
return;
}

  if (message.content.startsWith('/byejarvis')) {
    listening = false;
    message.reply("Goodbye sir.");
    return;
  }

  if (message.author.bot) return;

  if(listening){
    const prompt = message.content;
    const completionRequest = {
      model: "text-davinci-003",
      prompt,
      max_tokens: 1025,
      temperature: 0.7,
      top_p: 1,
      stream: true,
    };

    exports.messageJarvis = functions.https.onCall(async (data) => {
      const completion = await openai.createCompletion({ completionRequest });
      return completion;
    });

    async function getResponse(completion) {
      const response = await functions.https.call('messageJarvis', { text: completion });
      return response;
    }

    const response = await getResponse(completion);

    try {
      message.channel.send(response);
    } catch (error) {
      console.error(error);
      message.reply(error);
    }
  }
});

} catch (error) {
console.error(error);
res.send(error);
}
});

it threw this error:
{
“textPayload”: “Exception from a finished function: Error: Request failed with status code 400”,
“insertId”: “63cc16c10005e8631550a6dc”,
“resource”: {
“type”: “cloud_function”,
“labels”: {
“region”: “us-central1”,
“project_id”: “jarvis-69ee4”,
“function_name”: “startBot”
}
},
“timestamp”: “2023-01-21T16:45:53.387171Z”,
“labels”: {
“execution_id”: “phr2dvinpf01”,
“instance_id”: “00c61b117c00f594bd8148da604fc6fbcbc616ee94737536b3506daeca961abd634ba56ed00bf47c046622ba4f3df63ef60ce5575e97de332090”
},
“logName”: “projects/jarvis-69ee4/logs/cloudfunctions.googleapis.com%2Fcloud-functions”,
“trace”: “projects/jarvis-69ee4/traces/68c29b8db4f92410dc0d74d83c6131be”,
“receiveTimestamp”: “2023-01-21T16:45:53.393315496Z”
}

I have no idea what else to do.