2015-11-25 03:22:04 +01:00
|
|
|
-- Thanks to @TiagoDanin for writing the original plugin.
|
2015-09-23 20:12:06 +02:00
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
local youtube = {}
|
|
|
|
|
|
|
|
local HTTPS = require('ssl.https')
|
|
|
|
local URL = require('socket.url')
|
2016-04-15 21:07:23 +02:00
|
|
|
local JSON = require('dkjson')
|
2016-04-11 06:04:47 +02:00
|
|
|
local bindings = require('bindings')
|
|
|
|
local utilities = require('utilities')
|
|
|
|
|
|
|
|
function youtube:init()
|
|
|
|
if not self.config.google_api_key then
|
|
|
|
print('Missing config value: google_api_key.')
|
|
|
|
print('youtube.lua will not be enabled.')
|
|
|
|
return
|
|
|
|
end
|
2016-04-12 05:55:46 +02:00
|
|
|
|
|
|
|
youtube.triggers = utilities.triggers(self.info.username):t('youtube', true):t('yt', true).table
|
2016-01-13 19:00:17 +01:00
|
|
|
end
|
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
youtube.command = 'youtube <query>'
|
|
|
|
youtube.doc = [[```
|
2016-01-08 14:44:37 +01:00
|
|
|
/youtube <query>
|
|
|
|
Returns the top result from YouTube.
|
|
|
|
Alias: /yt
|
|
|
|
```]]
|
2015-09-23 20:12:06 +02:00
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
function youtube:action(msg)
|
2015-11-25 03:22:04 +01:00
|
|
|
|
2016-04-08 23:12:02 +02:00
|
|
|
local input = utilities.input(msg.text)
|
2015-11-25 03:22:04 +01:00
|
|
|
if not input then
|
|
|
|
if msg.reply_to_message and msg.reply_to_message.text then
|
|
|
|
input = msg.reply_to_message.text
|
|
|
|
else
|
2016-04-11 06:04:47 +02:00
|
|
|
bindings.sendMessage(self, msg.chat.id, youtube.doc, true, msg.message_id, true)
|
2015-11-25 03:22:04 +01:00
|
|
|
return
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
local url = 'https://www.googleapis.com/youtube/v3/search?key=' .. self.config.google_api_key .. '&type=video&part=snippet&maxResults=4&q=' .. URL.escape(input)
|
2015-11-25 03:22:04 +01:00
|
|
|
|
|
|
|
local jstr, res = HTTPS.request(url)
|
|
|
|
if res ~= 200 then
|
2016-04-11 06:04:47 +02:00
|
|
|
bindings.sendReply(self, msg, self.config.errors.connection)
|
2015-11-25 03:22:04 +01:00
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
local jdat = JSON.decode(jstr)
|
2016-01-18 20:52:21 +01:00
|
|
|
if jdat.pageInfo.totalResults == 0 then
|
2016-04-11 06:04:47 +02:00
|
|
|
bindings.sendReply(self, msg, self.config.errors.results)
|
2016-01-18 20:52:21 +01:00
|
|
|
return
|
|
|
|
end
|
2015-11-25 03:22:04 +01:00
|
|
|
|
2016-03-22 11:16:26 +01:00
|
|
|
local vid_url = 'https://www.youtube.com/watch?v=' .. jdat.items[1].id.videoId
|
|
|
|
local vid_title = jdat.items[1].snippet.title
|
2016-02-25 10:42:13 +01:00
|
|
|
vid_title = vid_title:gsub('%(.+%)',''):gsub('%[.+%]','')
|
|
|
|
local output = '[' .. vid_title .. '](' .. vid_url .. ')'
|
2015-11-25 03:22:04 +01:00
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
bindings.sendMessage(self, msg.chat.id, output, false, nil, true)
|
2015-09-23 20:12:06 +02:00
|
|
|
|
|
|
|
end
|
|
|
|
|
2016-04-11 06:04:47 +02:00
|
|
|
return youtube
|