I really wanted to use the Google Translate API. Just because I always use their app.

But, turns out the API is paid, so I looked at an alternative and I found Yandex Translate to be a good one.

Go to https://tech.yandex.com/translate/. If you don’t have a Yandex account, create one for free.

Then create an API key from the interface.

According to the Terms of Use for the Yandex.Translate service, the text Powered by Yandex.Translate must be shown above or below the translation result, with a clickable link to the page http://translate.yandex.com/. As this is just a private sample application, I won’t do it, but just be aware.

Now, store this API key in the .env file as YANDEX_API_KEY.

The Yandex Translate API documentation (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) tells us to build an API request in this way:

https://translate.yandex.net/api/v1.5/tr.json/translate
 ?key=<API key>
 &text=<text to translate>
 &lang=<translation direction>

In the project introduction I mentioned we’ll use two commands to set the languages:

  • /from <language> will change the origin language to a specific one
  • /to <language> will translate messages to that language

The preferences will be stored by the bot in the session, so every subsequent message will use those preferences.

The lang in the query parameter can take the form <from>-<to> or just <to> (in this case “from” will be guessed from the message). For example en or it-en.

Let’s try this and translate to english every message that comes in.

We listen to every message using on():

bot.on('message', ctx => {})

Using Axios (npm i axios) we’ll perform a network request to the Yandex Translate API.

See https://flaviocopes.com/axios to get an intro to Axios

We pass in the params object, and we listen for the promise to complete in the then() callback:

const axios = require('axios')

//...
bot.on('message', ctx => {
  axios.get('https://translate.yandex.net/api/v1.5/tr.json/translate', {
    params: {
      key: process.env.YANDEX_API_KEY,
      text: ctx.message.text,
      lang: 'en'
    }
  }).then(res => {
    ctx.reply(res.data.text[0])
  })
})

See, we post the response in the chat by calling ctx.reply() and passing res.data.text[0], which contains the response from the API.

Try it, it should work!


Go to the next lesson