Skip to content

Instantly share code, notes, and snippets.

@MariaRigaki
Created March 19, 2025 06:31
Show Gist options
  • Select an option

  • Save MariaRigaki/f184e8c078a6e64ca31e78b8f261a7eb to your computer and use it in GitHub Desktop.

Select an option

Save MariaRigaki/f184e8c078a6e64ca31e78b8f261a7eb to your computer and use it in GitHub Desktop.
Lichess discord presence
import requests
import time
from pypresence import Presence
import logging
# Setup logging
logging.basicConfig(filename='/var/log/lichess-discord.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Lichess Discord Presence service started!")
# Replace with your actual credentials
LICHESS_USERNAME = "<YOUR LICHESS USERNAME>"
DISCORD_CLIENT_ID = "<YOUR DISCORD CLIENT ID>"
LICHESS_API_TOKEN = "<YOUR LICHESS API TOKEN>"
LICHESS_API_URL = "https://lichess.org/api/account/playing"
HEADERS = {"Authorization": f"Bearer {LICHESS_API_TOKEN}"}
rpc = None # We will initialize this dynamically
def connect_to_discord():
global rpc
try:
rpc = Presence(DISCORD_CLIENT_ID)
rpc.connect()
#print("✅ Connected to Discord RPC")
logging.info("✅ Connected to Discord RPC")
except Exception as e:
print(f"⚠️ Could not connect to Discord: {e}")
logging.error(f"⚠️ Could not connect to Discord: {e}")
rpc = None # Reset if failed
def get_lichess_status():
response = requests.get(LICHESS_API_URL, headers=HEADERS)
if response.status_code == 200:
data = response.json()
games = data.get("nowPlaying", [])
for game in games:
game_type = game.get("speed", "")
if game_type != "correspondence": # Ignore correspondence games
time_left_seconds = game.get("secondsLeft", 0)
minutes = time_left_seconds // 60
seconds = time_left_seconds % 60
time_display = f"{minutes}:{seconds:02d}" # Format MM:SS
opponent = game.get("opponent", {}).get("username", "Unknown Opponent")
# TODO: Check why this is not working
#time_control = game.get("timeControl", "Unknown") # Example: "5+0"
rated = game.get("rated", False)
# Customize your Discord status message!
if rated:
details = f"Playing a rated {game_type}"
else:
details = f"Playing a casual {game_type}"
state = f"vs {opponent} | {time_display} left"
return game["fullId"], details, state
return None, None, None
# Try to connect initially
connect_to_discord()
while True:
if rpc is None:
logging.debug("🔄 Trying to reconnect to Discord...")
connect_to_discord()
if rpc:
try:
game_url, details, state = get_lichess_status()
if game_url:
rpc.update(details=details, state=state, large_image="lichess-logo")
logging.info(f"🟢 Updated status: {details} | {state}")
else:
rpc.clear()
logging.info("⚪ No active game. Clearing status.")
except Exception as e:
logging.error(f"❌ Lost connection to Discord: {e}")
rpc = None # Reset to trigger reconnect
time.sleep(15) # Check every minute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment