2018-08-31 09:51:47 +00:00
|
|
|
#--require-config soundcloud-api-key
|
2016-04-06 12:56:12 +00:00
|
|
|
|
2018-07-02 13:33:38 +00:00
|
|
|
import json, re, time
|
2016-04-06 12:56:12 +00:00
|
|
|
import Utils
|
|
|
|
|
2018-07-02 13:33:38 +00:00
|
|
|
URL_SOUNDCLOUD_TRACK = "http://api.soundcloud.com/tracks"
|
|
|
|
URL_SOUNDCLOUD_RESOLVE = "http://api.soundcloud.com/resolve"
|
2018-07-02 13:34:46 +00:00
|
|
|
REGEX_SOUNDCLOUD = "https?://soundcloud.com/([^/]+)/([^/]+)"
|
2016-04-06 12:56:12 +00:00
|
|
|
|
|
|
|
class Module(object):
|
|
|
|
_name = "SoundCloud"
|
|
|
|
def __init__(self, bot):
|
|
|
|
self.bot = bot
|
|
|
|
bot.events.on("received").on("command").on("soundcloud", "sc"
|
2018-08-31 09:51:47 +00:00
|
|
|
).hook(self.soundcloud, help="Search SoundCloud")
|
2016-04-06 12:56:12 +00:00
|
|
|
|
|
|
|
def soundcloud(self, event):
|
2018-07-02 13:33:38 +00:00
|
|
|
query = None
|
|
|
|
url = None
|
|
|
|
|
|
|
|
if event["args"]:
|
|
|
|
match = re.search(REGEX_SOUNDCLOUD, event["args"])
|
|
|
|
if match:
|
|
|
|
url = match.string
|
2016-04-06 12:56:12 +00:00
|
|
|
else:
|
2018-07-02 13:33:38 +00:00
|
|
|
query = event["args"]
|
|
|
|
else:
|
2018-08-28 11:23:57 +00:00
|
|
|
last_soundcloud = event["buffer"].find(REGEX_SOUNDCLOUD)
|
2018-07-02 13:33:38 +00:00
|
|
|
if last_soundcloud:
|
|
|
|
url = re.match(REGEX_SOUNDCLOUD,
|
2018-08-31 09:51:47 +00:00
|
|
|
last_soundcloud.message).string
|
2018-07-02 13:33:38 +00:00
|
|
|
|
|
|
|
if not query and not url:
|
|
|
|
event["stderr"].write("no search phrase provided")
|
|
|
|
return
|
|
|
|
has_query = not query == None
|
|
|
|
get_params = {"limit": 1,
|
2018-08-31 09:51:47 +00:00
|
|
|
"client_id": self.bot.config["soundcloud-api-key"]}
|
2018-07-02 13:33:38 +00:00
|
|
|
|
|
|
|
if query:
|
|
|
|
get_params["q"] = query
|
|
|
|
else:
|
|
|
|
get_params["url"] = url
|
|
|
|
|
|
|
|
page = Utils.get_url(
|
|
|
|
URL_SOUNDCLOUD_TRACK if has_query else URL_SOUNDCLOUD_RESOLVE,
|
|
|
|
get_params=get_params, json=True)
|
|
|
|
|
|
|
|
if page:
|
|
|
|
page = page[0] if has_query else page
|
|
|
|
title = page["title"]
|
|
|
|
user = page["user"]["username"]
|
|
|
|
duration = time.strftime("%H:%M:%S", time.gmtime(page[
|
2018-08-31 09:51:47 +00:00
|
|
|
"duration"]/1000))
|
2018-07-02 13:33:38 +00:00
|
|
|
if duration.startswith("00:"):
|
|
|
|
duration = duration[3:]
|
|
|
|
link = page["permalink_url"]
|
|
|
|
event["stdout"].write("%s [%s] (posted by %s) %s" % (title,
|
2018-08-31 09:51:47 +00:00
|
|
|
duration, user, link))
|
2016-04-06 12:56:12 +00:00
|
|
|
else:
|
|
|
|
event["stderr"].write("Failed to load results")
|