Xfce Forum

Sub domains
 

You are not logged in.

#1 2024-04-13 23:55:50

hacker097
Member
Registered: 2024-04-13
Posts: 4

[SOLVED] genmon-plugin randomly stopped working with my script

I made a script to show my current spotify song, and it works fine.

#!/usr/bin/env bash

readonly DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

readonly ICON="${DIR}/icons/spotify.png"
readonly ICON_OFFLINE="${DIR}/icons/spotify_offline.png"
readonly DISPALY_TITLE_MAX_LENGTH=50
        
if [[ "$(playerctl status 2>&1)" = "Paused" ]] || [[ "$(playerctl status 2>&1)" = "No players found" ]]; then
  h="$(python /home/truegav/Desktop/stuff/xfce4-spotify-panel/getname.py)"
  echo "<img>${ICON}</img>"
  echo "<txt>$h</txt>"
else
  echo "<txt>$(playerctl metadata title) - $(playerctl metadata artist)</txt>"
fi
$./spotify-panel.sh
<img>/home/truegav/Desktop/stuff/xfce4-spotify-panel/icons/spotify.png</img>
<txt>Jealous - Future</txt>

This worked fine for some time, until the pan randomly stopped displaying the song name. It will still show other text, or variables, say if I do

h="HELLO"

it still works. But for whatever reason it refuses to show my song name, even though running it from bash gives the intended output.

Another weird thing is if I add this line

notify-send "HELLO"

I get a notification at the delay I have set, but if I change it to

notify-send "$h"

I don't get any notifications.

This is all I see: https://ibb.co/nQRtdN7

It displays correctly for the else statement, that is when I am getting the text from `playerctl`: https://ibb.co/rfrwLSH

Refreshing/restarting/reinstalling does did not fix it. Any idea what's going on here?

Last edited by hacker097 (2024-04-14 22:07:04)

Offline

#2 2024-04-14 01:51:22

ToZ
Administrator
From: Canada
Registered: 2011-06-02
Posts: 11,486

Re: [SOLVED] genmon-plugin randomly stopped working with my script

Hello and welcome.

There are a number of confusing things with your post.

  1. The executable you run to get the output is "spotify-panel.sh", but the genmon script calls "getname.py"

  2. The if statement in your genmon script is using the equals sign incorrectly. "=" is an assignment, "==" is a comparison. This if will always return true.

  3. Not exactly sure what "getname.py" returns, but this script will always return the output of that command

  4. You have a couple of unused variables in the script

What is in the getname.py script?
Try changing the "=" to "==".


Please remember to mark your thread [SOLVED] to make it easier for others to find
--- How To Ask For Help | FAQ | Developer Wiki  |  Community | Contribute ---

Offline

#3 2024-04-14 09:45:02

hacker097
Member
Registered: 2024-04-13
Posts: 4

Re: [SOLVED] genmon-plugin randomly stopped working with my script

Hello, thank you for replying. Sorry for being a bit unclear in my post. Here are the answers to your questions.

1. I should have mentioned this, but "spotify-panel.sh" is the script being called by genmon, not "getname.py"
2. This did seem odd to me, but weirdly both of them work. Regardless, the if statements are not the problem here, because the "playerctl" does show up on my panel when I play something. And the spotify logo shoes up when thats not the case.
3. "getname.py" is a script I made to get my current song name and artist using spotify api. Its a bit dirty and complicated, which is why I don't want to share it here. But for the sake of the issue, at least according to me, it could just be "print('Jealous - Future')". But thats not true. I was testing, and when I replace "getname.py" to this print statement, it shows up correctly. Even when I add some delay, which the original script has. But the output from the original script, which is just printing a name with a delay of like half a second, does not show up. I cannot think of any reason why this would happen.
4. Ah, thats because I started with someone else's script, removing most of it because it get the name from the spotify app, rather than the api, so it would not have shown the song if I was playing it on another device.

I have removed he if statements entirely to narrow down the problem.

I think the issue is, when ran from bash "getname.py" is run, but its just not run when ran by genmon. When I modify "getname.py" to write to "name.txt" instead of printing the name, genmon never runs "getname.py"

#!/usr/bin/env bash

readonly DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly ICON="${DIR}/icons/spotify.png"

python /home/truegav/Desktop/stuff/xfce4-spotify-panel/getname.py
echo "<img>${ICON}</img>"
echo "<txt>$(cat /home/truegav/Desktop/stuff/xfce4-spotify-panel/name.txt)</txt>"

I know genmon is reading "name.txt" correctly because the panel updates when I run  "getname.py" manually. Why genmon runs some python scripts, and not others is beyond me.

The answer likely lies in "getname.py" which I didn't want to share because its a bit hard to get it running yourself and I would not expect anyone to go through this mess without even being able to run it. But here it is. In short, "get_access()" gets a code using my clientid and clientsecret by making request which has the cookie of a logged in session. The code is used by "get_token()" to get the token, the token is used by "get_current_track()" to get and print the currently playing track.

import requests
import json
import random

SPOTIFY_GET_CURRENT_TRACK_URL = 'https://api.spotify.com/v1/me/player/currently-playing'

def save_token(token):
    with open("token.txt", "w") as file:
        file.write(str(token))

