(вот прототип SDK, https://github.com/cctuan/line-bot-sdk-nodejs)
По некоторым причинам мне нужно выяснить, как написать LINE-бота с использованием последнего message api, я быстро изучил документ и нашел следующие доступные ссылки SDK,
ждать …. , версии NodeJS нет? он даже предоставляет Perl one…
Как член этой компании, и мне нужна эта библиотека как можно скорее, чтобы часть моего проекта прошла гладко, я решил написать ее для себя.
На самом деле, если вы потратите больше времени на эти документы, вы не подумаете, что сложно закодировать интерфейс самостоятельно, так как он понятен и прост для понимания. Все, что вам нужно сделать, это…
- Подготовить сервер (для пробы можно создать приложение на героку)
- зарегистрировать бота
- Настроить бота
В приведенных выше шагах есть некоторые детали, но это может быть не то, чем я хочу поделиться здесь (пожалуйста, внимательно прочитайте этот документ). То, чем я хочу поделиться, — это Node SDK, который я подготовил, давайте сразу к тому, как его использовать.
Установка его в ваши node_modules — это первый шаг.
// terminal npm i [email protected]:cctuan/line-bot-sdk-nodejs.git -S
Инициализация SDK
const LineBotSDK = require('line-message-sdk'); const client = new LineBotSDK.client({ // CHANNEL_SECRET, please refer to Configure the bot channelSecret: process.env.CHANNEL_SECRET, // CHANNEL_ACCESS_TOKEN, please refer to Configure the bot channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN });
Проверить сообщения
с сервера LINE и парсить сообщения из запроса
const app = express() app.post('/', function (req, res) { const isMessageValidated = client.requestValidator( // read the X-Line-Signature from headers req.headers['X-Line-Signature'], req.body // raw body from request ) // if isMessageValidated is true, then we can say the request is // from LINE and process the request let receives = client.bodyParser(req.body); receives.forEach(function(receive) { switch (receive.type) { case LineBotSDK.EVENT_TYPES.MESSAGE: { switch (receive.message.type) { case LineBotSDK.CONTENT_TYPES.TEXT: { // text type message break; } case LineBotSDK.CONTENT_TYPES.IMAGE: { // this helps you get the rawdata of image/video/audio receive.message.contentGetter().then(function(buffer) { // buffer of the image }); break; } }); })
Ответное сообщение
Я лично предпочитаю цепочку типов в качестве отправителя, так как в приложении бота иногда мне нужно ответить/отправить много сообщений типа в одном запросе, но они составлены в другом месте логики кода. И я также предпочитаю более простой API для отправки сообщений другого типа.
Поддержка отправки различных типов сообщений боту LINE.
// send text client.to({userId: '<userId>'}).message('text').send(); // send location client.to({userId: '<userId>'}).location(title, lat, long, addr).send(); // send image client.to({userId: '<userId>'}).image(originalContentUrl, previewImageUrl).send(); // send video client.to({userId: '<userId>'}).video(originalContentUrl, previewImageUrl).send(); // send video client.to({userId: '<userId>'}).audio(originalContentUrl, duration).send(); // send sticker client.to({userId: '<userId>'}).sticker(packageId, stickerId).send(); // send templateMessage // https://devdocs.line.me/en/#template-messages client.to({userId: '<userId>'}).template(templateObject).send(); // send imagemapObject // https://devdocs.line.me/en/#imagemap-message client.to({userId: '<userId>'}).imagemap(imagemapObject).send();
Поддержка отправки на другую цель
client.to({groupId: '<groupId>'}).message('text').send(); client.to({userId: '<userId>'}).message('text').send(); client.to({roomId: '<roomId>'}).message('text').send(); // if user ids is over 150 , it will help you automatically split to // different request client.to({ids: '[<userId>]'}).message('text').send(); // you can also set the target later client.to({ids: '[<userId>]'}) .message('text') .resetTarget({userId: '<userId>'}) // it will only send to userId .send();
Поддержка отправки нескольких сообщений
client.to({groupId: '<groupId>'}) .message('text') .message('text') .image(originalContentUrl, previewImageUrl) .message('text') .sticker(packageId, stickerId) // if the messages are over 5 items, then the request will be // divided to 2 requests or more automatically. .video(originalContentUrl, previewImageUrl) .audio(originalContentUrl, duration) .send(); // you can also prepare sending message and send them later. var sendItLater = client.to({groupId: '<groupId>'}) .message('text') .message('text'); // you can do something before calling send sendItLater.send(); //send text + text // you can also revert last stored message. var sendItLater = client.to({groupId: '<groupId>'}) .message('text1') .message('text2') .message('text3') .message('text4'); sendItLater.revert(2); sendItLater.send(); // only send text1 and text2
Поддержка покинуть комнату/группу
// leave group client.to({groupId: '<groupId>'}).leave(); // leave room client.to({roomId: '<roomId>'}).leave();
Добро пожаловать, если есть какие-либо отзывы.