quotes_display/quotes.py

74 lines
2.1 KiB
Python
Raw Normal View History

2024-09-12 19:15:21 +02:00
from rich.align import Align
2024-09-12 19:26:24 +02:00
from rich.console import Console
2024-09-12 19:15:21 +02:00
from rich.layout import Layout
from rich.live import Live
from rich.padding import Padding
2024-09-12 19:26:24 +02:00
from rich.text import Text
import json
2024-09-12 19:15:21 +02:00
import random
2024-09-12 19:26:24 +02:00
import requests
import time
from denylist import get_deny_list
denylist = get_deny_list()
def refresh_quotes():
res = None
try:
# Fetch quotes
res = requests.get('https://mattermore.zeus.gent/quotes.json').json()
2024-09-17 19:11:07 +02:00
assert len(res) > 150
res = res[-150:]
2024-09-12 19:26:24 +02:00
except:
pass
2024-09-12 19:15:21 +02:00
2024-09-12 19:26:24 +02:00
if res is None:
# Fallback: load last quotes
try:
with open('last_quotes.json') as f:
res = json.load(f)
except:
assert False, "Failed to fetch quotes, and failed to load fallback json"
else:
try:
# Fetched successfully
# Save to disk for the fallback
with open('last_quotes.json', 'w') as f:
json.dump(res, f)
except:
pass
# Only keep non-denied quotes
res = [q for q in res if not any(denied in q['quote'] for denied in denylist)]
return res
2024-09-12 19:15:21 +02:00
def render_quote(quote):
for i in range(len(quote['quote'])):
l = Layout()
l.split_column(
Layout(f"Mattermost: ~{quote['channel']}", size=1),
Layout(Align.center(Padding(quote['quote'][:i+1], (0, 4)), vertical="middle")),
Layout(quote['created_at'][:10], size=1)
)
yield l
2024-09-12 19:26:24 +02:00
with Live(
renderable=Layout(Align.center(Text("Yeet"), vertical="middle")),
console=Console(highlighter=None),
refresh_per_second=30
) as live:
first_it = True
2024-09-12 19:15:21 +02:00
while True:
2024-10-09 19:37:06 +02:00
try:
quotes = refresh_quotes()
for _ in range(500):
for q in render_quote(random.choice(quotes) if not first_it else quotes[-1]):
live.update(q)
time.sleep(0.05)
time.sleep(30)
first_it = False
except KeyboardInterrupt:
# Ctrl-C reloads, kill me with Ctrl-\
first_it = True
pass