Skip to content

Instantly share code, notes, and snippets.

@TheBooker66
Last active January 9, 2022 19:41
Show Gist options
  • Save TheBooker66/b9992a4854665e8eaf379ff0e953895c to your computer and use it in GitHub Desktop.
Save TheBooker66/b9992a4854665e8eaf379ff0e953895c to your computer and use it in GitHub Desktop.
Translate sentences or words and hear them with Google Translate and Wikipedia
const nodeFetch = require("node-fetch"), request = require("request"), say = require("say");
async function translate(text) {
text = text.replace(/^Translate to/i).trim();
//Extracts the text to translated from the text inputted
const textToTranslate = text.replace(text.split(" ")[1], "").replace(undefined, "").trim();
const url = encodeURI(`https://en.wikipedia.org/w/api.php?action=languagesearch&search=${text.split(" ")[1]}&format=json`);
//Sends a request to Wikipedia to fetch the language code
let langResponse = await nodeFetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json'
},
});
//Processes the response to extract the language code
langResponse = await langResponse.json();
const langCode = Object.keys(langResponse.languagesearch)[0];
//If it exists, proceed
if (langCode) {
const url = encodeURI(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${langCode}&dt=t&q=${textToTranslate}`);
//Send a request to Google Translate to translate the text
request.get(url, async function (error, response, body) {
//If nothing's wrong, proceed
if (!error && response.statusCode === 200) {
const response = body.split('"');
console.log(`Translation: \n ${response[1]} \n From language (language code): \n ${response[response.length - 2]}`);
say.speak(response[1]); //To disable the text-to-speech you can comment this line
} else console.log("The language you chose doesn't exist in Google Translate, or you translated too much and your IP address got blocked.") //Writing Quenya instead of English will trigger this
}, null);
} else console.log("The Language you chose doesn't exist."); //Writing gibberish instead of English will trigger this.
}
translate("Translate to English Write your text here!").then();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment