const axios = require('axios') const config = require('@config/index') const client = axios.create({ baseURL: 'https://api.line.me/v2/bot', headers: { Authorization: `Bearer ${config.line.access}` } }) /** * push message to group or room or user * @param {string} target target id (groupid, userid, roomid) * @param {string} message push message */ 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) } const textObject = (txt = '') => { if (typeof txt !== 'string' || txt.trim().length === 0) return null return { type: 'text', text: txt } } const imageObject = (txt = '') => { if (typeof txt !== 'string' || txt.trim().length === 0) return null txt = txt.split(';') return { type: 'image', originalContentUrl: txt[0], previewImageUrl: txt[1] } } /** * send reply message * @param {string} replyToken line message reply token * @param {string} message reply message */ const replyMessage = async (replyToken, message) => { let url = '/message/reply' let regex = /^\$(.+?)\$/ let m = message.match(regex) let obj = null message = message.replace(/^\$.+?\$/, '') if (m !== null && m.length > 1) { switch (m[1]) { case 'image': obj = imageObject(message) break case 'text': obj = textObject(message) break default: obj = textObject(message) } } else { obj = textObject(message) } if (obj !== null) { let opts = { method: 'post', url, data: { replyToken, messages: [obj] } } await client(opts) } } /** * query user info * @param {string} group group id * @param {string} id user id */ const getUserInfo = async (group = '', id = '') => { if (typeof group !== 'string' || group.trim().length === 0) return null if (typeof id !== 'string' || id.trim().length === 0) return null let url = `/group/${group.trim()}/member/${id.trim()}` try { let result = await client({ url, method: 'get' }) if ('data' in result && typeof result.data === 'object') { let {displayName, userId} = result.data if (typeof displayName !== 'string' || displayName.length === 0) return null if (typeof userId !== 'string' || userId.length === 0) return null console.log('get user result ::::: ', result.data) return { displayName, userId } } } catch (err) { console.log('get user info error :::: ', err) } return null } module.exports = { pushMessage, replyMessage, getUserInfo }