app.js 3.71 KB
const TelegramBot = require('node-telegram-bot-api');

// replace the value below with the Telegram token you receive from @BotFather
const token = '825631426:AAE9tgw89kOZyLTre8DSDaObFQeVx7q41gw';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true });

var request = require('request');

// Translation api url
const translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt';

// Language detection api url
const languagedetect_api_url = 'https://openapi.naver.com/v1/papago/detectLangs'

// Naver papago client id & secret
const papago_client_id = 'lA0rGxQllAfrlOkGGNnK';
const papago_client_secret = 'u3fykDlNb0';

// /echo [whatever]
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  const resp = match[1]; // the captured "whatever"

  // send back the matched "whatever" to the chat
  bot.sendMessage(chatId, resp);
});

/**
 * Translate given message and send it to the specified chatroom.
 *
 * @param {*} message Message to translate
 * @param {*} chatId  Id of the chatroom to send translated message to
 */
function translate(message, chatId) {
  // Language detection options
  var lang_detect_options = {
    url: languagedetect_api_url,
    form: { 'query': message },
    headers: {
      'X-Naver-Client-Id': papago_client_id,
      'X-Naver-Client-Secret': papago_client_secret
    }
  };

  // Papago language detection
  request.post(lang_detect_options, function (error, response, body) {
    console.log(response.statusCode);
    if (!error && response.statusCode == 200) {
      var detect_body = JSON.parse(response.body);
      var source = '';
      var target = '';
      var result = { type: 'text', text: '' };

      // Check if detection was successful
      console.log('Language detected: ' + detect_body.langCode);

      // Translate using papago
      // Target defaults to English for Korean source, or Korean for all other langs
      if (detect_body.langCode != 'unk') {
        source = detect_body.langCode;
        target = source == 'ko' ? 'en' : 'ko';

        // Papago translation options
        var translate_options = {
          url: translate_api_url,
          form: {
            'source': source, // Before translation
            'target': target, // After translation
            'text': message // Message to translate
          },
          headers: {
            'X-Naver-Client-Id': papago_client_id,
            'X-Naver-Client-Secret': papago_client_secret
          }
        };

        // Send translatation request
        request.post(translate_options, function (error, response, body) {
          // On success
          if (!error && response.statusCode == 200) {
            var objBody = JSON.parse(response.body);
            result.text = objBody.message.result.translatedText;

            // Send translated message
            console.log('Before: ' + message);
            console.log('After: ' + result.text);
            bot.sendMessage(chatId, result.text);
          }
        });
      }
      // Language not detected
      else {
        result.text = '언어를 감지할 수 없습니다.';
        bot.sendMessage(chatId, result.text);
      }
    }
  });
}

// [Any normal message which is not a command (not starting with '/')]
bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => {
  const chatId = msg.chat.id;
  const chatType = msg.chat.type;
  const received_msg = match[1];

  // Ignore if we are not on a private chat,
  // since direct translation is to be used only on private chats.
  if (chatType != 'private') {
    return;
  }

  translate(received_msg, chatId);
});