写在前面:本文只是简单的demo,具体请结合自身业务开发
一.初始创建bot
参考:https://sendpulse.com/knowledge-base/chatbot/telegram/create-telegram-chatbot
按照流程逐步执行即可,创建完成之后获取bot token
二.nodejs实现简单交互
1.安装node环境
2.在本地执行以下脚本node [name]
备注:在token处填上自己的bot token
脚本实现的功能:
a.订阅者输入hi返回指定信息hello
b.实现点击事件,输入/start会在telegram的bot界面展示div块,订阅者点击之后发送指定信息“请选择一个区块”
const TelegramBot = require('node-telegram-bot-api')
// replace the value below with the Telegram token you receive from @BotFather
const token = ''
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true })
// Matches "/echo [whatever]"
// bot.onText(/\/echo (.+)/, (msg, match) => {
bot.onText(/\/start/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id
// 创建一个Inline Keyboard
const inlineKeyboard = {
reply_markup: {
inline_keyboard: [
[
{ text: '区块1', callback_data: '1' },
{ text: '区块2', callback_data: '2' }
]
]
}
}
// 发送消息并附加Inline Keyboard
bot.sendMessage(chatId, '请选择一个区块:', inlineKeyboard)
})
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
const chatId = msg.chat.id
console.log("msg", msg.text)
if (msg.text === "hi") {
// send a message to the chat acknowledging receipt of their message
bot.sendMessage(chatId, 'hello')
} else {
bot.sendMessage(chatId, 'Received your message')
}
})
// 监听Inline Keyboard上按钮的点击事件
bot.on('callback_query', (callbackQuery) => {
const message = callbackQuery.message
const data = callbackQuery.data
// 基于用户点击的按钮,做出响应
const responseText = `选择的区块是: ${data}`
// 更新消息或发送新消息
bot.editMessageText(responseText, { chat_id: message.chat.id, message_id: message.message_id })
})