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

**URL:** <https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546>\
**Category:** API\
**Created:** [January 20, 2023, 3:06pm UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546 "2023-01-20T15:06:33Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![nik1](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/nik1/32/19720_2.png) [@nik1](https://community.openai.com/u/nik1)\
**Post date:** [January 20, 2023, 3:06pm UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546/1 "2023-01-20T15:06:33Z")

</div>

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:

```auto
 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);
      }
  }
}
})

```

---

<div class="post-metadata">

**Author:** ![logankilpatrick](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/logankilpatrick/32/14116_2.png) [@logankilpatrick](https://community.openai.com/u/logankilpatrick)\
**Post date:** [January 20, 2023, 4:09pm UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546/2 "2023-01-20T16:09:13Z")

</div>

What is the error you are getting?

---

<div class="post-metadata">

**Author:** ![i-technology](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/i-technology/32/21608_2.png) [@i-technology](https://community.openai.com/u/i-technology)\
**Post date:** [January 20, 2023, 7:49pm UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546/3 "2023-01-20T19:49:27Z")

</div>

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

Here is a low tech example:

```auto
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 ^^

---

<div class="post-metadata">

**Author:** ![ruby\_coder](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/ruby_coder/32/19875_2.png) [@ruby\_coder](https://community.openai.com/u/ruby_coder)\
**Post date:** [January 21, 2023, 2:54am UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546/4 "2023-01-21T02:54:45Z")

</div>

> [@nik1](#):
>
> 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.

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

See, for example, this tutorial:

> **[Fix JavaScript errors that are reported in the Console - Microsoft Edge...](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/console-debug-javascript)**
>
> Debugging and resolving JavaScript-related errors that are reported in the Console.

See also:

> **[Debug JavaScript - Chrome for Developers](https://developer.chrome.com/docs/devtools/javascript/)**
>
> Learn how to use Chrome DevTools to find and fix JavaScript bugs.

---

<div class="post-metadata">

**Author:** ![nik1](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/nik1/32/19720_2.png) [@nik1](https://community.openai.com/u/nik1)\
**Post date:** [January 21, 2023, 4:51pm UTC](https://community.openai.com/t/need-help-discord-bot-using-open-ai-api-node-js/41546/6 "2023-01-21T16:51:47Z")

</div>

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.
