This repository has been archived on 2021-04-24. You can view files and clone it, but cannot push or open issues or pull requests.
Mikubot-2/otouto/plugins/chatter.lua

80 lines
2.2 KiB
Lua
Raw Normal View History

-- Put this absolutely at the end, even after greetings.lua.
2015-07-05 18:14:41 +02:00
local chatter = {}
local HTTP = require('socket.http')
local URL = require('socket.url')
local JSON = require('dkjson')
2016-06-07 06:31:34 +02:00
local bindings = require('otouto.bindings')
2016-05-27 02:26:30 +02:00
function chatter:init(config)
if not config.simsimi_key then
print('Missing config value: simsimi_key.')
print('chatter.lua will not be enabled.')
return
end
2016-01-21 20:57:06 +01:00
chatter.triggers = {
''
}
end
2015-07-05 04:51:12 +02:00
chatter.base_url = 'http://%sapi.simsimi.com/request.p?key=%s&lc=%s&ft=1.0&text=%s'
2015-07-05 04:51:12 +02:00
2016-05-27 02:26:30 +02:00
function chatter:action(msg, config)
if msg.text == '' then return true end
if (
not (
msg.text_lower:match('^'..self.info.first_name:lower()..',')
or msg.text_lower:match('^@'..self.info.username:lower()..',')
or msg.from.id == msg.chat.id
--Uncomment the following line for Al Gore-like conversation.
--or (msg.reply_to_message and msg.reply_to_message.from.id == self.info.id)
)
2016-06-07 05:45:11 +02:00
or msg.text:match('^'..config.cmd_pat)
or msg.text == ''
) then
return true
end
2015-07-05 04:51:12 +02:00
bindings.sendChatAction(self, { action = 'typing' } )
2015-07-05 04:51:12 +02:00
local input = msg.text_lower:gsub(self.info.first_name, 'simsimi')
input = input:gsub('@'..self.info.username, 'simsimi')
local sandbox = self.config.simsimi_trial and 'sandbox.' or ''
2016-05-27 02:26:30 +02:00
local url = chatter.base_url:format(sandbox, config.simsimi_key, self.config.lang, URL.escape(input))
2015-07-05 04:51:12 +02:00
local jstr, res = HTTP.request(url)
2015-07-05 04:51:12 +02:00
if res ~= 200 then
2016-05-27 02:26:30 +02:00
utilities.send_message(self, msg.chat.id, config.errors.chatter_connection)
return
2015-07-05 04:51:12 +02:00
end
local jdat = JSON.decode(jstr)
if not jdat.response or jdat.response:match('^I HAVE NO RESPONSE.') then
2016-05-27 02:26:30 +02:00
utilities.send_message(self, msg.chat.id, config.errors.chatter_response)
2016-01-21 20:57:06 +01:00
return
end
2016-04-27 01:37:55 +02:00
local output = jdat.response
2015-07-05 04:51:12 +02:00
-- Clean up the response here.
output = utilities.trim(output)
-- Simsimi will often refer to itself. Replace "simsimi" with the bot name.
output = output:gsub('%aimi?%aimi?', self.info.first_name)
-- Self-explanatory.
output = output:gsub('USER', msg.from.first_name)
-- Capitalize the first letter.
output = output:gsub('^%l', string.upper)
-- Add a period if there is no punctuation.
output = output:gsub('%P$', '%1.')
2015-07-05 18:14:41 +02:00
utilities.send_message(self, msg.chat.id, output)
2015-07-05 04:51:12 +02:00
end
return chatter