diff --git a/index.js b/index.js index 9fca1de..12f6e79 100644 --- a/index.js +++ b/index.js @@ -32,7 +32,7 @@ var logger = new (winston.Logger)({ }) ] }); - + var chat_ids = {}; @@ -63,8 +63,15 @@ function deleteChatId(from) { function sendMessage(destination, message) { //destination = destination.replace(/@TELEGRAM$/, ''); - logger.info('Sending reply to ' + destination + ': ' + message); - var chat_id = chat_ids[destination]; + var 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); } @@ -72,9 +79,9 @@ function createHttpResponseServer(){ var httpServer = http.createServer(function(request,response){ var qs = url.parse(request.url, true).query; logger.info('Incoming request from SMSIN server:', {qs: qs}) - //logger.info(qs); + //logger.info(qs); response.end('OK'); - + sendMessage(qs.PhoneNumber, qs.text); }); httpServer.listen(config.globals.listen_port, function(){ @@ -89,21 +96,21 @@ bot.getMe().then(function (me) { bot.on('text', function (msg) { logger.info(msg); - + var now = Math.floor(new Date().getTime()/1000); - + if (now - msg.date > config.globals.message_max_age){ var message = 'Pesan "' + msg.text + '" diabaikan. Silahkan diulang kembali.'; logger.info(message) bot.sendMessage(msg.chat.id, message); return; } - + var from = msg.from.username.toUpperCase() + config.globals.msisdn_suffix; - + chat_ids[from] = msg.chat.id; //setTimeout(deleteChatId, 1000 * 3600 * 24 * 2, from) - + bot.sendMessage( msg.chat.id,'Pesan anda telah diterima: ' + msg.text); var request_opts = { @@ -115,16 +122,27 @@ bot.on('text', function (msg) { 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() { + var i = 0; + for (var 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); +}