我正在使用discord.js库为discord编写机器人。一切正常,直到我收到来自googleapis的回复。
我试图翻译的例子是:“hallo MagstdugrüneBäume”,作为回应,我得到“你好,你们是不是树木”。大多数语言都会出现此问题。我的代码:
'use strict';
const request = require('request');
const iso = require('iso-639-1');
// const iconv = require('iconv-lite');
const querystring = require("querystring");
// var baseRequest = request.defaults({
// encoding: null
// })
module.exports = {
main: function(bot, msg, settings) {
let args = msg.content.replace(/"/g, '');
let toLang = args.split(' ')[args.split(' ').length - 1];
toLang = iso.getCode(toLang) == '' ? toLang : iso.getCode(toLang);
args = args.replace((" " + args.split(' ')[args.split(' ').length - 1]), '')
args = querystring.escape(args);
let fromlang = 'auto';
let gurl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + fromlang + "&tl=" + toLang + "&dt=t&q=" + args;
request(gurl, function(error, response, body) {
try {
// body = iconv.decode(body, 'utf8');
// console.log(bodyWithCorrectEncoding)
let translated = body.match(/^\[\[\[".+?",/)[0];
translated = translated.substring(4, translated.length - 2);
msg.channel.sendMessage("```\nTranslated:\n" + translated + "\n```");
} catch (err) {
msg.channel.sendMessage("`Input was invalid`");
}
});
}
};
你可以看到我正在尝试返回二进制文件和iconv它但没有成功。我知道我的问题在于编码,但我无法解决。