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/miku/plugins/reddit.lua

78 lines
2.6 KiB
Lua
Raw Normal View History

2016-11-29 18:28:21 +01:00
local reddit = {}
reddit.command = 'reddit [r/subreddit | Suchbegriff]'
function reddit:init(config)
reddit.triggers = utilities.triggers(self.info.username, config.cmd_pat, {'^/r/'}):t('reddit', true):t('r', true):t('r/', true).table
reddit.doc = [[*
]]..config.cmd_pat..[[r* _[r/subreddit | Suchbegriff]_: Gibt Top-Posts oder Ergebnisse eines Subreddits aus. Wenn kein Argument gegeben ist, wird /r/all genommen.]]
end
local format_results = function(posts)
local output = ''
for _,v in ipairs(posts) do
local post = v.data
local title = post.title:gsub('%[', '('):gsub('%]', ')'):gsub('&', '&')
if title:len() > 256 then
title = title:sub(1, 253)
title = utilities.trim(title)..'...'
2016-11-29 18:28:21 +01:00
end
local short_url = 'https://redd.it/'..post.id
local s = '<a href="'..short_url..'">'..unescape(title)..'</a>'
2016-11-29 18:28:21 +01:00
if post.domain and not post.is_self and not post.over_18 then
s = '[<a href="'..post.url:gsub('%)', '\\)')..'">'..post.domain..'</a>] '..s
2016-11-29 18:28:21 +01:00
end
output = output..''..s..'\n'
2016-11-29 18:28:21 +01:00
end
return output
end
reddit.subreddit_url = 'https://www.reddit.com/%s/.json?limit='
reddit.search_url = 'https://www.reddit.com/search.json?q=%s&limit='
reddit.rall_url = 'https://www.reddit.com/.json?limit='
function reddit:action(msg, config)
-- Eight results in PM, four results elsewhere.
local limit = 4
if msg.chat.type == 'private' then
limit = 8
end
local text = msg.text_lower
if text:match('^/r/.') then
-- Normalize input so this hack works easily.
text = msg.text_lower:gsub('^/r/', config.cmd_pat..'r r/')
end
local input = utilities.input(text)
local source, url
if input then
if input:match('^r/.') then
input = utilities.get_word(input, 1)
url = reddit.subreddit_url:format(input)..limit
source = '<b>/'..utilities.md_escape(input)..'</b>\n'
2016-11-29 18:28:21 +01:00
else
input = utilities.input(msg.text)
source = '<b>Ergebnisse für</b> <i>'..utilities.md_escape(input)..'</i> <b>:</b>\n'
2016-11-29 18:28:21 +01:00
input = URL.escape(input)
url = reddit.search_url:format(input)..limit
2016-11-29 18:28:21 +01:00
end
else
url = reddit.rall_url..limit
source = '<b>/r/all</b>\n'
2016-11-29 18:28:21 +01:00
end
local jstr, res = https.request(url)
if res ~= 200 then
utilities.send_reply(msg, config.errors.results)
else
local jdat = json.decode(jstr)
if #jdat.data.children == 0 then
utilities.send_reply(msg, config.errors.results)
else
local output = format_results(jdat.data.children)
local redd_link = source:gsub('</?b>', '')
output = source..output..'<a href="https://reddit.com'..redd_link..'">Mehr auf Reddit ansehen.</a>'
utilities.send_reply(msg, output, 'HTML')
2016-11-29 18:28:21 +01:00
end
end
end
return reddit