Skip to content

Instantly share code, notes, and snippets.

@nathan-v
Created December 22, 2017 18:09
Show Gist options
  • Save nathan-v/67b444c0baec3eb23d3339ddc5da03ef to your computer and use it in GitHub Desktop.
Save nathan-v/67b444c0baec3eb23d3339ddc5da03ef to your computer and use it in GitHub Desktop.
Pulls my 'now playing' track from Last.fm and posts it to Slack as my status with the 🎧 emoji.
#!/usr/bin/env python
# coding: utf-8
#
# Nowplaying (via Last.fm) to Slack
# Author: Nathan V <Nathan.V@gmail.com>
#
# Copyright 2017 Nathan V
# License: MIT; https://opensource.org/licenses/MIT
# This simple little script could be expanded to support command line
# args, multiple sources, and multiple Slack domains... but for now it
# gets the job done posting my current tunes so ¯\_(ツ)_/¯
#
# Works on Python 2.7.3+ and 3.3.0+
#
# Expects ~/.config/last-fm.yml with an API key and user name
# Expects ~/.config/slack.yml with a legacy key
#
# Deps: pip install requests retry pyyaml
from __future__ import print_function
import os
import time
import requests
from requests.exceptions import HTTPError, ConnectionError
from retry import retry
import yaml
class NPSlack:
def __init__(self):
self.lastfm_config = yaml.load(
open(os.path.expanduser('~/.config/last-fm.yml')))
self.lastfm_url_base = 'https://audioscrobbler.com/'
self.lastfm_user = self.lastfm_config['user']
self.lastfm_key = self.lastfm_config['key']
self.slack_config = yaml.load(
open(os.path.expanduser('~/.config/slack.yml')))
self.slack_url_base = 'https://slack.com/api/'
self.slack_key = self.slack_config['key']
def update(self):
print('Getting data from Last.fm...', end='')
lfm = self.last_fm_playing()
print("Got info: {}".format(lfm))
if lfm is not None:
print('Sending to Slack status...', end='')
self.slack_status("Now playing: {}".format(lfm), ':headphones:')
else:
print('Nothing playing; blanking Slack...', end='')
self.slack_status('', '')
print('Done.')
@retry((HTTPError, ConnectionError), delay=1, backoff=2, tries=4)
def last_fm_playing(self):
params = {'method': 'user.getrecenttracks',
'user': self.lastfm_user,
'api_key': self.lastfm_key,
'format': 'json',
'limit': 1}
req = requests.get(
"{}2.0/".format(self.lastfm_url_base),
params=params
)
lfm_data = req.json()['recenttracks']
try:
if lfm_data['track'][0]['@attr']['nowplaying'] == 'true':
artist = lfm_data['track'][0]['artist']['#text']
song = lfm_data['track'][0]['name']
result = "{} - {}".format(artist, song)
else:
result = None
return result
except KeyError:
return None
@retry((HTTPError, ConnectionError), delay=1, backoff=2, tries=4)
def slack_status(self, text, emoji):
profile = '{{"status_text":"{}","status_emoji":"{}"}}'.format(
text, emoji
)
params = {'token': self.slack_key,
'profile': profile}
requests.get(
"{}users.profile.set".format(self.slack_url_base),
params=params
)
def main():
np_slack = NPSlack()
while True:
try:
np_slack.update()
time.sleep(60)
except (KeyboardInterrupt, SystemExit):
exit()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment