mtfosbot/libs/api-action/line.js

89 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-06-28 09:37:33 +00:00
const axios = require('axios')
const config = require('../../config')
const client = axios.create({
baseURL: 'https://api.line.me/v2/bot',
headers: {
Authorization: `Bearer ${config.line.access}`
}
})
2018-06-28 13:26:44 +00:00
/**
* push message to group or room or user
* @param {string} target target id (groupid, userid, roomid)
* @param {string} message push message
*/
2018-06-28 09:37:33 +00:00
const pushMessage = async (target, message = '') => {
if (typeof target !== 'string' || target.trim().length === 0) return
if (typeof message !== 'string' || message.trim().length === 0) return
let data = {
to: target,
messages: [
{
type: 'text',
text: message
}
]
}
let opts = {
method: 'post',
url: '/message/push',
data
}
await client(opts)
}
2018-07-12 16:29:41 +00:00
const textObject = (txt = '') => {
if (typeof txt !== 'string' || txt.trim().length === 0) return null
return {
type: 'text',
text: txt
}
}
2018-06-28 13:26:44 +00:00
/**
* send reply message
* @param {string} replyToken line message reply token
* @param {string} message reply message
*/
2018-06-28 09:37:33 +00:00
const replyMessage = async (replyToken, message) => {
let url = '/message/reply'
2018-07-12 16:29:41 +00:00
let regex = /^\$(.+?)\$/
let m = message.match(regex)
let obj = null
message = message.replace(/^\$.+?\$/, '')
if (m !== null && m.length > 1) {
switch (m[1]) {
case 'image':
break
case 'text':
obj = textObject(message)
break
default:
obj = textObject(message)
2018-06-28 09:37:33 +00:00
}
}
2018-07-12 16:29:41 +00:00
if (obj !== null) {
let opts = {
method: 'post',
url,
data: {
replyToken,
messages: [obj]
}
}
await client(opts)
}
2018-06-28 09:37:33 +00:00
}
module.exports = {
pushMessage,
replyMessage
}