2016-04-11 06:04:47 +02:00
|
|
|
local translate = {}
|
|
|
|
|
|
|
|
local HTTPS = require('ssl.https')
|
|
|
|
local URL = require('socket.url')
|
2016-04-15 21:07:23 +02:00
|
|
|
local JSON = require('dkjson')
|
2016-06-07 06:31:34 +02:00
|
|
|
local utilities = require('otouto.utilities')
|
2016-04-11 06:04:47 +02:00
|
|
|
|
|
|
|
translate.command = 'translate [text]'
|
2016-05-27 05:28:44 +02:00
|
|
|
|
|
|
|
function translate:init(config)
|
2016-08-14 04:46:18 +02:00
|
|
|
assert(config.yandex_key,
|
|
|
|
'translate.lua requires a Yandex translate API key from http://tech.yandex.com/keys/get.'
|
|
|
|
)
|
2016-08-14 04:26:44 +02:00
|
|
|
|
2016-08-14 04:46:18 +02:00
|
|
|
translate.triggers = utilities.triggers(self.info.username, config.cmd_pat)
|
|
|
|
:t('translate', true):t('tl', true).table
|
|
|
|
translate.doc = config.cmd_pat .. [[translate [text]
|
2016-07-25 11:03:35 +02:00
|
|
|
Translates input or the replied-to message into the bot's language.]]
|
2016-08-14 04:46:18 +02:00
|
|
|
translate.base_url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=' .. config.yandex_key .. '&lang=' .. config.lang .. '&text=%s'
|
2016-04-11 06:04:47 +02:00
|
|
|
end
|
2015-07-21 01:29:40 +02:00
|
|
|
|
2016-05-27 02:26:30 +02:00
|
|
|
function translate:action(msg, config)
|
2016-08-14 04:46:18 +02:00
|
|
|
local input = utilities.input_from_msg(msg)
|
|
|
|
if not input then
|
|
|
|
utilities.send_reply(self, msg, translate.doc, true)
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
local url = translate.base_url:format(URL.escape(input))
|
|
|
|
local jstr, code = HTTPS.request(url)
|
|
|
|
if code ~= 200 then
|
|
|
|
utilities.send_reply(self, msg, config.errors.connection)
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
local data = JSON.decode(jstr)
|
|
|
|
if data.code ~= 200 then
|
|
|
|
utilities.send_reply(self, msg, config.errors.connection)
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
utilities.send_reply(self, msg.reply_to_message or msg, utilities.style.enquote('Translation', data.text[1]), true)
|
2015-07-21 01:29:40 +02:00
|
|
|
end
|
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
return translate
|