Node.js 如何创建Telegram Chatbot
在本文中,我们将讨论如何使用Node.js创建一个Telegram聊天机器人,借助Telegram的帮助,我们可以创建任意数量的机器人,并根据我们的需求进行配置。目前,Telegram中的机器人主要用于保护用户免受垃圾信息,或在Telegram群组中维护隐私。
让我们了解如何注册Telegram机器人。对于每个Telegram机器人,我们都需要一个机器人令牌,该令牌负责与Telegram机器人的管理员进行通信和身份验证。让我们了解为Telegram机器人生成新的机器人令牌的步骤。
生成Telegram机器人令牌的步骤:
步骤1: 转到Telegram并搜索Bot Father。这是Telegram中的一个机器人,负责为每个新机器人生成唯一令牌。
步骤2: 打开Bot Father后输入/start,并点击/newbot
步骤3: 现在输入机器人的名称,它必须是唯一的。
记住: 出于安全考虑,不要与任何人共享此标记。
步骤4: 现在只需从BotFather复制令牌。要删除令牌,只需在BotFather中搜索/删除令牌。
让我们了解如何使用此令牌创建新机器人:
项目结构:
文件名: bot.js
const token = 'Enter the token';
let TelegramBot = require('node-telegram-bot-api');
let bot = new TelegramBot(token, { polling: true });
// Matches "/echo [whatever]"
bot.onText(/\/echo(.+)/, (msg, match) => {
// The 'msg' is the received Message from Telegram
// and 'match' is the result of executing the regexp
// above on the text content of the message
let chatId = msg.chat.id;
// The captured "whatever"
let resp = match[1];
// send back the matched "whatever" to the chat
bot.sendMessage(chatId, resp);
});
运行该应用程序的步骤: 在终端中输入以下代码来运行应用程序:
node bot.js
输出: