如何导出和导入电报机器人功能?

时间:2019-04-03 12:07:48

标签: node.js telegram-bot

我要创建一个带有两个按钮的机器人电报。在每个按钮上,我都想挂动作。我想将这些操作转移到另一个文件。我该怎么办?

const Telegraf = require("telegraf"); 
const session = require("telegraf/session");
const Composer = require('telegraf/composer');
const bot = new Telegraf('Token')
const first = require('./command/first');


bot.command('start', (ctx) => {
    const markdown = `
   Hi! Click on the button 1 or 2!`;
    ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
        parse_mode: 'Markdown',
        reply_markup: {
            keyboard: [
                ['1', '2'],
            ],
            resize_keyboard: true
        },
        disable_notification: false
    });
});

bot.use(session());
bot.use(Telegraf.log())
bot.on('1', first.hears()) ///myfunction command
bot.startPolling();
console.log(Telegraf.log());

和文件./command/first

module.exports = {
    hears: function () {
        console.log("debug 1");
        bot.action('1', (ctx) => {
            const markdown = ` Type some text...`;
            ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
                parse_mode: 'Markdown',
                reply_markup: {
                    keyboard: [
                        [' Back'],
                    ],
                    resize_keyboard: true
                },
                disable_notification: false
            });
        })
    }
};


但没有任何效果。启动时,机器人会立即写入debug 1 没什么..请帮助我!

1 个答案:

答案 0 :(得分:0)

首先更改:

bot.on('1', first.hears()) // on is for events

bot.hears('1', first.hears()) // hears listens for the specified string from bot

然后将/command/first中的模块重写为:

module.exports = {
  hears: function (ctx) {
    console.log("debug 1");
    // Added markdown formatting
    const message = `*Bold text* and _italic text_`;

    ctx.telegram.sendMessage(ctx.message.chat.id, message, {
      parse_mode: 'Markdown',
      reply_markup: JSON.stringify({ // You also missed JSON.stringify()
        keyboard: [
            [' Back'],
        ],
        resize_keyboard: true
      }),
      disable_notification: false
    });
  }
}

这应该有效。我希望这会有所帮助。