Skip to content

Instantly share code, notes, and snippets.

@theoparis
Created October 29, 2023 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theoparis/da4abda3929c1f8d65b7fd6acd5a16e1 to your computer and use it in GitHub Desktop.
Save theoparis/da4abda3929c1f8d65b7fd6acd5a16e1 to your computer and use it in GitHub Desktop.
Send emerge output from gentoo portage to a custom discord status
#!/usr/bin/env python3
import re
import subprocess
import sys
import json
import os
import requests
import threading
token = os.environ.get("DISCORD_TOKEN")
emerge_process = subprocess.Popen(
["emerge"] + sys.argv[2:],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
universal_newlines=True,
)
current_jobs = None
max_jobs = None
package_being_emerged = ""
output_lock = threading.Lock()
def capture_stdout():
global package_being_emerged
global current_jobs
global max_jobs
global emerge_process
while True:
line = emerge_process.stdout.readline()
if not line:
break
with output_lock:
print(line, end="")
match = re.match(r">>> Emerging \(\d+ of \d+\) (.+)::gentoo", line.strip())
if match:
package_being_emerged = match.group(1)
job_match = re.match(r'>>> Jobs: (\d+) of (\d+) complete', line.strip())
if job_match:
current_jobs = int(job_match.group(1))
max_jobs = int(job_match.group(2))
# Discord Webhook URL
discord_webhook_url = "https://discord.com/api/v8/users/@me/settings"
# Set the headers
headers = {
"Authorization": token,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
"Content-Type": "application/json",
"Accept": "*/*",
}
# Create JSON payload
payload = {
"status": "online",
"custom_status": {
"text": f"[{current_jobs}/{max_jobs}] Emerging {package_being_emerged}"
},
}
# Send the payload to Discord using a PATCH request
response = requests.patch(
discord_webhook_url, headers=headers, data=json.dumps(payload)
)
print(f"discord: {response.status_code} - {response.text}")
def capture_stderr():
global emerge_process
while True:
line = emerge_process.stderr.readline()
if not line:
break
with output_lock:
print(line, end="")
stdout_thread = threading.Thread(target=capture_stdout)
stderr_thread = threading.Thread(target=capture_stderr)
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment