【问题标题】:Error: 401: Bot Token is required - Telegram - Telegraf错误:401:需要机器人令牌 - 电报 - Telegraf
【发布时间】:2022-08-18 19:43:45
【问题描述】:

我正在为博彩平台制作一个机器人:火焰网谁向谁发送投注信号电报但它在令牌,即使我把令牌放在.env,它不工作!谁可以帮我?

.env.example

PORT = 3000
TOKEN = #####################
CHANNEL_NAME = -1772325150

DATABASE_URL=\"mysql://userDatabase:password@localhost:port/nameDatabase\"

CreateBot.ts

import { Telegraf } from \"telegraf\"
import { ConfigsController } from \"../useCases/configs/ConfigsController\"
import { ConfigsUseCase } from \"../useCases/configs/ConfigsUseCase\"
import { CountsUseCase } from \"../useCases/counts/CountsUseCase\"



interface IMessage {
    countGreen?: number
    countRed?: number
    color?: string
    message: string
}

interface IDataCount {
    id: string
    countWhite: number
    countGreen: number
    countRed: number
    countGale1: number
    countGale2: number
    totalWin?: number
    totalSent?: number
    percentageWin?: number
}

class Bot {
    start: string
    bots: Telegraf

    constructor() {
        this.start = \"Bot On! ????\"
        this.bots = new Telegraf (process.env.TOKEN)
    }

