一:安装

npm install node-telegram-bot-api

二:引入node-telegram-bot-api和fs模块,发送本地媒体文件时需要用到

const TelegramBot = require('node-telegram-bot-api');

const fs = require('fs')

三:在Tg的BotFather机器人那里创建你的机器人,获取机器人的token,接入代码

const botToken = "5575711741:AAFHdel52xxxxxxxxxxN1N80exxxxUOaRw"

const bot = new TelegramBot(botToken, { polling: true });

bot.on('message', async (msg) => {
    //接受所有消息回调函数
    //chatId = msg.chat.chatId
})

// 发送消息
//chatId : 聊天的id
// msg: 回复的消息
//option: { reply_to_message_id: msg.message_id, parse_mode: 'HTML',                     
//            disable_web_page_preview: true } 要回复的消息id,格式化选项,是否禁用网页链接浏览
//            更多参数可以看官方文档
bot.sendMessage(chatId,msg,option) // 返回promise .then获取结果.catch获取异常

bot.sendPhoto(chatId,"string|buffer(发送的buffer文件或地址)",option)


// 发送媒体组
//chatId: 聊天的id,
//inputMedia 发送的媒体数组
//{
//    type: "photo", //photo,audio,video登
//    media: Buffer.from(fs.readFileSync('文件地址(/media/1.jpg)', 'binary'), 'binary'),
//    caption: 类似option 媒体组的标题以及标题的格式化
//}
bot.sendMediaGroup(chatId, inuptMedia)

//列出几个常用的,其他都可以类推,更多api可以自行查看文档

官方文档:

node-telegram-bot-api/api.md at release · yagop/node-telegram-bot-api · GitHubTelegram Bot API for NodeJS. Contribute to yagop/node-telegram-bot-api development by creating an account on GitHub.https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#TelegramBot

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