Compare commits

..
10 Commits
Author SHA1 Message Date
Kaaninchen f65aa3cfa0 fix grammatical error in NS slogans (how embarassing)... 2026-08-28 19:53:49 +02:00
Kaaninchen e9708d435e fix example config 2026-08-28 19:42:32 +02:00
Kaaninchen d50cf0277b readme 2026-08-28 15:51:41 +02:00
Kaaninchen dde0c443de map improvements 2026-08-27 13:10:30 +02:00
Kaaninchen 93b9712394 up max_attempt to 30 2026-08-24 07:55:06 +02:00
Kaaninchen 21a279839d update favicon 2026-08-23 17:57:01 +02:00
Kaaninchen 1c006731a4 feat: priority list 2026-08-23 17:21:22 +02:00
Kaaninchen db43ee4279 forgot to include de.yaml 2026-08-23 16:10:11 +02:00
Kaaninchen dc2f9dade0 move footer_notice from lang files to source code 2026-08-23 16:09:52 +02:00
Kaaninchen 10b6ee560e README: rename python run file to python file 2026-08-23 13:39:48 +02:00
14 changed files with 98 additions and 131 deletions
+34 -5
View File
@@ -4,7 +4,7 @@ Gleiswechsel [ˈɡlaɪsvɛksəl] (german for "platform change") is a selfhostabl
![Example Channel](.github/preview_kanal.png) ![Example Channel](.github/preview_kanal.png)
## Features ## Features
- [International support](https://transitous.org/sources/) for countries aswell as and cities - [International support](https://transitous.org/sources/) for countries as well as cities
- Support for various types of transportations, including but not limited to Subways, Busses, Funiculars, Trams and Trains - Support for various types of transportations, including but not limited to Subways, Busses, Funiculars, Trams and Trains
- Multi language support (+ option to easily add more languages) - Multi language support (+ option to easily add more languages)
- Announcements, including the option to join the voice chat and play an audio file while arriving at a specific station - Announcements, including the option to join the voice chat and play an audio file while arriving at a specific station
@@ -82,7 +82,7 @@ but you can safely ignore this warning if you're fine with it.
If not, I've created a tool which would help you to get the exact station name. You can use the tool by running If not, I've created a tool which would help you to get the exact station name. You can use the tool by running
```sh ```sh
$ python run main.py stations $ python main.py stations
``` ```
Example output: Example output:
@@ -121,12 +121,35 @@ For every station inside of the `stations.json` you'll find an ID. You can add t
This is especially useful if you want to add a station whose name isn't unique and also used by other stations. The bot would falsely use the first station with the same name and consider it an exact match, even if you wanted a different one. This won't happen with the ID, as every ID is uniquely assigned to only one station. This is especially useful if you want to add a station whose name isn't unique and also used by other stations. The bot would falsely use the first station with the same name and consider it an exact match, even if you wanted a different one. This won't happen with the ID, as every ID is uniquely assigned to only one station.
##### priority
You can define priorities of transport modes while selecting a connection. Leave empty to disable
The list should be descending, with "1" as the most important transport mode. For example, let's say, the bot should always choose Trains and other longer distance public transport modes. If it can't find any, then it should resort to Metros/Subways/Suburbans. If these are also missing at that station, then it should just use Busses/Trams:
```json
"priority": {
"HIGHSPEED_RAIL": 1,
"LONG_DISTANCE": 1,
"NIGHT_RAIL": 1,
"REGIONAL_RAIL": 1,
"COACH": 1,
"FERRY": 1,
"METRO": 2,
"SUBURBAN": 2,
"SUBWAY": 2,
"BUS": 3,
"TRAM": 3
}
```
A transport mode that isn't in the priority list would immediately get assigned the value of "99", making it near impossible to get that connection. Except when there are no other connections available, of course.
You can find the MODE names either in the console log or the stations.json from [helper tool](#stations)
##### blacklist ##### blacklist
You can blacklist specific types of transport, the bot would then skip them while selecting a connection. You can get the type either in your console (mode) You can blacklist specific types of transport, the bot would then skip them while selecting a connection. You can get the type in your console (mode)
```sh ```sh
22:44:47: INFO: Agency: GVB, mode: TRAM 22:44:47: INFO: Agency: GVB, mode: TRAM
``` ```
or in the `/info` embed.
I highly recommend keeping `"OTHER"` blacklisted, if the API doesn't know what that is then we probably shouldn't use it. Also, it would probably a good idea to keep `"RIDE_SHARING"` blacklisted as they have weird timetables I highly recommend keeping `"OTHER"` blacklisted, if the API doesn't know what that is then we probably shouldn't use it. Also, it would probably a good idea to keep `"RIDE_SHARING"` blacklisted as they have weird timetables
@@ -156,6 +179,12 @@ To reduce spam, the bot will only send announcements if someone is in the voice
The bot can join the voice chat, play an audio file, and disconnect from the voice chat, at various points of your trip. You have to have [FFmpeg](https://www.ffmpeg.org/) installed for this to work. The bot can join the voice chat, play an audio file, and disconnect from the voice chat, at various points of your trip. You have to have [FFmpeg](https://www.ffmpeg.org/) installed for this to work.
Place the audio file of your desired station in [src/data/announcements](src/data/announcements/) with the EXACT name of the station. The bot will automatically check if an audio file with the stations name exists, and if it does, play it. Place the audio file of your desired station in [src/data/announcements](src/data/announcements/) with the EXACT name of the station. The bot will automatically check if an audio file with the stations name exists, and if it does, play it.
You don't have to restart the bot after placing new audio files in the folder.
#### `map:`
The bot can generate a map of your route in the `/info` embed. Set `map` to `true` to enable.
#### http #### http
- `"user_agent"`: The user agent of the bot for the API. If you don't know what that is, then you shouldn't have to change that. Modify the contact URL (in my case, the github repo) if you change a lot of the code, so that transitous can contact you in case of any issues - `"user_agent"`: The user agent of the bot for the API. If you don't know what that is, then you shouldn't have to change that. Modify the contact URL (in my case, the github repo) if you change a lot of the code, so that transitous can contact you in case of any issues
@@ -164,7 +193,7 @@ Place the audio file of your desired station in [src/data/announcements](src/dat
After you've set everything up, you're ready to start the bot! After you've set everything up, you're ready to start the bot!
```sh ```sh
$ python run main.py $ python main.py
``` ```
## src/data ## src/data
+5 -3
View File
@@ -1,8 +1,8 @@
{ {
"discord": { "discord": {
"token": "", "token": "",
"server": , "server": "",
"vc": , "vc": "",
"lang": "de", "lang": "de",
"formatting": "┇", "formatting": "┇",
"emojis": true "emojis": true
@@ -14,6 +14,7 @@
"Helsinki" "Helsinki"
], ],
"IDs": [], "IDs": [],
"priority": {},
"blacklist": [ "blacklist": [
"OTHER", "OTHER",
"RIDE_SHARING" "RIDE_SHARING"
@@ -25,7 +26,8 @@
}, },
"announcements": { "announcements": {
"text_announcements": true, "text_announcements": true,
"voice_announcements": false "voice_announcements": false,
"map": true
}, },
"http": { "http": {
"user_agent": "Gleiswechsel-Discord-Bot/1.0 (https://github.com/kaaninchen/Gleiswechsel)" "user_agent": "Gleiswechsel-Discord-Bot/1.0 (https://github.com/kaaninchen/Gleiswechsel)"
+27 -39
View File
@@ -142,10 +142,12 @@ def get_random_stop_id() -> str | None:
return None return None
stop_ids_list = list(stop_ids.keys()) stop_ids_list = list(stop_ids.keys())
chosen_stop_id = random.choice(stop_ids_list)
if len(stop_ids_list) > 1: if len(stop_ids_list) > 1:
logger(f"No station associated as '{assigned_station}', choosing random from similar named stations") logger(f"No station associated as '{assigned_station}', choosing random from similar named stations")
logger(f"Run `python run main.py stations` to get exact station names") logger(f"Run `python run main.py stations` to get exact station names")
chosen_stop_id, chosen_station = random.choice(list(stop_ids.items())) logger(f"Selected station: {stop_ids[chosen_stop_id]}")
return chosen_stop_id return chosen_stop_id
def get_random_connection(stop_id: str) -> str | None: def get_random_connection(stop_id: str) -> str | None:
@@ -153,20 +155,7 @@ def get_random_connection(stop_id: str) -> str | None:
return None return None
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
cursor = None params = {"stopId": stop_id, "n": 50, "time": now}
max_pages = 5
min_results = 5
trip_ids = []
all_stop_times = []
for _ in range(max_pages):
params = {
"stopId": stop_id,
"n": 20,
"time": now,
}
if cursor:
params["pageCursor"] = cursor
try: try:
response = requests.get(f"{endpoint}/api/v5/stoptimes", params=params, headers=headers) response = requests.get(f"{endpoint}/api/v5/stoptimes", params=params, headers=headers)
@@ -174,39 +163,38 @@ def get_random_connection(stop_id: str) -> str | None:
data = response.json() data = response.json()
except requests.RequestException as e: except requests.RequestException as e:
logger(e, "Error") logger(e, "Error")
break return None
stop_times = data.get("stopTimes", []) candidates = []
all_stop_times.extend(stop_times) for entry in data.get("stopTimes", []):
for entry in stop_times:
trip_id = entry["tripId"]
if entry["mode"] in blacklist: if entry["mode"] in blacklist:
continue continue
else: candidates.append(entry)
trip_ids.append(entry["tripId"])
if len(trip_ids) >= min_results: if not candidates:
break
cursor = data.get("nextPageCursor")
if not cursor:
break
if not trip_ids:
logger("Couldn't find any connections", "error") logger("Couldn't find any connections", "error")
return None return None
trip_id = random.choice(trip_ids)
from_station = None if config.connections.priority:
for entry in all_stop_times: best_priority = None
if entry.get("tripId") == trip_id: for entry in candidates:
from_station = entry.get("place", {}).get("name") priority = config.connections.priority.get(entry["mode"], 99)
break if best_priority is None or priority < best_priority:
best_priority = priority
best_candidates = []
for entry in candidates:
priority = config.connections.priority.get(entry["mode"], 99)
if priority == best_priority:
best_candidates.append(entry)
chosen = random.choice(best_candidates)
else:
chosen = random.choice(candidates)
return { return {
"trip_id": trip_id, "trip_id": chosen["tripId"],
"from_station": from_station "from_station": chosen.get("place", {}).get("name"),
} }
def get_trip_details(random_connection: dict | None) -> dict | None: def get_trip_details(random_connection: dict | None) -> dict | None:
+3 -1
View File
@@ -1,5 +1,5 @@
import json import json
from dataclasses import dataclass, field from dataclasses import dataclass
from typing import Optional from typing import Optional
@dataclass @dataclass
@@ -15,6 +15,7 @@ class DiscordConfig:
class ConnectionsConfig: class ConnectionsConfig:
stations: list[str] stations: list[str]
IDs: list[str] IDs: list[str]
priority: dict
blacklist: list[str] blacklist: list[str]
min_duration: int min_duration: int
timezone: str timezone: str
@@ -25,6 +26,7 @@ class ConnectionsConfig:
class AnnouncementConfig: class AnnouncementConfig:
text_announcements: bool text_announcements: bool
voice_announcements: bool voice_announcements: bool
map: bool
@dataclass @dataclass
class HttpConfig: class HttpConfig:
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

@@ -1,2 +0,0 @@
SPDX-FileCopyrightText: 2024 Mathis Brüchert <[email protected]>
SPDX-License-Identifier: CC-BY-SA-4.0
-2
View File
@@ -4,8 +4,6 @@ channel:
train_via: "{train_name} nach {goes_to} über {from_station}" train_via: "{train_name} nach {goes_to} über {from_station}"
short_name: "{train_name} nach {goes_to}" short_name: "{train_name} nach {goes_to}"
embeds: embeds:
footer:
notice: "https://transitous.org/sources/ • Maps (C) CARTO (C) OpenStreetMap.org contributors"
info: info:
description: "Abfahrt von {station} um {departure}. Ankunft um {arrival}" description: "Abfahrt von {station} um {departure}. Ankunft um {arrival}"
via: "Über" via: "Über"
-2
View File
@@ -4,8 +4,6 @@ channel:
train_via: "{train_name} to {goes_to} via {from_station}" train_via: "{train_name} to {goes_to} via {from_station}"
short_name: "{train_name} to {goes_to}" short_name: "{train_name} to {goes_to}"
embeds: embeds:
footer:
notice: "Data provided by https://transitous.org/sources/ • Maps (C) CARTO (C) OpenStreetMap.org contributors"
info: info:
description: "Departure from {station} at {departure}. Arrival by {arrival}" description: "Departure from {station} at {departure}. Arrival by {arrival}"
via: "via" via: "via"
+4 -2
View File
@@ -74,7 +74,7 @@ OPERATORS = {
"NS": { "NS": {
"logo": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/Logo_NS.svg/960px-Logo_NS.svg.png", "logo": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/Logo_NS.svg/960px-Logo_NS.svg.png",
"color": 0x00337F, "color": 0x00337F,
"slogan": ["Goed op weg", "Welkom in de trein van morgen", "Veilig, Vlug, Voordelig", "we haben een serious probleem", "Neuken in de keuken"] "slogan": ["Goed op weg", "Welkom in de trein van morgen", "Veilig, Vlug, Voordelig", "we hebben een serieus probleem", "Neuken in de keuken"]
}, },
"Ostdeutsche Eisenbahn GmbH": { "Ostdeutsche Eisenbahn GmbH": {
"logo": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/ODEG-Logo_Neu.svg/960px-ODEG-Logo_Neu.svg.png", "logo": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/ODEG-Logo_Neu.svg/960px-ODEG-Logo_Neu.svg.png",
@@ -165,6 +165,7 @@ OPERATOR_ALIASES = {
"Bayerische Regiobahn": OPERATORS["db_bayern"], "Bayerische Regiobahn": OPERATORS["db_bayern"],
"DB Regio AG Bayern": OPERATORS["db_bayern"], "DB Regio AG Bayern": OPERATORS["db_bayern"],
"DB Fernverkehr AG": OPERATORS["db_allgemein"], "DB Fernverkehr AG": OPERATORS["db_allgemein"],
"DB Regio AG": OPERATORS["db_allgemein"],
"DB Regio AG NRW": OPERATORS["db_allgemein"], "DB Regio AG NRW": OPERATORS["db_allgemein"],
"DB Regio AG Südost": OPERATORS["db_allgemein"], "DB Regio AG Südost": OPERATORS["db_allgemein"],
"DB Regio AG Nordost": OPERATORS["db_allgemein"], "DB Regio AG Nordost": OPERATORS["db_allgemein"],
@@ -177,7 +178,8 @@ OPERATOR_ALIASES = {
"VR": OPERATORS["Vr"], "VR": OPERATORS["Vr"],
"FlixBus-gb": OPERATORS["Flixbus"], "FlixBus-gb": OPERATORS["Flixbus"],
"FlixBus-eu": OPERATORS["Flixbus"], "FlixBus-eu": OPERATORS["Flixbus"],
"S-Bahn Berlin GmbH": OPERATORS["S-Bahn"] "S-Bahn Berlin GmbH": OPERATORS["S-Bahn"],
"DB Regio AG S-Bahn München": OPERATORS["S-Bahn"]
} }
+7 -5
View File
@@ -4,12 +4,13 @@ import random
from src.utils import get_operator_metadata, get_next_station, format_via_list, format_stop_list from src.utils import get_operator_metadata, get_next_station, format_via_list, format_stop_list
from src.dc.helpers import format_timestamp_to_dc from src.dc.helpers import format_timestamp_to_dc
from src.lang.locales import lang from src.lang.locales import lang
from src.config import config
lang_embed = lang.embeds lang_embed = lang.embeds
def build_embed_footer(mode: str, slogans): def build_embed_footer(slogans):
footer_notice = f"{lang.embeds.footer.notice()} • mode: {mode}" footer_notice = f"https://transitous.org/sources/"
icon = "https://raw.githubusercontent.com/kaaninchen/Gleiswechsel/refs/heads/main/src/data/assets/transitous-logo.png" icon = "https://api.transitous.org/favicon.png"
if slogans is not None: if slogans is not None:
footer_text = f"{random.choice(slogans)}{footer_notice}" footer_text = f"{random.choice(slogans)}{footer_notice}"
@@ -55,12 +56,13 @@ def build_info_embed() -> discord.Embed:
for field_name, field_value in route_fields: for field_name, field_value in route_fields:
embed.add_field(name=field_name, value=field_value, inline=False) embed.add_field(name=field_name, value=field_value, inline=False)
footer = build_embed_footer(trip["mode"], metadata["slogans"]) footer = build_embed_footer(metadata["slogans"])
embed.set_footer(text=footer["text"], icon_url=footer["icon"]) embed.set_footer(text=footer["text"], icon_url=footer["icon"])
embed.set_author(name=agency) embed.set_author(name=agency)
embed.set_thumbnail(url=metadata["logo"]) embed.set_thumbnail(url=metadata["logo"])
if config.announcements.map:
embed.set_image(url="attachment://ride.png") embed.set_image(url="attachment://ride.png")
return embed return embed
@@ -78,7 +80,7 @@ def build_announcement_embed(msg):
embed.set_author(name=agency) embed.set_author(name=agency)
embed.set_thumbnail(url=metadata["logo"]) embed.set_thumbnail(url=metadata["logo"])
footer = build_embed_footer(trip["mode"], metadata.get("slogan")) footer = build_embed_footer(metadata.get("slogan"))
embed.set_footer(text=footer["text"], icon_url=footer["icon"]) embed.set_footer(text=footer["text"], icon_url=footer["icon"])
return embed return embed
+3 -2
View File
@@ -18,7 +18,7 @@ async def rename_vc(bot: discord.Bot, voice_channel, from_scheduler: bool = Fals
_scheduled_task.cancel() _scheduled_task.cancel()
attempt = 0 attempt = 0
max_attempt = 15 max_attempt = 30
trip = choose_connection() trip = choose_connection()
while trip is None and attempt < max_attempt: while trip is None and attempt < max_attempt:
attempt += 1 attempt += 1
@@ -28,6 +28,7 @@ async def rename_vc(bot: discord.Bot, voice_channel, from_scheduler: bool = Fals
logger(f"Failed to select route after {max_attempt} attempts", "fatal") logger(f"Failed to select route after {max_attempt} attempts", "fatal")
return False return False
if config.announcements.map:
generate_static_map(trip["stops"], trip["mode"], trip["agency"], trip["route_color"]) generate_static_map(trip["stops"], trip["mode"], trip["agency"], trip["route_color"])
arrival = trip["arrival"] arrival = trip["arrival"]
@@ -70,7 +71,7 @@ async def announcer(announcement: str, voice_channel: discord.VoiceChannel, dest
embed = None embed = None
if embed: if embed:
if image: if image and config.announcements.map:
await voice_channel.send(file=image, embed=embed) await voice_channel.send(file=image, embed=embed)
else: else:
await voice_channel.send(embed=embed) await voice_channel.send(embed=embed)
+1 -7
View File
@@ -1,6 +1,6 @@
# generated by datamodel-codegen: # generated by datamodel-codegen:
# filename: en.yaml # filename: en.yaml
# timestamp: 2026-08-20T10:40:43+00:00 # timestamp: 2026-08-23T14:08:25+00:00
from __future__ import annotations from __future__ import annotations
@@ -19,11 +19,6 @@ class Channel:
short_name: str short_name: str
@dataclass
class Footer:
notice: str
@dataclass @dataclass
class Info: class Info:
description: str description: str
@@ -45,7 +40,6 @@ class Announcement:
@dataclass @dataclass
class Embeds: class Embeds:
footer: Footer
info: Info info: Info
announcement: Announcement announcement: Announcement
+2 -49
View File
@@ -217,22 +217,7 @@ def generate_static_map(stops: dict, mode: str, operator: str, route_color: str)
context = staticmaps.Context() context = staticmaps.Context()
context.set_tile_provider( context.set_tile_provider(staticmaps.tile_provider_OSM)
staticmaps.TileProvider(
"carto-voyager",
url_pattern=(
"https://$s.basemaps.cartocdn.com/"
"rastertiles/voyager/$z/$x/$y.png"
),
shards=["a", "b", "c", "d"],
attribution="",
)
# It is against the law (and against your morals...) to not give
# OSM and carto credits for their great work
# I only removed the attribution text because I really dislike the
# ugly white box that py-staticmaps adds. Credits are still visible in the
# embeds footer
)
stop_coords = [ stop_coords = [
staticmaps.create_latlng( staticmaps.create_latlng(
@@ -246,7 +231,7 @@ def generate_static_map(stops: dict, mode: str, operator: str, route_color: str)
staticmaps.Line( staticmaps.Line(
stop_coords, stop_coords,
color=white, color=white,
width=20, width=15,
) )
) )
@@ -279,38 +264,6 @@ def generate_static_map(stops: dict, mode: str, operator: str, route_color: str)
size=12 size=12
) )
) )
lats = [c.lat().degrees for c in stop_coords]
lons = [c.lng().degrees for c in stop_coords]
lat_span = max(lats) - min(lats)
lon_span = max(lons) - min(lons)
MIN_SPAN = 0.01
if lat_span < MIN_SPAN or lon_span < MIN_SPAN:
center_lat = (max(lats) + min(lats)) / 2
center_lon = (max(lons) + min(lons)) / 2
pad = MIN_SPAN / 2
context.add_object(
staticmaps.Circle(
staticmaps.create_latlng(center_lat + pad, center_lon + pad),
radius_km=0.01,
fill_color=staticmaps.TRANSPARENT,
color=staticmaps.TRANSPARENT,
width=0,
)
)
context.add_object(
staticmaps.Circle(
staticmaps.create_latlng(center_lat - pad, center_lon - pad),
radius_km=0.01,
fill_color=staticmaps.TRANSPARENT,
color=staticmaps.TRANSPARENT,
width=0,
)
)
try: try:
image = context.render_cairo(400, 300) image = context.render_cairo(400, 300)
image.write_to_png("src/data/assets/current_map.png") image.write_to_png("src/data/assets/current_map.png")