    public async inital() {

        try {
            this.bots.launch();

            process.once(\"SIGINT\", () => this.bots.stop(\"SIGINT\"));
            process.once(\"SIGTERM\", () => this.bots.stop(\"SIGTERM\"));
        } catch (error) {
            console.log(\"Error in connection of API!\")
        }
    }

    async sendMessage({ countGreen, countRed, color, message }: IMessage) {
        try {
            const messageId = await this.bots.telegram.sendMessage(process.env.CHANNEL_NAME, message, { parse_mode: \'HTML\' })

            return messageId.message_id
        } catch (error) {
            console.log(\"Error send message!\")
        }

    }

    async deleteMessageWithID(messageID: any) {
        try {
            await this.bots.telegram.deleteMessage(process.env.CHANNEL_NAME, messageID)
        } catch (error) {
            console.log(\"Error in delete message!\")
        }
    }

    async commandBot() {
        this.bots.start(async (ctx) => {
            await ctx.reply(`???? Bem vindo ao ${ctx.botInfo.first_name} ????\\n\\n/padrao Ver as configurações do Bot.\\n\\n/config Cadastrar e alterar as configs do Bot.\\n\\n/resultado Envia relatório no canal.\\n<i>Você pode passar uma data\\nExemplo: \'24/01/2022\', se não vai\\nser enviado com a data do dia.</i>\\n\\n/help Ajuda.`, { parse_mode: \'HTML\' })
        })

        this.bots.help(async (ctx) => {
            await ctx.reply(`???? Bot Comandos ????\\n\\n/padrao Ver as configurações do Bot.\\n\\n/config Cadastrar e alterar as configs do Bot.\\n\\n/resultado Envia relatório no canal.\\n<i>Você pode passar uma data\\nExemplo: \'24/01/2022\', se não vai\\nser enviado com a data do dia.</i>`, { parse_mode: \'HTML\' })
        })

        this.bots.command(\"padrao\", async (ctx) => {
            const configUseCase = new ConfigsUseCase()
            const configs = await configUseCase.show()

            if (configs !== null) {
                const { activo, standard } = await configUseCase.show()
                await ctx.reply(`???? Bot Configs ⚙️\\n\\n<b>Bot:</b> ${activo ? \"Ativado\" : \"Desativado\"}\\n<b>Padrão:</b> ${Number(standard)}`, { parse_mode: \'HTML\' })
                return
            }
            await ctx.reply(`Você precisa configurar seu bot\\n\\n/config`, { parse_mode: \'HTML\' })
        })

        this.bots.command(\"resultado\", async (ctx) => {
            const [command, date] = ctx.message.text.split(\" \")
            const countUseCase = new CountsUseCase()
            const data = await countUseCase.getCounts(date)

            if (data.length === 0) {
                console.log(\"Sem registro\")
                await ctx.reply(`???? Resultados até agora! ????\\n\\n⛔<b>Sem registro</b>\\n\\n✅Acertos: <b>0</b>\\n❌Não Bateu: <b>0</b>\\n\\n????Primeira Entrada: <b>0</b>\\n1️⃣Primeira Gale: <b>0</b>\\n2️⃣Segunda Gale: <b>0</b>\\n⚪Winn Branco: <b>0</b>\\n\\n <b>0% de aproveitamento!</b>`, { parse_mode: \'HTML\' })
                return
            }

            const { greenWhite, green, red, gale1, gale2, totalWin, totalSent, percentageWin } = await this.calculateCounts(data)

            const message = `???? Resultados até agora! ????\\n\\n✅Acertos: <b>${totalWin}</b>\\n❌Não Bateu: <b>${red}</b>\\n\\n????Primeira Entrada: <b>${green}</b>\\n1️⃣Primeira Gale: <b>${gale1}</b>\\n2️⃣Segunda Gale: <b>${gale2}</b>\\n⚪Winn Branco: <b>${greenWhite}</b>\\n\\n <b>${Math.round(100 - percentageWin)}% de aproveitamento!</b>`
            await this.sendMessage({ message })
            await ctx.replyWithHTML(`???? <b>Relatório enviado!</b>`)
            return
        })

        this.bots.command(\"config\", async (ctx) => {
            const configUseCase = new ConfigsUseCase()
            const configs = await configUseCase.show()

            const configsController = new ConfigsController()

            const respone = ctx.message.text.split(\" \")
            const [_, botName, password, newDefault, activo] = ctx.message.text.split(\" \")
            const newActivo = activo === \"ativado\" ? true : false

            if (respone.length !== 5) {
                await ctx.reply(\"⚠️ <b>Parametros Errados!</b>\\n\\nEnviar da seguinte maneira:\\n\\n<b>Comando:</b> /config\\n<b>Bot:</b> nome do seu bot\\n<b>Senha:</b> senha de acesso\\n<b>Padrão:</b> número do seu padrão, ex. 3\\n<b>Ativo:</b> ativado ou desativado\\n\\n<b>Exemplo:</b> /config blaze-bot abc123 4 ativado\", { parse_mode: \'HTML\' })
                return
            }

            switch (activo) {
                case \"ativado\":
                case \"desativado\":
                    if (configs === null) {
                        await configsController.create({ name: botName, standard: Number(newDefault), activo: newActivo, password: password.toString() })
                        await ctx.reply(`⚠️ Atenção ⚠️\\n\\nCadastro realizado!`, { parse_mode: \'HTML\' })
                        return
                    }

                    if (configs.password === password && configs.name === botName) {
                        await configsController.create({ name: botName, standard: Number(newDefault), activo: newActivo, password: password.toString() })
                        await ctx.reply(`⚠️ Atenção ⚠️\\n\\nParâmetros Alterados\\n\\n<b>Bot:</b> ${newActivo ? \"Ativado\" : \"Desativado\"}\\n<b>Padrão:</b> ${Number(newDefault)}`, { parse_mode: \'HTML\' })
                        return
                    }
                    await ctx.reply(`⚠️ Atenção ⚠️\\n\\nNome do Bot ou Senha errada!`, { parse_mode: \'HTML\' })
                    break;
                default:
                    await ctx.reply(\"⚠️ Atenção ⚠️\\n\\nInforme se o BOT está \\n<b>ativado</b> ou <b>desativado</b>\", { parse_mode: \'HTML\' })
                    break;
            }
        })
    }

    async calculateCounts(data: Array<IDataCount>) {
        let greenWhite = null
        let green = null
        let red = null
        let gale1 = null
        let gale2 = null

        data.forEach(async counts => {
            greenWhite = greenWhite + counts.countWhite
            green = green + counts.countGreen
            red = red + counts.countRed
            gale1 = gale1 + counts.countGale1
            gale2 = gale2 + counts.countGale2
        })
        let totalWin = green + greenWhite + gale1 + gale2
        let totalSent = totalWin + red
        let percentageWin = Math.round((red * 100) / totalSent)

        return {
            greenWhite,
            green,
            red,
            gale1,
            gale2,
            totalWin,
            totalSent,
            percentageWin
        }
    }
}

export { Bot }

我已经更改了机器人令牌,但它仍然不会:

  • 创建 .env 文件不会自动加载其中的值。你在使用类似 dotenv 的东西吗?

标签: node.js typescript bots telegram prisma


【解决方案1】:

也许你不再需要答案,但无论如何

.env工作,你必须安装类似的东西dotenvhttps://github.com/motdotla/dotenv

npm install dotenv --save

require('dotenv').config()

// or

import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config()

它从一个.env 文件进入进程.env,所以在你的情况下,

this.bots = new Telegraf (process.env.TOKEN)

不起作用,因为它无法从中获取数据进程.env

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-12
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多