'use strict' /** * Copyright (c) 2017~2024, OBCon Inc. * All rights reserved. */ /** * @file * @copyright 2017~2024, OBCon Inc. * @author gye hyun james kim [pnuskgh@gmail.com] */ const moment = require('moment'); //--- 'YYYY-MM-DD HH:mm:ss.SSS ZZ' const fetch = require('node-fetch'); //--- https://core.telegram.org/bots/api class Telegram { constructor() { this._bot = config.telegram.bot || null; } set bot(newValue) { this._bot = newValue; } get bot() { // if (this._bot == null) { // this._bot = config.telegram.bot; // } return this._bot; } _getUrl(method) { const endPoint = `bot${this.bot.api_key}:${security.decrypt(this.bot.api_secret)}/${method}`; return `https://api.telegram.org/${endPoint}`; } async _request(method, params) { const url = `${this._getUrl(method)}?${params.join('&')}`; const options = { method: 'get', mode: 'cors', cache: 'no-cache', headers: {} }; console.log(url, options); const res = await fetch(url, options); console.log(res.ok, res.status, res.statusText); return res; } _unixtimeToDatetime(unixtime) { return moment(unixtime * 1000).format('YYYY-MM-DD HH:mm:ss') } //--- 메시지 송신 // { // ok: true, // result: { // message_id: 24, // from: { // id: 1783798789, //--- 보낸 사람 chat id // is_bot: true, //--- true. ㅠot임 // first_name: "OBCon", //--- 보낸 사람 이름 // username: "OBConBot" //--- 보낸 사람 User Name // }, // chat: { // id: 818275856, //--- 받는 사람 chat id // first_name: "\uacc4\ud604", //--- 받는 사람 이름 // last_name: "\uae40", //--- 받는 사람 성 // type: "private" //--- private. 개인 메시지 // }, // date: 1624521914, //--- 발송일시 (timestamp) // text: "Hello" //--- 메시지 // } // } async send(chat_id, message) { try { if (config.telegram.use == false) { return { code: 500, message: 'Telegram 사용 설정이 되어 있지 않습니다.', data: {}, err: {} }; } const params = []; params.push(`chat_id=${chat_id}`); params.push(`text=${encodeURIComponent(message)}`); const res = await this._request('sendMessage', params); if (res.ok) { const json = await res.json(); if (json.ok) { json.result.date = this._unixtimeToDatetime(json.result.date); console.log(`ID: ${json.result.message_id}, datetime: ${json.result.date}, message: [${json.result.text}]`); console.log(` from: ${JSON.stringify(json.result.from)}`); console.log(` chat: ${JSON.stringify(json.result.chat)}`); } else { console.log(JSON.stringify(json)); } return { code: (res.ok) ? 0:res.status, message: res.statusText, data: json, err: {} }; } else { return { code: (res.ok) ? 0:res.status, message: res.statusText, data: {}, err: {} }; } } catch(ex) { utils.obj.loggerError(ex); return { code: 500, message: ex.message, data: {}, err: ex }; } } //--- telegram.notification(null, '알림'); async notification(notifications, message) { try { notifications = notifications || config.telegram.notifications; for (let idx = 0; idx < notifications.length; idx++) { await this.send(notifications[idx].id, message); } } catch(ex) { utils.obj.loggerError(ex); return { code: 500, message: ex.message, data: {}, err: ex }; } } //--- 메시지 수신 // { // ok:true, // result: [ //--- 최근에 받은 메시지가 가장 뒤에 배치된다. // { // update_id: 127981751, // message: { // message_id: 26, //--- 1씩 증가 한다. // from:{ // id: 818275856, //--- 보낸 사람 chat id // is_bot:false, //--- true. Bot임 // first_name: "\uacc4\ud604", //--- 보낸 사람 이름 // last_name: "\uae40", //--- 보낸 사람 성 // language_code: "ko" //--- 사용 언어 // }, // chat:{ // id: 818275856, //--- 보낸 사람 chat id // first_name: "\uacc4\ud604", //--- 보낸 사람 이름 // last_name: "\uae40", //--- 보낸 사람 성 // type: "private" //--- private. 개인 메시지 // }, // "date": 1624522279, //--- 수신일시 (timestamp) // "text": "\ub124" //--- 메시지 // } // } // ] // } async receive(offset=null, _timeout=0) { try { if (config.telegram.use == false) { return { code: 500, message: 'Telegram 사용 설정이 되어 있지 않습니다.', data: {}, err: {} }; } const params = []; if (offset != null) { params.push(`offset=${offset}`); //--- "offset <= update_id" 조건을 만족하는 메시지만 반환 } params.push(`limit=100`); //--- 가져올 메시지 갯수 (Default. 100) // params.push(`timeout=${timeout}`); //--- Timeout 초 const res = await this._request('getUpdates', params); if (res.ok) { const json = await res.json(); if (json.ok) { for (let idx = 0; idx < json.result.length; idx++) { const item = json.result[idx]; item.message.date = this._unixtimeToDatetime(item.message.date); console.log(JSON.stringify(item)); } return { code: (res.ok) ? 0:res.status, message: res.statusText, data: json.result, err: {} }; } else { console.log(JSON.stringify(json)); return { code: (res.ok) ? 0:res.status, message: res.statusText, data: [], err: json }; } } else { return { code: (res.ok) ? 0:res.status, message: res.statusText, data: {}, err: {} }; } } catch(ex) { utils.obj.loggerError(ex); return { code: 500, message: ex.message, data: {}, err: ex }; } } } module.exports = Telegram;