Skip to content

Instantly share code, notes, and snippets.

@curtisgibby
Created February 23, 2019 00:53
Show Gist options
  • Save curtisgibby/02e705ef2452106ed57d366b299ff5e4 to your computer and use it in GitHub Desktop.
Save curtisgibby/02e705ef2452106ed57d366b299ff5e4 to your computer and use it in GitHub Desktop.
Linux media player (MPRIS) now playing status to Slack
from ansimarkup import ansiprint
import calendar
import datetime
import dbus
import json
import random
import re
import requests
token = '<YOUR_SLACK_TOKEN_HERE>'
def getPlayingPlayer():
session_bus = dbus.SessionBus()
for service in session_bus.list_names():
if re.match('org.mpris.MediaPlayer2.', service):
player = session_bus.get_object(service, '/org/mpris/MediaPlayer2')
interface = dbus.Interface(player, 'org.freedesktop.DBus.Properties')
playbackStatus = interface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
if playbackStatus == 'Playing':
ansiprint('<yellow>Currently playing:</yellow> ' + interface.Get('org.mpris.MediaPlayer2', 'Identity'))
return interface
ansiprint('<red>No players playing!</red>')
quit()
interface = getPlayingPlayer()
metadata = interface.Get('org.mpris.MediaPlayer2.Player', 'Metadata')
status_text = 'Now Playing: ' + ','.join(metadata['xesam:artist']) + ' - ' + metadata['xesam:title']
expiration_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=2)
profile = {
'status_text': status_text,
'status_emoji': random.choice([
':cd:',
':headphones:',
':musical_note:',
':notes:',
':radio:',
]),
'status_expiration': calendar.timegm(expiration_time.timetuple()),
}
postBody = {
'profile': json.dumps(profile),
'token': token,
}
url = 'https://slack.com/api/users.profile.set'
ansiprint('<yellow>Attempting to set status:</yellow> ' + status_text)
r = requests.post(url, data = postBody)
if(r.ok):
parsed = json.loads(r.text)
if parsed['ok']:
ansiprint('<green>Success</green>')
else:
ansiprint('<red>Error setting status : ' + parsed['error'] + '</red>')
else:
r.raise_for_status()
@curtisgibby
Copy link
Author

Background info for setting Slack status programatically
Get your own Slack token here, then plug it in on line 10 instead of <YOUR_SLACK_TOKEN_HERE>

@curtisgibby
Copy link
Author

I've tested this with the following players on Linux Mint 18:

Theoretically, it should work for any player client that supports the MPRIS spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment