Skip to content

Commit

Permalink
Merge branch 'python3.4' into master.
Browse files Browse the repository at this point in the history
While this isn't strictly tested, not much more has happened since the last commits here (which were quite a while ago), and having master up to date can't hurt.
  • Loading branch information
daboross committed Mar 8, 2017
2 parents 29ef5b3 + 8e04bf7 commit ff623f3
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 49 deletions.
9 changes: 7 additions & 2 deletions cloudbot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,18 @@ def main():
original_sigint = signal.getsignal(signal.SIGINT)

# define closure for signal handling
def exit_gracefully():
# The handler is called with two arguments: the signal number and the current stack frame
# These parameters should NOT be removed
def exit_gracefully(signum, frame):
nonlocal stopped_while_restarting
if not _bot:
# we are currently in the process of restarting
stopped_while_restarting = True
else:
_bot.loop.call_soon_threadsafe(lambda: asyncio.async(_bot.stop("Killed"), loop=_bot.loop))
_bot.loop.call_soon_threadsafe(
lambda: asyncio.async(_bot.stop("Killed (Received SIGINT {})".format(signum)), loop=_bot.loop))

logger.warn("Bot received Signal Interrupt ({})".format(signum))

# restore the original handler so if they do it again it triggers
signal.signal(signal.SIGINT, original_sigint)
Expand Down
4 changes: 3 additions & 1 deletion plugins/profiling.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ def pympler_diff():

# # Provide an easy way to get a threaddump, by using SIGUSR1 (only on POSIX systems)
if os.name == "posix":
def debug():
# The handler is called with two arguments: the signal number and the current stack frame
# These parameters should NOT be removed
def debug(sig, frame):
print(get_thread_dump())

signal.signal(signal.SIGUSR1, debug) # Register handler
110 changes: 64 additions & 46 deletions plugins/spotify.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import re

import requests

from cloudbot import hook
from cloudbot.util import web


gateway = 'http://open.spotify.com/{}/{}' # http spotify gw address
spuri = 'spotify:{}:{}'
api_url = "https://api.spotify.com/v1/search?"

spotify_re = re.compile(r'(spotify:(track|album|artist|user):([a-zA-Z0-9]+))', re.I)
http_re = re.compile(r'(open\.spotify\.com/(track|album|artist|user)/'
Expand All @@ -17,84 +13,106 @@
@hook.command('spotify', 'sptrack')
def spotify(text):
"""spotify <song> -- Search Spotify for <song>"""
params = {'q': text.strip()}

request = requests.get('http://ws.spotify.com/search/1/track.json', params=params)
params = {
"q": text.strip(),
"offset": 0,
"limit": 1,
"type": "track"
}

request = requests.get(api_url, params=params)
if request.status_code != requests.codes.ok:
return "Could not get track information: {}".format(request.status_code)

data = request.json()
data = request.json()["tracks"]["items"][0]

try:
_type, _id = data["tracks"][0]["href"].split(":")[1:]
artist, url, song, uri = (data["artists"][0]["name"],
data["external_urls"]["spotify"],
data["name"],
data["uri"])
except IndexError:
return "Could not find track."
url = web.try_shorten(gateway.format(_type, _id))
return "Unable to find any tracks!"

return "\x02{}\x02 by \x02{}\x02 - {}".format(data["tracks"][0]["name"],
data["tracks"][0]["artists"][0]["name"], url)
return "\x02{}\x02 by \x02{}\x02 - {} / {}".format(song, artist,
url, uri)


@hook.command
@hook.command("spalbum")
def spalbum(text):
"""spalbum <album> -- Search Spotify for <album>"""
params = {'q': text.strip()}

request = requests.get('http://ws.spotify.com/search/1/album.json', params=params)
params = {
"q": text.strip(),
"offset": 0,
"limit": 1,
"type": "album"
}

request = requests.get(api_url, params=params)
if request.status_code != requests.codes.ok:
return "Could not get album information: {}".format(request.status_code)

data = request.json()
data = request.json()["albums"]["items"][0]

try:
_type, _id = data["albums"][0]["href"].split(":")[1:]
artist, name, url, uri = (data["artists"][0]["name"],
data["name"],
data["external_urls"]["spotify"],
data["uri"])

except IndexError:
return "Could not find album."
url = web.try_shorten(gateway.format(_type, _id))
return "Unable to find any albums!"

return "\x02{}\x02 by \x02{}\x02 - {}".format(data["albums"][0]["name"],
data["albums"][0]["artists"][0]["name"], url)
return "\x02{}\x02 by \x02{}\x02 - {} / {}".format(name, artist,
url, uri)


@hook.command
@hook.command("spartist", "artist")
def spartist(text):
"""spartist <artist> -- Search Spotify for <artist>"""
params = {'q': text.strip()}

request = requests.get('http://ws.spotify.com/search/1/artist.json', params=params)
params = {
"q": text.strip(),
"offset": 0,
"limit": 1,
"type": "artist"
}

request = requests.get(api_url, params=params)
if request.status_code != requests.codes.ok:
return "Could not get artist information: {}".format(request.status_code)

data = request.json()
data = request.json()["artists"]["items"][0]

try:
_type, _id = data["artists"][0]["href"].split(":")[1:]
artist, url, uri = (data["name"],
data["external_urls"]["spotify"],
data["uri"])
except IndexError:
return "Could not find artist."
url = web.try_shorten(gateway.format(_type, _id))
return "Unable to find any artists!"

return "\x02{}\x02 - {}".format(data["artists"][0]["name"], url)
return "\x02{}\x02 - {} / {}".format(artist, url, uri)


@hook.regex(http_re)
@hook.regex(spotify_re)
def spotify_url(match):
_type = match.group(2)
spotify_id = match.group(3)
url = spuri.format(_type, spotify_id)
# no error catching here, if the API is down fail silently
params = {'uri': url}
request = requests.get('http://ws.spotify.com/search/1/artist.json', params=params)
if request.status_code != requests.codes.ok:
return
data = request.json()

if _type == "track":
name = data["track"]["name"]
artist = data["track"]["artists"][0]["name"]
album = data["track"]["album"]["name"]
request = requests.get("https://api.spotify.com/v1/tracks/{}".format(spotify_id))
data = request.json()

return "Spotify Track: \x02{}\x02 by \x02{}\x02 from the album \x02{}\x02".format(data["name"], data["album"]["artists"][0]["name"], data["album"]["name"])

return "Spotify Track: \x02{}\x02 by \x02{}\x02 from the album \x02{}\x02".format(name, artist, album)
elif _type == "artist":
return "Spotify Artist: \x02{}\x02".format(data["artist"]["name"])
request = requests.get("https://api.spotify.com/v1/artists/{}".format(spotify_id))
data = request.json()

return "Spotify Artist: \x02{}\x02, followers: \x02{}\x02, genres: \x02{}\x02".format(data["name"], data["followers"]["total"], ', '.join(data["genres"]))

elif _type == "album":
return "Spotify Album: \x02{}\x02 - \x02{}\x02".format(data["album"]["artist"], data["album"]["name"])
request = requests.get("https://api.spotify.com/v1/albums/{}".format(spotify_id))
data = request.json()

return "Spotify Album: \x02{}\x02 by \x02{}\x02".format(data["name"], data["artists"][0]["name"])

0 comments on commit ff623f3

Please sign in to comment.