kykint

Fix and improve translate()

Previous way translate() determined its source and target language was inflexible and inconvenient.
For example a user always had to change target language according to whether he wants to translate
into other language or his own.

Improve this by assuming that user wants to translate his own language into other language when
source language matches the user's locale, and the opposite if it doesn't.

Also make some other improvements to logic:
- translate() now doesn't send a message to user directly, and instead returns a Promise.
- Also it takes a full user info instead of userId as a parameter, allowing it to detect
  user's locale as well.
Showing 1 changed file with 103 additions and 78 deletions
...@@ -31,95 +31,108 @@ bot.onText(/\/echo (.+)/, (msg, match) => { ...@@ -31,95 +31,108 @@ bot.onText(/\/echo (.+)/, (msg, match) => {
31 }); 31 });
32 32
33 /** 33 /**
34 - * Translate given message and send it to the specified chatroom. 34 + * Translate given message and return the result as a parameter of Promise.
35 * 35 *
36 - * @param {*} userId Id of the user that wants to translate 36 + * @param {*} user Info of user that sent the message (msg.from)
37 * @param {*} message Message to translate 37 * @param {*} message Message to translate
38 - * @param {*} chatId Id of the chatroom to send translated message to
39 */ 38 */
40 -function translate(userId, message, chatId) { 39 +function translate(user, message) {
41 - // Language detection options 40 + return new Promise(function (resolve, reject) {
42 - var lang_detect_options = { 41 + const userId = user.id;
43 - url: languagedetect_api_url, 42 + const userLang = user.language_code;
44 - form: { 'query': message }, 43 +
45 - headers: { 44 + // Language detection options
46 - 'X-Naver-Client-Id': config.papago.client_id, 45 + var lang_detect_options = {
47 - 'X-Naver-Client-Secret': config.papago.client_secret 46 + url: languagedetect_api_url,
48 - } 47 + form: { 'query': message },
49 - }; 48 + headers: {
50 - 49 + 'X-Naver-Client-Id': config.papago.client_id,
51 - // Papago language detection 50 + 'X-Naver-Client-Secret': config.papago.client_secret
52 - request.post(lang_detect_options, function (error, response, body) { 51 + }
53 - console.log(response.statusCode); 52 + };
54 - if (!error && response.statusCode == 200) { 53 +
55 - var detect_body = JSON.parse(response.body); 54 + // Papago language detection
56 - var source = ''; 55 + request.post(lang_detect_options, function (error, response, body) {
57 - var target = ''; 56 + console.log(response.statusCode);
58 - var result = { type: 'text', text: '' }; 57 + if (!error && response.statusCode == 200) {
59 - 58 + var detect_body = JSON.parse(response.body);
60 - // Check if detection was successful 59 + var source = '';
61 - console.log('Language detected: ' + detect_body.langCode); 60 + var target = '';
62 - 61 + var result = { type: 'text', text: '' };
63 - // Translate using papago 62 +
64 - // Try to grab source lang and target lang from user's preference first. 63 + // Check if detection was successful
65 - // If preference is not found, source default to detected language, and 64 + console.log('Language detected: ' + detect_body.langCode);
66 - // target defaults to English for Korean source, or Korean for all other langs. 65 +
67 - if (detect_body.langCode != 'unk') { 66 + // Translate using papago
68 - db.findPref(userId, "pref", (dbResult) => { 67 + // Try to grab source lang and target lang from user's preference first.
69 - // Choosing source language not implemented as of now 68 + // If preference is not found, source default to detected language, and
70 - if (dbResult != undefined) { 69 + // target defaults to English for Korean source, or Korean for all other langs.
71 - source = dbResult.source != undefined ? dbResult.source : detect_body.langCode; 70 + if (detect_body.langCode != 'unk') {
72 - target = dbResult.target != undefined ? dbResult.target : (source == 'ko' ? 'en' : 'ko'); 71 + db.findPref(userId, "pref", (dbResult) => {
73 - } else {
74 source = detect_body.langCode; 72 source = detect_body.langCode;
75 - target = source == 'ko' ? 'en' : 'ko';
76 - }
77 - console.log(source + ' => ' + target);
78 -
79 - // Papago translation options
80 - var translate_options = {
81 - url: translate_api_url,
82 - form: {
83 - 'source': source, // Before translation
84 - 'target': target, // After translation
85 - 'text': message // Message to translate
86 - },
87 - headers: {
88 - 'X-Naver-Client-Id': config.papago.client_id,
89 - 'X-Naver-Client-Secret': config.papago.client_secret
90 - }
91 - };
92 73
93 - // Send translatation request 74 + if (source == userLang) {
94 - request.post(translate_options, function (error, response, body) { 75 + // User wants to translate his language into another
95 - var objBody = JSON.parse(response.body); 76 + // Leave target untouched, which is his desired destination language
96 - if (!error && response.statusCode == 200) {
97 - // On success
98 - result.text = objBody.message.result.translatedText;
99 77
100 - console.log('Before: ' + message); 78 + // Check if user target language exists in db, if not default to English
101 - console.log('After: ' + result.text); 79 + console.log('Translating to target');
80 + target = (dbResult != undefined && dbResult.target != undefined)
81 + ? dbResult.target : 'en';
102 } else { 82 } else {
103 - // On failure 83 + // source != userLang
104 - result.text = '[' + objBody.errorCode + '] ' + objBody.errorMessage; 84 + // User wants to translate another language into his
85 + // Then destination should be his language
86 + console.log('Translating to userLang');
87 + target = userLang;
105 } 88 }
106 - // Send translated message 89 +
107 - bot.sendMessage(chatId, result.text); 90 + console.log(source + ' => ' + target);
91 +
92 + // Papago translation options
93 + var translate_options = {
94 + url: translate_api_url,
95 + form: {
96 + 'source': source, // Before translation
97 + 'target': target, // After translation
98 + 'text': message // Message to translate
99 + },
100 + headers: {
101 + 'X-Naver-Client-Id': config.papago.client_id,
102 + 'X-Naver-Client-Secret': config.papago.client_secret
103 + }
104 + };
105 +
106 + // Send translatation request
107 + request.post(translate_options, function (error, response, body) {
108 + var objBody = JSON.parse(response.body);
109 + if (!error && response.statusCode == 200) {
110 + // On success
111 + result.text = objBody.message.result.translatedText;
112 +
113 + console.log('Before: ' + message);
114 + console.log('After: ' + result.text);
115 + } else {
116 + // On failure
117 + result.text = '[' + objBody.errorCode + '] ' + objBody.errorMessage;
118 + }
119 + resolve(result.text);
120 + });
108 }); 121 });
109 - }); 122 + }
123 + // Language not detected
124 + else {
125 + result.text = '언어를 감지할 수 없습니다.';
126 + reject(result.text);
127 + }
110 } 128 }
111 - // Language not detected 129 + });
112 - else {
113 - result.text = '언어를 감지할 수 없습니다.';
114 - bot.sendMessage(chatId, result.text);
115 - }
116 - }
117 }); 130 });
118 } 131 }
119 132
120 // [Any normal message which is not a command (not starting with '/')] 133 // [Any normal message which is not a command (not starting with '/')]
121 bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => { 134 bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => {
122 - const userId = msg.from.id; 135 + const user = msg.from;
123 const chatId = msg.chat.id; 136 const chatId = msg.chat.id;
124 const chatType = msg.chat.type; 137 const chatType = msg.chat.type;
125 const received_msg = match[1]; 138 const received_msg = match[1];
...@@ -130,7 +143,11 @@ bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => { ...@@ -130,7 +143,11 @@ bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => {
130 return; 143 return;
131 } 144 }
132 145
133 - translate(userId, received_msg, chatId); 146 + translate(user, received_msg).then(function (result) {
147 + bot.sendMessage(chatId, result);
148 + }).catch(function (error) {
149 + console.log(error);
150 + });
134 }); 151 });
135 152
136 // /t(ranslate) [Whatever] 153 // /t(ranslate) [Whatever]
...@@ -138,7 +155,7 @@ bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => { ...@@ -138,7 +155,7 @@ bot.onText(/^(?!\/)((.|\n)+)/, (msg, match) => {
138 // Also, if the given '/t' message is a reply to another message, 155 // Also, if the given '/t' message is a reply to another message,
139 // translate the reply target message as well. 156 // translate the reply target message as well.
140 bot.onText(/^\/(t|translate)($| ((.|\n)+))/, (msg, match) => { 157 bot.onText(/^\/(t|translate)($| ((.|\n)+))/, (msg, match) => {
141 - const userId = msg.from.id; 158 + const user = msg.from;
142 const chatId = msg.chat.id; 159 const chatId = msg.chat.id;
143 const chatType = msg.chat.type; 160 const chatType = msg.chat.type;
144 const received_msg = match[3]; 161 const received_msg = match[3];
...@@ -150,12 +167,20 @@ bot.onText(/^\/(t|translate)($| ((.|\n)+))/, (msg, match) => { ...@@ -150,12 +167,20 @@ bot.onText(/^\/(t|translate)($| ((.|\n)+))/, (msg, match) => {
150 // Translate the reply's target message 167 // Translate the reply's target message
151 if (isReply) { 168 if (isReply) {
152 const replyMsg = msg.reply_to_message.text; 169 const replyMsg = msg.reply_to_message.text;
153 - translate(userId, replyMsg, chatId); 170 + translate(user, replyMsg).then(function (result) {
171 + bot.sendMessage(chatId, result);
172 + }).catch(function (error) {
173 + console.log(error);
174 + });
154 } 175 }
155 176
156 // Translate the message after '/t' if exists 177 // Translate the message after '/t' if exists
157 if (msgExists) { 178 if (msgExists) {
158 - translate(userId, received_msg, chatId); 179 + translate(user, received_msg).then(function (result) {
180 + bot.sendMessage(chatId, result);
181 + }).catch(function (error) {
182 + console.log(error);
183 + });
159 } 184 }
160 }); 185 });
161 186
......