def read_token():
    with open("token.txt", "r") as file:
        token = file.read().strip()
        return token

def save_name(name):
    with open("name.txt", "w") as file:
        file.write(str(name))

def get_access():
    params = {
        'response_type': 'code',
        'client_id': '...',
        'scope': 'user-read-currently-playing',
        'redirect_uri': 'http://localhost:8888/callback',
        'state': random.randint(9999, 9999999),
    }
    url = 'https://accounts.spotify.com/authorize'

    full_url = f'{url}?{"&".join([f"{key}={value}" for key, value in params.items()])}'

    cookies = {
        ...
    }

    headers = {
        ...
    }

    response = requests.get(
        full_url,
        cookies=cookies,
        headers=headers,
        allow_redirects=False,
    )

    return response.headers['Location'].split("=")[1].split("&")[0]

def get_token(code):
    token_url = 'https://accounts.spotify.com/api/token'

    client_id = '...'
    client_secret = '...'

    authorization_code = code

    redirect_uri = "http://localhost:8888/callback"

    payload = {
        'grant_type': 'authorization_code',
        'code': authorization_code,
        'redirect_uri': redirect_uri,
        'client_id': client_id,
        'client_secret': client_secret
    }

    response = requests.post(token_url, data=payload)

    if response.status_code == 200:
        access_token = response.json()['access_token']
        return access_token
    else:
        print("Failed to get access token:", response.text)

def get_current_track(token):

    headers = {
        'Authorization': 'Bearer ' + token
    }

    response = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers)

    data =  json.loads(response.text)

    if "error" in data:
        code  = get_access()
        token = get_token(code)

        save_token(token)

        headers = {
            'Authorization': 'Bearer ' + token
        }

        response = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers)

        data =  json.loads(response.text)

    #print(data)
    name = data["item"]["name"]
    artist = ", ".join([i["name"] for i in [artist for artist in data['item']['artists']]])

    save_name(f"{name} - {artist}")

token = read_token()
get_current_track(token)

Last edited by hacker097 (2024-04-14 09:46:44)

Offline

#4 2024-04-14 15:48:53

hacker097
Member
Registered: 2024-04-13
Posts: 4

Re: [SOLVED] genmon-plugin randomly stopped working with my script

Alright, I have managed to recreate the issue in a far easier way.

#!/usr/bin/env bash

title="$(playerctl metadata title)"
artist="$(playerctl metadata artist)"
echo "<txt>${title}</txt>"
if [[ -n $artist ]]; then echo "<txt> - $artist </txt>"; fi

Here is the panel: https://ibb.co/cCNYZz6

Here is the bash output:

$./spotify-panel.sh
<txt>You're Not a Monk</txt>
<txt> - Bettina Levy </txt>

Offline

#5 2024-04-14 19:09:28

ToZ
Administrator
From: Canada
Registered: 2011-06-02
Posts: 11,486

Re: [SOLVED] genmon-plugin randomly stopped working with my script

You have too many <txt></txt> blocks - genmon will only process the first.
Try this as your genmon script:

#!/usr/bin/env bash

OUTPUT="$(playerctl metadata title)"
ARTIST="$(playerctl metadata artist)"
if [[ -n $ARTIST ]]; then OUTPUT="$OUTPUT - $ARTIST"; fi

echo "<txt>$OUTPUT</txt>"

Please remember to mark your thread [SOLVED] to make it easier for others to find
--- How To Ask For Help | FAQ | Developer Wiki  |  Community | Contribute ---

Offline

#6 2024-04-14 22:05:05

hacker097
Member
Registered: 2024-04-13
Posts: 4

Re: [SOLVED] genmon-plugin randomly stopped working with my script

Thank you so much for your help. I was able to solve both my issues.

Although it seemed to me that I had recreated the original issue in my second reply, I had not. I thought it was another case of genmon not displaying the correct thing even though running from bash gives the correct output. But as you pointed out, we can only use 1 "<txt>" block. Your script fixed the issue.

As for the original issue, it was caused by my "getname.py" not using the full path. In my testing I was executing everything from the same directory, so didn't notice it. I just had to replace the path everywhere I was reading/writing a file to the file's full path. It took me a while to get this. I wonder if genmon logs it's errors anywhere, or the last output, would have saved a lot of headache.

Thanks again for your help.

Offline

#7 2024-04-15 00:41:08

ToZ
Administrator
From: Canada
Registered: 2011-06-02
Posts: 11,486

Re: [SOLVED] genmon-plugin randomly stopped working with my script

hacker097 wrote:

I wonder if genmon logs it's errors anywhere, or the last output, would have saved a lot of headache.

It would log its errors to your xsession errors log file. Depending on the distro, this might be in ~/.xsession-errors and/or your journal (systemd).


Please remember to mark your thread [SOLVED] to make it easier for others to find
--- How To Ask For Help | FAQ | Developer Wiki  |  Community | Contribute ---

Offline

Registered users online in this topic: 0, guests: 1
[Bot] ClaudeBot

Board footer

Powered by FluxBB
Modified by Visman

[ Generated in 0.010 seconds, 7 queries executed - Memory usage: 587.98 KiB (Peak: 604.83 KiB) ]