From dab55685deda41e8cac6a9a64d5c4d3edd0d4f5c Mon Sep 17 00:00:00 2001 From: jimmytai Date: Wed, 17 Jul 2024 17:01:28 +0800 Subject: [PATCH] replyCalc --- line/handler/index.js | 1 + line/handler/replyCalc.js | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 line/handler/replyCalc.js diff --git a/line/handler/index.js b/line/handler/index.js index 817f2d4..6759870 100644 --- a/line/handler/index.js +++ b/line/handler/index.js @@ -8,6 +8,7 @@ const lineEventHander = middlewareCompose([ require('./cmd'), // 處理指令 require('./replyFlexFromText'), // 嘗試回傳 flex require('./noReplyUrl'), // 如果是一個合法的 URL 就不作回應 + require('./replyCalc'), // 計算數學式 require('./replyEventJson'), // 把事件用 json 回傳 ]) diff --git a/line/handler/replyCalc.js b/line/handler/replyCalc.js new file mode 100644 index 0000000..52c74d3 --- /dev/null +++ b/line/handler/replyCalc.js @@ -0,0 +1,15 @@ +const _ = require('lodash') +const msgText = require('../msg/text') + +module.exports = async (ctx, next) => { + const text = ctx?.event?.message?.text + try { + if (!_.isString(text)) throw new Error('Not a string') + if (/[^0-9!.()*/&%^+<>|~A-Fa-fnoOxX -]/.test(text)) throw new Error('Not a arithmetic string') + const result = new Function(`return ${text}`)() // eslint-disable-line no-new-func + await ctx.replyMessage(msgText(`${result}`)) + } catch (err) { + // console.log(err) + return await next() + } +}