简体   繁体   English

如何设置 and.env 文件并让我的代码读取 .env 文件?

[英]How do I setup and .env file and have my code read the .env file?

I want to setup and discord bot, but I need some help setting up an.env file and modify my bot code to read the .env file.我想设置 discord 机器人,但我需要一些帮助来设置 .env 文件并修改我的机器人代码以读取.env文件。 Also, using Heroku to start hosting the bot.此外,使用 Heroku 开始托管机器人。

Code for the main.bot.js : main.bot.js的代码:

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const discord_js_1 = __importDefault(require("discord.js"));
const builders_1 = require("@discordjs/builders");
const SlashCommand_model_1 = require("./model/SlashCommand.model");
const HelpCommand_command_1 = require("./commands/HelpCommand.command");
const fs_extra_1 = __importDefault(require("fs-extra"));
const BINFlipCommand_command_1 = require("./commands/flip/BINFlipCommand.command");
var client = new discord_js_1.default.Client({ "intents": [discord_js_1.default.Intents.FLAGS.GUILDS, discord_js_1.default.Intents.FLAGS.GUILD_MEMBERS, discord_js_1.default.Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => __awaiter(void 0, void 0, void 0, function* () {
    var helpcommandbuilder = new builders_1.SlashCommandBuilder()
        .setName("help")
        .setDescription("Get the list of commands that Project: Scyll has.");
    var binflipcommandbuilder = new builders_1.SlashCommandBuilder()
        .setName("binflip")
        .setDescription("Finds a BIN snipe on the auction house based on the amount of profit you can make.")
        .addIntegerOption(option => option.setName("profit")
        .setDescription("the amount of profit you would like to make.").setRequired(true));
    SlashCommand_model_1.SlashCommand.CreateSlashCommands([helpcommandbuilder, binflipcommandbuilder]);
}));
client.on('interactionCreate', function (interaction) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!interaction.isCommand())
            return;
        new HelpCommand_command_1.HelpCommand(interaction);
        new BINFlipCommand_command_1.BINFlipCommand(interaction);
    });
});
client.login(process.env.SERVER_BOT_KEY);

Code for my .env file that I tried to make:我尝试制作的.env文件的代码:

SERVER_BOT_KEY=samplebottoken75686
SERVER_CLIENT_ID=sampleclientid

and also need some help fixing the .env thing on this file as well.并且还需要一些帮助来修复此文件上的.env内容。

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlashCommand = void 0;
const discord_js_1 = require("discord.js");
const axios = __importStar(require("axios"));
const rest_1 = require("@discordjs/rest");
const v9_1 = require("discord-api-types/v9");
const fs_extra_1 = __importDefault(require("fs-extra"));
var token = process.env.SERVER_BOT_KEY;
class SlashCommand {
    constructor(interaction) {
        this.http = axios.default;
        this.interaction = interaction;
        this.command = interaction.commandName;
        this.purple = "#BA55D3";
        this.backtick = "`";
        this.gold = "#d4af37";
        this.red = "#C70039";
    }
    CreateEmbed() {
        return new discord_js_1.MessageEmbed()
            .setAuthor("Project: Scyll", this.interaction.client.user.avatarURL()).setFooter("Project:Scyll 0.1.0").setTimestamp();
    }
    static CreateSlashCommands(commands) {
        return __awaiter(this, void 0, void 0, function* () {
            var clientid = process.env.SERVER_CLIENT_ID;
            yield SlashCommand.REST.put(v9_1.Routes.applicationCommands(clientid), { "body": commands });
        });
    }
}
exports.SlashCommand = SlashCommand;
SlashCommand.REST = new rest_1.REST({ "version": "9" }).setToken(token);

I put in client.login(process.env.SERVER_BOT_KEY);我输入了client.login(process.env.SERVER_BOT_KEY); and the bot still doesn't go online.并且机器人仍然没有在线 go。 I put “dotenv”: “^14.3.0” in my package.json .我把“dotenv”: “^14.3.0”放在我的package.json中。 I also did it in Heroku, in the Config Vars section.我还在 Heroku 的 Config Vars 部分中进行了此操作。

What am I doing wrong?我究竟做错了什么?

If you've updated your code to use process.env.SERVER_BOT_KEY and set a SERVER_BOT_KEY config var on Heroku, your app should work there.如果您已更新代码以使用process.env.SERVER_BOT_KEY并在 Heroku 上设置SERVER_BOT_KEY配置变量,那么您的应用程序应该可以在那里工作。 Heroku doesn't need dotenv or use an .env file. Heroku 不需要dotenv或使用.env文件。

This won't be enough locally, though.但是,这在本地是不够的。 You have installed dotenv and created your .env file, but it doesn't sound like you've actually imported and used it :您已经安装了dotenv并创建了.env文件,但听起来您实际上并没有导入并使用它

  1. As early as possible in your application, import and configure dotenv.尽早在您的应用程序中导入和配置 dotenv。

     // index.js require('dotenv').config() console.log(process.env) // remove this after you've confirmed it working

Make sure to require('dotenv').config() in your code.确保require('dotenv').config()在您的代码中。

Ideally, that can be done once in a shared startup file but I can't tell from the code you shared above if you have something like that.理想情况下,这可以在共享的启动文件中完成一次,但如果你有类似的东西,我无法从你上面共享的代码中判断出来。 That code looks like it was generated by a tool of some kind.该代码看起来像是由某种工具生成的。

Note that your .env file should not be tracked.请注意,不应跟踪您的.env文件。 Make sure to add it to your .gitignore .确保将其添加到您的.gitignore中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM