Skip to content

Instantly share code, notes, and snippets.

@nikotan
Last active April 9, 2016 14:38
Show Gist options
  • Save nikotan/622dd577887df8fda042c2833349a9cd to your computer and use it in GitHub Desktop.
Save nikotan/622dd577887df8fda042c2833349a9cd to your computer and use it in GitHub Desktop.
LINE BOT API sample code on webscript.io (with Microsoft Translator Text API)
-- setting
local mstr_cid = 'client_id for microsoft translator text api'
local mstr_secret = 'client_secret for microsoft translator text api'
local line_id = 'Channel ID for LINE BOT API'
local line_secret = 'Channel Secret for LINE BOT API'
local line_mid = 'MID for LINE BOT API'
-- function: mstr
function mstr(text, cid, secret)
local lom = require 'lxp.lom'
local response, parsed
-- get token
response = http.request {
url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
method = 'POST',
data = {
client_id = cid,
client_secret = secret,
scope = 'http://api.microsofttranslator.com',
grant_type = 'client_credentials'
}
}
local token = json.parse(response.content).access_token
log('token = ' .. token)
-- detect
response = http.request {
url = 'http://api.microsofttranslator.com/V2/Http.svc/Detect',
method = 'GET',
params = {
appId = 'Bearer ' .. token,
text = text
},
headers = {
Authorization = 'Bearer ' .. token
}
}
parsed = lom.parse(response.content)
local code_from = parsed[1]
local code_to = 'ja'
if code_from == 'ja' then
code_to = 'en'
end
log('code_from = ' .. code_from)
log('code_to = ' .. code_to)
-- translate
local response = http.request {
url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate',
method = 'GET',
params = {
appId = 'Bearer ' .. token,
from = code_from,
to = code_to,
text = text
},
headers = {
Authorization = 'Bearer ' .. token
}
}
parsed = lom.parse(response.content)
return parsed[1]
end
-- create reply message from request
local body = json.parse(request.body)
local res = mstr(body.result[1].content.text, mstr_cid, mstr_secret)
local reply = body.result[1].content.from
local data = {
['to'] = {reply},
['toChannel'] = '1383378250',
['eventType'] = '138311608800106203',
['content'] = {
['contentType'] = 1,
['toType'] = 1,
['text'] = res
}
}
log('input message = ' .. body.result[1].content.text)
log('output message = ' .. res)
-- send reply
local response = http.request {
url = 'https://trialbot-api.line.me/v1/events',
method = 'POST',
data = json.stringify(data),
headers = {
['Content-Type'] = 'application/json; charser=UTF-8',
['X-Line-ChannelID'] = line_id,
['X-Line-ChannelSecret'] = line_secret,
['X-Line-Trusted-User-With-ACL'] = line_mid
}
}
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment