index.js 4.09 KB
"use strict";

const iniparser = require('iniparser');
const config = iniparser.parseSync('./config.ini');
const telegram = require('node-telegram-bot-api');
const request = require('request');
const http = require('http');
const url = require('url');
const strftime = require('strftime');
const winston = require('winston');

const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      timestamp: function() {
        return strftime('%F %T', new Date());
      },
      formatter: function(options) {
        // Return string will be passed to logger.
        return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') +
          (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
      }
    }),
    new (winston.transports.DailyRotateFile)({
	  filename: 'log',
      timestamp: function() {
        return strftime('%F %T', new Date());
      },
      formatter: function(options) {
        // Return string will be passed to logger.
        return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') +
          (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
      }
    })
  ]
});


const chat_ids = {};

const options = {
  webHook: {
    port: config.globals.webhook_port,
    key: __dirname+'/key.pem',
    cert: __dirname+'/crt.pem'
  }
};

const bot = new telegram(config.globals.token, options);
bot.setWebHook(config.globals.webhook_prefix + config.globals.token, __dirname+'/crt.pem');

/*
var options = {
  polling: true
};
bot = new telegram(config.globals.token, options);
*/


function deleteChatId(from) {
	delete chat_ids[from];
}

function sendMessage(destination, message) {
	//destination = destination.replace(/@TELEGRAM$/, '');
    let chat_id = chat_ids[destination];

    if (!chat_id) {
        logger.warn('Can not find approriate chat id for ' + destination + '. Abort sending message.');
        return;
    }

	logger.info('Sending reply to ' + destination + '(' + chat_id + '): ' + message);

	bot.sendMessage(chat_id, message);
}

function createHttpResponseServer(){
	const httpServer = http.createServer(function(request,response){
		let qs = url.parse(request.url, true).query;
		logger.info('Incoming request from SMSIN server:', {qs: qs})
		response.end('OK');

		sendMessage(qs.PhoneNumber, qs.text);
	});
	httpServer.listen(config.globals.listen_port, function(){
		logger.info("listening on " + config.globals.listen_port);
	})
}
createHttpResponseServer();

bot.getMe().then(function (me) {
  logger.info('Hi my name is %s!', me.username);
});

bot.on('text', function (msg) {
	logger.info('Incoming message', {msg: msg});

    if (!msg.from.username) {
        var replyMessage = "Pesan anda diabaikan, anda belum memiliki username pada telegram: " + msg.text;
		logger.info(replyMessage, {msg: msg});
        bot.sendMessage(msg.chat.id, replyMessage);
		return;
    }

	let now = Math.floor(new Date().getTime()/1000);

	if (now - msg.date > config.globals.message_max_age){
		let message = 'Pesan "' + msg.text + '" diabaikan. Silahkan diulang kembali.';
		logger.info(message)
		bot.sendMessage(msg.chat.id, message);
		return;
	}

	let from = msg.from.username.toUpperCase() + config.globals.msisdn_suffix;

	chat_ids[from] = msg.chat.id;

	bot.sendMessage( msg.chat.id,'Pesan anda telah diterima: ' + msg.text);

	var request_opts = {
		url: config.globals.aaa,
		qs: {
			PhoneNumber: from,
			Text: msg.text,
			Res_Port: config.globals.listen_port,
			SMSCID: config.globals.smscid
		}
	};

	request(request_opts, function(err, response, body) {
		if (err) {
			logger.info('Request error: ' + err);
			return;
		}

		logger.info('Response: ' + response);
		logger.info('Body: ' + body);

	});
});


function dumpChatIds() {
    let i = 0;
    for (let key in chat_ids) {
        logger.verbose('DUMPED CHAT IDS #' + ++i + ' ' + key + ': ' + chat_ids[key])
    }
}

if (config.dump_chat_ids_interval) {
    setInterval(dumpChatIds, config.dump_chat_ids_interval * 1000);
}