scythercas
@scythercas

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

.envに設定した環境変数が複数だとうまくimport出来ない。DiscordAPI×OpenAIでBot作成中

解決したいこと

Node.jsで、DiscordのBOTをつくっています。
GitHubにあげるため、.envファイルを作成して
DiscordのTokenとOpenAIのAPIキーを隠そうとしているのですが、
実行するとエラーが発生します。

おそらく原因となっているのは

const require = createRequire(import.meta.url);
require("dotenv").config({ debug: true });

const discordToken = process.env.DISCORD_TOKEN;
const openAIAPIKey = process.env.OPENAI_API_KEY;

この部分で、

- const discordToken = process.env.DISCORD_TOKEN;
- const openAIAPIKey = process.env.OPENAI_API_KEY;
+ const discordToken = "discordトークンべたがき";
+ const openAIAPIKey = "OpenAIのAPIキーべたがき";

もしくはDISCORD_TOKENだけ.envから呼び出すようにすると問題なく動くので、
恐らく複数の環境変数が呼び出せていないことが問題です。
その改善の仕方を教えてください。

発生している問題・エラー

if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
                                                   ^

Error [TokenInvalid]: An invalid token was provided.
    at Client.login (C:\Users\user1\discord-bot-to-talk-with-ai\node_modules\discord.js\src\client\Client.js:214:52)
    at file:///C:/Users/user1/discord-bot-to-talk-with-ai/index.mjs:89:8
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25) {
  code: 'TokenInvalid'
}

該当するソースコード

import axios from "axios";
import { createRequire } from "module";
import { Client, Events, GatewayIntentBits } from "discord.js";

const require = createRequire(import.meta.url);
require("dotenv").config({ debug: true });

const discordToken = process.env.DISCORD_TOKEN;
const openAIAPIKey = process.env.OPENAI_API_KEY;

// const discordToken = "discordトークンべたがき";
// const openAIAPIKey = "OpenAIのAPIキーべたがき";

const serverID = "サーバID";
const channelID = "チャンネルID";

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

// ChatGPT
async function requestChatAPI(text) {
  const headers = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${openAIAPIKey}`,
  };

  const messages = [
    {
      role: "user",
      content: text,
    },
    {
      role: "system",
      content: "あなたは作詞家です。詩を書いてください。",
    },
  ];

  const payload = {
    model: "gpt-3.5-turbo",
    max_tokens: 128, //文字数制限
    messages: messages,
  };
  const response = await axios.post(
    "https://api.openai.com/v1/chat/completions",
    payload,
    {
      headers: headers,
    }
  );
  console.log(response.data.choices[0].message.content);
  return response.data.choices[0].message.content;
}

client.once(Events.ClientReady, (c) => {
  // 起動した時に"Ready!"とBotの名前をコンソールに出力する
  console.log(`Ready! (${c.user.tag})`);
});

// client.on("guildCreate", (guild) => {});

client.on(Events.guildMemberAdd, (member) => {
  // 指定のサーバー以外では動作しないようにする
  if (member.guild.id !== serverID) return;
  member.guild.channels.cache
    .get(channelID)
    .send(`${member.user}が参加しました!`);
});

client.on(Events.MessageCreate, async (message) => {
  if (message.author.bot) return; // Botには反応しないようにする
  if (message.guild.id !== serverID) return; // 指定のサーバー以外では動作しないようにする
  if (
    message.content.includes("???") ||
    message.content.includes("。。。")
  ) {
    message.channel.send("えっとね・・・");
    const ChatGPTsReply = await requestChatAPI(message.content);
    message.reply(`お待たせしました!
    ${ChatGPTsReply}`);
  }
});

client.login(discordToken);
.env
const DISCORD_TOKEN = ABCDEFGH
const OPENAI_API_KEY = IJKLMNOP
.gitignore
node_modules/
.env
package.json
{
  "name": "discord-bot-to-talk-with-ai",
  "version": "1.0.0",
  "description": "",
  "main": "index.mjs",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Scythercas/discord-bot-to-talk-with-ai.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/Scythercas/discord-bot-to-talk-with-ai/issues"
  },
  "homepage": "https://github.com/Scythercas/discord-bot-to-talk-with-ai#readme",
  "dependencies": {
    "axios": "^1.3.5",
    "discord.js": "^14.9.0",
    "dotenv": "^16.0.3"
  },
  "type": "module"
}

どなたか宜しくお願いします

0

1Answer

.env ファイルの記法は

const DISCORD_TOKEN = ABCDEFGH
const OPENAI_API_KEY = IJKLMNOP

ではなく

DISCORD_TOKEN=ABCDEFGH
OPENAI_API_KEY=IJKLMNOP

です。

1Like

Comments

  1. @scythercas

    Questioner

    仰る通りでした、気づきませんでした。
    ご回答ありがとうございます!!!!!!

Your answer might help someone💌