Operator-logik effizienter gemacht

Durch die neuen Infos ist es möglich, die Betreiber direkt auszulesen. Dadurch muss nicht nur ein Betreiber komisch durch die Anfangsbuchstaben gefunden werden
This commit is contained in:
Kaaninchen
2026-07-17 23:37:26 +02:00
parent 8cca3133f2
commit 23f4134b8b
4 changed files with 38 additions and 48 deletions
+8 -21
View File
@@ -1,35 +1,22 @@
db_logo = "https://marketingportal.extranet.deutschebahn.com/resource/blob/13602522/c53f806b9df966e144010b276af72dd2/Bild_09-data.png"
db_slogans = ["Senk ju vor träwelling wis Deutsche Bahn.", "Bitte beachten Sie die umgekehrte Wagenreihung.", "Zurückbleiben bitte!", "Alle reden vom Wetter. Wir nicht.", "Die Bahn macht mobil.", "Grün abgefahren"] db_slogans = ["Senk ju vor träwelling wis Deutsche Bahn.", "Bitte beachten Sie die umgekehrte Wagenreihung.", "Zurückbleiben bitte!", "Alle reden vom Wetter. Wir nicht.", "Die Bahn macht mobil.", "Grün abgefahren"]
OPERATORS = { OPERATORS = {
# alles außer slogan ist ESSENZIELL für den Bot. # alles außer slogan ist ESSENZIELL für den Bot.
# Color ist Hex Color Code mit 0x am anfang. # Color ist Hex Color Code mit 0x am anfang.
"fallback": { "fallback": {
"name": "Unbekannter Anbieter", "unknown": True,
"logo": "https://upload.wikimedia.org/wikipedia/commons/2/20/Bahn_aus_Zusatzzeichen_1024-15_A.png", "logo": "https://upload.wikimedia.org/wikipedia/commons/2/20/Bahn_aus_Zusatzzeichen_1024-15_A.png",
"color": 0x000000 "color": 0x000000
}, },
"ICE": { "DB": {
"name": "Deutsche Bahn", "unknown": False,
"logo": db_logo, "logo": "https://marketingportal.extranet.deutschebahn.com/resource/blob/13602522/c53f806b9df966e144010b276af72dd2/Bild_09-data.png",
"color": 0xEC0016, "color": 0xEC0016,
"slogan": db_slogans "slogan": db_slogans
}, },
"RB": { "Ostdeutsche Eisenbahn GmbH": {
"name": "DB Regio", "unknown": False,
"logo": db_logo, "logo": "https://www.odeg.de/fileadmin/user_upload/Unternehmensseite/presse/pressebilder/ODEG_Pressebilder_Logo-CMYK-JPG.jpg",
"color": 0xEC0016, "color": 0x00745C
"slogan": db_slogans
},
"RE": {
"name": "DB Regio",
"logo": db_logo,
"color": 0xEC0016,
"slogan": db_slogans
},
"NBE": {
"name": "Nordbahn",
"logo": "https://upload.wikimedia.org/wikipedia/commons/b/b5/Logo_Nordbahn_NAH.SH_Blau_positiv_final.png",
"color": 0x1A2848
} }
} }
+14 -12
View File
@@ -2,7 +2,7 @@ import random
import discord import discord
from datetime import datetime, timedelta from datetime import datetime, timedelta
import src.handlers as handlers import src.handlers as handlers
from src.utils import operator_infos, format_via_list, logger from src.utils import operator_metadata, format_via_list, logger
def format_timestamp(timestr): def format_timestamp(timestr):
parsed_time = datetime.strptime(timestr, "%H:%M") parsed_time = datetime.strptime(timestr, "%H:%M")
@@ -30,28 +30,30 @@ def build_info_embed() -> discord.Embed | None:
conn = handlers.current conn = handlers.current
info = handlers.train_info info = handlers.train_info
current_operator = info["operators"][0]
arrival = format_iso_timestamp(info["arrival"]) arrival = format_iso_timestamp(info["arrival"])
departure = format_timestamp(conn['departure']) departure = format_timestamp(conn['departure'])
operator = operator_infos(conn["train"])
if current_operator.split()[0] == "DB":
operator_infos = operator_metadata("DB") # die haben auch 500 tochterkonzerne da blickt keiner durch
else:
operator_infos = operator_metadata(current_operator)
embed = discord.Embed( embed = discord.Embed(
title=handlers.train_name, title=handlers.train_name,
description=f"Abfahrt von {conn['station']} um {departure}. Ankunft um {arrival}", description=f"Abfahrt von {conn['station']} um {departure}. Ankunft um {arrival}",
color=operator["color"] color=operator_infos["color"]
) )
if len(conn['via']) > 0: if len(conn['via']) > 0:
embed.add_field(name="Über", value=format_via_list(conn['via']), inline=False) embed.add_field(name="Über", value=format_via_list(conn['via']), inline=False)
if operator["name"] == "Unbekannter Anbieter": if operator_infos.get("unknown"):
anbieter = conn['train'].split()[0] logger(f"WARNING: {current_operator} nicht in operators.py gefunden")
logger(f"INFO: Unbekannter Anbieter für Typ {anbieter}")
operator_name = f"{operator['name']} (Typ: {anbieter})"
else:
operator_name = operator["name"]
embed.set_author(name=operator_name) embed.set_author(name=current_operator)
embed.set_thumbnail(url=operator["logo"]) embed.set_thumbnail(url=operator_infos["logo"])
route_lines = [] route_lines = []
for stop in conn['route']: for stop in conn['route']:
@@ -63,7 +65,7 @@ def build_info_embed() -> discord.Embed | None:
embed.add_field(name="Route", value="\n".join(route_lines)) embed.add_field(name="Route", value="\n".join(route_lines))
slogans = operator.get("slogan") slogans = operator_infos.get("slogan")
footer_text = ( footer_text = (
f"{random.choice(slogans)} • Daten großzügig bereitgestellt von dbf.finalrewind.org" f"{random.choice(slogans)} • Daten großzügig bereitgestellt von dbf.finalrewind.org"
if slogans else if slogans else
+5 -4
View File
@@ -22,7 +22,8 @@ async def rename_vc(bot: discord.Bot, scheduled = False) -> bool:
current = random_connection() current = random_connection()
train_type = current['train'].split()[0] train_type = current['train'].split()[0]
if train_type in ("IC", "ICE", "NJ", "ES", "DZ"): print(train_type)
if train_type in ("IC", "ICE", "NJ", "ES", "DZ"): # Diese Züge haben ihre normalen Namen, nicht sowas wie RE RE7 sondern ICE 781 zb
train = current['train'] train = current['train']
train_ID = current['train'].split()[1] train_ID = current['train'].split()[1]
else: else:
@@ -39,7 +40,7 @@ async def rename_vc(bot: discord.Bot, scheduled = False) -> bool:
_scheduled_task = asyncio.create_task(_schedule_next_umstieg(bot, train_info["arrival"])) _scheduled_task = asyncio.create_task(_schedule_next_umstieg(bot, train_info["arrival"]))
print("-----------------------------------------") print("-----------------------------------------")
logger(f"Umstieg: {train_name} (Typ {train_type}) von {current['station']}") logger(f"Umstieg: {train_name} von {current['station']}")
logger(f"Wenn der Name nicht geändert wird bin ich im Cooldown") logger(f"Wenn der Name nicht geändert wird bin ich im Cooldown")
await channel.edit(name=f"{config['formatting']}{train_name}",) await channel.edit(name=f"{config['formatting']}{train_name}",)
logger(f"Name geändert!") logger(f"Name geändert!")
@@ -48,9 +49,9 @@ async def rename_vc(bot: discord.Bot, scheduled = False) -> bool:
async def _schedule_next_umstieg(bot, arrival_iso): async def _schedule_next_umstieg(bot, arrival_iso):
try: try:
arrival = datetime.fromisoformat(arrival_iso) # arrival = datetime.fromisoformat(arrival_iso)
# wait_seconds = (arrival - datetime.now()).total_seconds() # wait_seconds = (arrival - datetime.now()).total_seconds()
wait_seconds = 30 wait_seconds = 30 # debug aktuell
if wait_seconds > 0: if wait_seconds > 0:
remaining = str(timedelta(seconds=wait_seconds)) remaining = str(timedelta(seconds=wait_seconds))
+8 -8
View File
@@ -19,6 +19,7 @@ def random_connection():
departures = [ departures = [
d for d in data.get("departures", []) d for d in data.get("departures", [])
if d.get("scheduledDeparture") and d.get("destination") != station if d.get("scheduledDeparture") and d.get("destination") != station
and not d.get("train", "").startswith("S ")
] ]
if not departures: if not departures:
@@ -35,14 +36,6 @@ def random_connection():
"train_number": dep['trainNumber'] "train_number": dep['trainNumber']
} }
def operator_infos(train):
if not train:
return OPERATORS["fallback"]
train_type = train.split()[0]
return OPERATORS.get(train_type, OPERATORS["fallback"])
def format_via_list(via: list[str]): def format_via_list(via: list[str]):
if not via: if not via:
return "" return ""
@@ -61,11 +54,18 @@ def get_train_info(station, train_ID, train_type):
dep = data.get("departure", []) dep = data.get("departure", [])
arrival_iso = dep["route_post_diff"][-1]["sched_arr"] arrival_iso = dep["route_post_diff"][-1]["sched_arr"]
print(dep["operators"])
return { return {
"arrival": arrival_iso, "arrival": arrival_iso,
"operators": dep["operators"] "operators": dep["operators"]
} }
def operator_metadata(operator):
if not operator:
return OPERATORS["fallback"]
return OPERATORS.get(operator, OPERATORS["fallback"])
def logger(msg): def logger(msg):
current_time = datetime.now().strftime('%X') current_time = datetime.now().strftime('%X')
print(f"{current_time}: {msg}") print(f"{current_time}: {msg}")