在telegram中创建bot

本文介绍了如何在Node.js中创建一个基本的Telegrambot,包括获取bottoken、设置简单交互(如`hi`响应和`/start`触发的区块选择)以及处理InlineKeyboard点击事件。
摘要由CSDN通过智能技术生成

写在前面:本文只是简单的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 })
})

三、其他参考网址

https://lolipopj.github.io/2022/01/08/start-telegram-bot/

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戎码江湖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值