6 Commits

Author SHA1 Message Date
6659079d7a Clean up type hints everywhere, overhaul bot configuration
Some checks failed
Build Heidi Docker image / build-docker (push) Failing after 28s
2025-09-23 20:39:11 +02:00
591f4ea191 Add line-length configuration 2025-09-23 20:37:38 +02:00
f167b23dcc Update development dependencies 2025-09-23 20:37:27 +02:00
d319fa21f5 Update python interpreter version in dockerfile 2025-09-23 20:37:17 +02:00
44a1ea2c83 Add sounds 2025-09-23 20:34:28 +02:00
d04244221b Replace ENTRANCE.SOUND menu with dropdowns
All checks were successful
Build Heidi Docker image / build-docker (push) Successful in 14s
2023-12-09 23:01:24 +01:00
60 changed files with 571 additions and 261 deletions

View File

@ -1,10 +1,10 @@
# syntax=docker/dockerfile:1 FROM python:3.13.7-slim-buster
RUN apt-get update -y && apt-get install -y ffmpeg libopus0
FROM python:3.10.1-slim-buster
RUN apt-get update -y
RUN apt-get install -y ffmpeg libopus0
WORKDIR /app WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . . COPY . .
RUN pip3 install -r requirements.txt
CMD ["python3", "-u", "bot.py"] CMD ["python3", "-u", "bot.py"]

339
bot.py
View File

@ -1,26 +1,35 @@
# Example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py # Example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
import random, logging import os
import random
import logging
from types import CoroutineType
from typing import Any, Callable, override
from discord import app_commands, ui
from discord.app_commands import Choice from discord.app_commands import Choice
from typing import Dict, List, Optional, Union, Callable, Any
from rich.traceback import install
from heidi_client import * from discord.client import Client
from discord.components import SelectOption
from discord.enums import ButtonStyle
from discord.flags import Intents
from discord.interactions import Interaction
from discord.member import Member, VoiceState
from discord.message import Message
# Install rich traceback from heidi_client import HeidiClient
install(show_locals=True) from heidi_config import ConfigSection, FlagsConfigKey
from heidi_constants import DOCKER, HEIDI_SPAM_ID, SOUNDDIR
from heidi_helpers import enforce_channel, play_voice_line_for_member
# @todo Only post in heidi-spam channel # TODO: yt-dlp music support
# @todo yt-dlp music support
# @todo Somehow upload voicelines more easily (from discord voice message?)
# Log to file # Log to file
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w") handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
# Intents specification is no longer optional # Intents specification is no longer optional
intents = discord.Intents.default() intents: Intents = Intents.default()
intents.members = True # Allow to react to member join/leave etc intents.members = True # Allow to react to member join/leave etc
intents.message_content = True # Allow to read message content from arbitrary messages intents.message_content = True # Allow to read message content from arbitrary messages
intents.voice_states = True # Allow to process on_voice_state_update intents.voice_states = True # Allow to process on_voice_state_update
@ -63,9 +72,7 @@ async def on_message(message: Message) -> None:
@client.event @client.event
async def on_voice_state_update( async def on_voice_state_update(member: Member, before: VoiceState, after: VoiceState) -> None:
member: Member, before: VoiceState, after: VoiceState
) -> None:
""" """
This event triggers when a member joins/changes/leaves a voice channel or mutes/unmutes. This event triggers when a member joins/changes/leaves a voice channel or mutes/unmutes.
""" """
@ -77,7 +84,9 @@ async def on_voice_state_update(
# python iterates over the keys of a map # python iterates over the keys of a map
for predicate in client.on_voice_state_triggers: for predicate in client.on_voice_state_triggers:
if predicate(member, before, after): if predicate(member, before, after):
action: Callable = client.on_voice_state_triggers[predicate] action: Callable[[Member, VoiceState, VoiceState], CoroutineType[Any, Any, None]] = (
client.on_voice_state_triggers[predicate]
)
print(f"on_voice_state_update: calling {action.__name__}") print(f"on_voice_state_update: calling {action.__name__}")
await action(member, before, after) await action(member, before, after)
@ -85,91 +94,195 @@ async def on_voice_state_update(
# Config Commands -------------------------------------------------------------------------------- # Config Commands --------------------------------------------------------------------------------
async def user_config_key_autocomplete( class FlagValueSelect(ui.Select[ui.View]):
interaction: Interaction, current: str def __init__(
) -> List[Choice[str]]: self, flag: str, on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
self.flag: str = flag
self.on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]] = (
on_flag_select_callback
)
options: list[SelectOption] = [SelectOption(label=val, value=val) for val in ["True", "False"]]
super().__init__(placeholder="Select Value", min_values=1, max_values=1, options=options)
@override
async def callback(self, interaction: Interaction) -> None:
await self.on_flag_select_callback(interaction, self.flag, self.values[0])
class FlagValueView(ui.View):
def __init__(
self, flag: str, on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
super().__init__(timeout=600)
_ = self.add_item(FlagValueSelect(flag, on_flag_select_callback))
class FlagsSelect(ui.Select[ui.View]):
def __init__(
self, on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
self.on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]] = (
on_flag_select_callback
)
options: list[SelectOption] = [SelectOption(label=flag.value, value=flag.value) for flag in FlagsConfigKey]
super().__init__(placeholder="Select Flag", min_values=1, max_values=1, options=options)
@override
async def callback(self, interaction: Interaction) -> None:
_ = await interaction.response.send_message(
"Welchen Wert willst du setzen?",
view=FlagValueView(self.values[0], self.on_flag_select_callback),
ephemeral=True,
)
class FlagsView(ui.View):
def __init__(
self, on_flag_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
super().__init__(timeout=600)
_ = self.add_item(FlagsSelect(on_flag_select_callback))
class EntranceSoundBoardSelect(ui.Select[ui.View]):
def __init__(
self, on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
self.on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]] = (
on_sound_select_callback
)
options: list[SelectOption] = [SelectOption(label=board, value=board) for board in os.listdir(f"{SOUNDDIR}")]
super().__init__(placeholder="Select Board", min_values=1, max_values=1, options=options)
@override
async def callback(self, interaction: Interaction) -> None:
_ = await interaction.response.send_message(
"Welchen sound willst du?",
view=EntranceSoundSoundView(self.values[0], self.on_sound_select_callback),
ephemeral=True,
)
class EntranceSoundBoardView(ui.View):
def __init__(
self, on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
super().__init__(timeout=600)
_ = self.add_item(EntranceSoundBoardSelect(on_sound_select_callback))
class EntranceSoundSoundSelect(ui.Select[ui.View]):
def __init__(
self, board: str, on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
self.board: str = board
self.on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]] = (
on_sound_select_callback
)
options: list[SelectOption] = [
SelectOption(label=sound.split(".")[0], value=sound) for sound in os.listdir(f"{SOUNDDIR}/{board}")
]
super().__init__(placeholder="Select Sound", min_values=1, max_values=1, options=options)
@override
async def callback(self, interaction: Interaction) -> None:
await self.on_sound_select_callback(interaction, self.board, self.values[0])
class EntranceSoundSoundView(ui.View):
def __init__(
self, board: str, on_sound_select_callback: Callable[[Interaction, str, str], CoroutineType[Any, Any, None]]
) -> None:
super().__init__(timeout=600)
_ = self.add_item(EntranceSoundSoundSelect(board, on_sound_select_callback))
async def user_config_key_autocomplete(interaction: Interaction, current: str) -> list[Choice[str]]:
""" """
Suggest a value from the user config keys (each .conf section is a key). Suggest a value from the user config keys (each .conf section is a key).
""" """
return [ return [
Choice(name=key, value=key) Choice(name=key, value=key) for key in client.user_config.sections() if key.lower().startswith(current.lower())
for key in client.user_config.sections()
if key.lower().startswith(current.lower())
] ]
async def user_config_value_autocomplete(
interaction: Interaction, current: str
) -> List[Choice[str]]:
"""
Calls an autocomplete function depending on the entered config_key.
"""
autocompleters = {"ENTRANCE.SOUND": user_entrance_sound_autocomplete}
autocompleter = autocompleters[interaction.namespace.option]
print(f"config_value_autocomplete: calling {autocompleter.__name__}")
return autocompleter(interaction, current)
def user_entrance_sound_autocomplete(
interaction: Interaction, current: str
) -> List[Choice[str]]:
"""
Generates autocomplete options for the ENTRANCE.SOUND config key.
"""
boards: List[str] = os.listdir(SOUNDDIR)
all_sounds: Dict[str, List[str]] = {
board: os.listdir(f"{SOUNDDIR}/{board}/") for board in boards
} # These are all sounds, organized per board
# @todo Initially only suggest boards, because there are too many sounds to show them all
completions: List[Choice[str]] = []
for (
board,
board_sounds,
) in all_sounds.items(): # Iterate over all sounds, organized per board
for sound in board_sounds: # Iterate over board specific sounds
soundpath = f"{board}/{sound}"
if soundpath.lower().startswith(current.lower()):
completions += [Choice(name=soundpath.split(".")[0], value=soundpath)]
return completions
@client.tree.command( @client.tree.command(
name="userconfig", name="heidiconfig",
description="User-spezifische Heidi-Einstellungen (Heidi merkt sie sich in ihrem riesigen Gehirn).", description="User-spezifische Heidi-Einstellungen (Heidi merkt sie sich in ihrem riesigen Gehirn).",
) )
@app_commands.rename(config_key="option") @app_commands.rename(config_key="option")
@app_commands.describe(config_key="Die Option, welche du ändern willst.") @app_commands.describe(config_key="Die Option, welche du ändern willst.")
@app_commands.autocomplete(config_key=user_config_key_autocomplete) @app_commands.autocomplete(config_key=user_config_key_autocomplete)
@app_commands.rename(config_value="wert")
@app_commands.describe(
config_value="Der Wert, auf welche die Option gesetzt werden soll."
)
@app_commands.autocomplete(config_value=user_config_value_autocomplete)
@enforce_channel(HEIDI_SPAM_ID) @enforce_channel(HEIDI_SPAM_ID)
async def user_config( async def user_config(interaction: Interaction[Client], config_key: str) -> None:
interaction: Interaction, config_key: str, config_value: str
) -> None:
""" """
Set a user config value for the calling user. Set a user config value for the calling user.
""" """
# Only Members can set settings # Only Members can set settings
if not isinstance(interaction.user, Member): if not isinstance(interaction.user, Member):
print("User not a member") print("User not a member")
await interaction.response.send_message("Heidi sagt: Komm in die Gruppe!", ephemeral=True) _ = await interaction.response.send_message("Heidi sagt: Komm in die Gruppe!", ephemeral=True)
return return
member: Member = interaction.user member: Member = interaction.user
client.user_config[config_key][member.name] = config_value async def on_flag_select_callback(interaction: Interaction, flag: str, value: str) -> None:
"""
This function is called when an FlagValueSelect option is selected.
"""
client.user_config[ConfigSection.FLAGS.value][flag] = value
client.write_user_config() client.write_user_config()
await interaction.response.send_message( _ = await interaction.response.send_message(
f"Ok, ich schreibe {member.name}={config_value} in mein fettes Gehirn!", f"Ok, ich schreibe {flag}={value} in mein fettes Gehirn!",
ephemeral=True ephemeral=True,
)
async def on_sound_select_callback(interaction: Interaction, board: str, sound: str) -> None:
"""
This function is called when an EntrySoundSoundSelect option is selected.
"""
client.user_config[config_key][member.name] = f"{board}/{sound}"
client.write_user_config()
_ = await interaction.response.send_message(
f"Ok, ich schreibe {member.name}={board}/{sound} in mein fettes Gehirn!",
ephemeral=True,
)
# Views for different user config options are defined here
views: dict[str, tuple[type[ui.View], Callable[..., CoroutineType[Any, Any, None]], str]] = {
ConfigSection.FLAGS.value: (
FlagsView,
on_flag_select_callback,
"Welches Setting möchtest du ändern?",
),
ConfigSection.ENTRANCE_SOUND.value: (
EntranceSoundBoardView,
on_sound_select_callback,
"Aus welchem Soundboard soll dein Sound sein?",
),
}
view, select_callback, description = views[config_key]
_ = await interaction.response.send_message(
description,
view=view(select_callback), # pyright: ignore[reportCallIssue]
ephemeral=True,
) )
@ -195,7 +308,8 @@ async def heidi_exclaim(interaction: Interaction) -> None:
"Models müssen da halt durch!", "Models müssen da halt durch!",
"Heul doch nicht!", "Heul doch nicht!",
] ]
await interaction.response.send_message(random.choice(messages))
_ = await interaction.response.send_message(random.choice(messages))
@client.tree.command(name="miesmuschel", description="Was denkt Heidi?") @client.tree.command(name="miesmuschel", description="Was denkt Heidi?")
@ -223,14 +337,13 @@ async def magic_shell(interaction: Interaction, question: str) -> None:
"In deinen Träumen.", "In deinen Träumen.",
"Tom sagt Nein", "Tom sagt Nein",
] ]
question = question.strip() question = question.strip()
question_mark = "" if question[-1] == "?" else "?" question_mark = "" if question[-1] == "?" else "?"
await interaction.response.send_message( _ = await interaction.response.send_message(f"{question}{question_mark}\nHeidi sagt: {random.choice(choices)}")
f"{question}{question_mark}\nHeidi sagt: {random.choice(choices)}"
)
# @todo Allow , separated varargs, need to parse manually as slash commands don't support varargs # TODO: Allow separated varargs, need to parse manually as slash commands don't support varargs
@client.tree.command(name="wähle", description="Heidi trifft die Wahl!") @client.tree.command(name="wähle", description="Heidi trifft die Wahl!")
@app_commands.rename(option_a="entweder") @app_commands.rename(option_a="entweder")
@app_commands.describe(option_a="Ist es vielleicht dies?") @app_commands.describe(option_a="Ist es vielleicht dies?")
@ -242,7 +355,7 @@ async def choose(interaction: Interaction, option_a: str, option_b: str) -> None
Select an answer from two options. Select an answer from two options.
""" """
options = [option_a.strip(), option_b.strip()] options = [option_a.strip(), option_b.strip()]
await interaction.response.send_message( _ = await interaction.response.send_message(
f"{options[0]} oder {options[1]}?\nHeidi sagt: {random.choice(options)}" f"{options[0]} oder {options[1]}?\nHeidi sagt: {random.choice(options)}"
) )
@ -250,40 +363,28 @@ async def choose(interaction: Interaction, option_a: str, option_b: str) -> None
# Sounds ----------------------------------------------------------------------------------------- # Sounds -----------------------------------------------------------------------------------------
async def board_autocomplete( async def board_autocomplete(interaction: Interaction, current: str) -> list[Choice[str]]:
interaction: Interaction, current: str
) -> List[Choice[str]]:
""" """
Suggest a sound board. Suggest a sound board.
""" """
boards: List[str] = os.listdir(SOUNDDIR) boards: list[str] = os.listdir(SOUNDDIR)
return [ return [Choice(name=board, value=board) for board in boards if board.lower().startswith(current.lower())]
Choice(name=board, value=board)
for board in boards
if board.lower().startswith(current.lower())
]
async def sound_autocomplete( async def sound_autocomplete(interaction: Interaction, current: str) -> list[Choice[str]]:
interaction: Interaction, current: str
) -> List[Choice[str]]:
""" """
Suggest a sound from an already selected board. Suggest a sound from an already selected board.
""" """
board: str = interaction.namespace.board board: str = interaction.namespace.board
sounds: List[str] = os.listdir(f"{SOUNDDIR}/{board}/") sounds: list[str] = os.listdir(f"{SOUNDDIR}/{board}/")
return [ return [
Choice(name=sound.split(".")[0], value=sound) Choice(name=sound.split(".")[0], value=sound) for sound in sounds if sound.lower().startswith(current.lower())
for sound in sounds
if sound.lower().startswith(current.lower())
] ]
@client.tree.command( @client.tree.command(name="sag", description="Heidi drückt den Knopf auf dem Soundboard.")
name="sag", description="Heidi drückt den Knopf auf dem Soundboard."
)
@app_commands.describe(sound="Was soll Heidi sagen?") @app_commands.describe(sound="Was soll Heidi sagen?")
@app_commands.autocomplete(board=board_autocomplete) @app_commands.autocomplete(board=board_autocomplete)
@app_commands.autocomplete(sound=sound_autocomplete) @app_commands.autocomplete(sound=sound_autocomplete)
@ -295,7 +396,7 @@ async def say_voiceline(interaction: Interaction, board: str, sound: str) -> Non
# Only Members can access voice channels # Only Members can access voice channels
if not isinstance(interaction.user, Member): if not isinstance(interaction.user, Member):
print("User not a member") print("User not a member")
await interaction.response.send_message("Heidi sagt: Komm in die Gruppe!", ephemeral=True) _ = await interaction.response.send_message("Heidi sagt: Komm in die Gruppe!", ephemeral=True)
return return
member: Member = interaction.user member: Member = interaction.user
@ -303,41 +404,42 @@ async def say_voiceline(interaction: Interaction, board: str, sound: str) -> Non
await play_voice_line_for_member(interaction, member, board, sound) await play_voice_line_for_member(interaction, member, board, sound)
class InstantButton(discord.ui.Button): class InstantButton(ui.Button[ui.View]):
def __init__(self, label: str, board: str, sound: str): def __init__(self, label: str, board: str, sound: str) -> None:
super().__init__(style=discord.ButtonStyle.red, label=label) super().__init__(style=ButtonStyle.red, label=label)
self.board = board self.board: str = board
self.sound = sound self.sound: str = sound
async def callback(self, interaction: Interaction): @override
async def callback(self, interaction: Interaction) -> None:
""" """
Handle a press of the button. Handle a press of the button.
""" """
if not isinstance(interaction.user, Member): if not isinstance(interaction.user, Member):
await interaction.response.send_message("Heidi mag keine discord.User, nur discord.Member!", ephemeral=True) _ = await interaction.response.send_message(
"Heidi mag keine discord.User, nur discord.Member!", ephemeral=True
)
return return
await play_voice_line_for_member(interaction, interaction.user, self.board, self.sound) await play_voice_line_for_member(interaction, interaction.user, self.board, self.sound)
class InstantButtons(discord.ui.View): class InstantButtonsView(ui.View):
def __init__(self, board: str, timeout=None): def __init__(self, board: str, timeout: float | None = None) -> None:
super().__init__(timeout=timeout) super().__init__(timeout=timeout)
sounds = os.listdir(f"{SOUNDDIR}/{board}") sounds = os.listdir(f"{SOUNDDIR}/{board}")
for sound in sounds: for sound in sounds:
self.add_item(InstantButton(sound.split(".")[0], board, sound)) _ = self.add_item(InstantButton(sound.split(".")[0], board, sound))
@client.tree.command( @client.tree.command(name="instantbuttons", description="Heidi malt Knöpfe für Sounds in den Chat.")
name="instantbuttons", description="Heidi malt Knöpfe für Sounds in den Chat."
)
@app_commands.describe(board="Welches Soundboard soll knöpfe bekommen?") @app_commands.describe(board="Welches Soundboard soll knöpfe bekommen?")
@app_commands.autocomplete(board=board_autocomplete) @app_commands.autocomplete(board=board_autocomplete)
@enforce_channel(HEIDI_SPAM_ID) @enforce_channel(HEIDI_SPAM_ID)
async def soundboard_buttons(interaction: Interaction, board: str) -> None: async def soundboard_buttons(interaction: Interaction, board: str) -> None:
await interaction.response.send_message(f"Soundboard: {board.capitalize()}", view=InstantButtons(board)) _ = await interaction.response.send_message(f"Soundboard: {board.capitalize()}", view=InstantButtonsView(board))
# Contextmenu ------------------------------------------------------------------------------------ # Contextmenu ------------------------------------------------------------------------------------
@ -352,11 +454,11 @@ async def insult(
Send an insult to a member via direct message. Send an insult to a member via direct message.
""" """
if not member.dm_channel: if not member.dm_channel:
await member.create_dm() _ = await member.create_dm()
if not member.dm_channel: if not member.dm_channel:
print("Error creating DMChannel!") print("Error creating DMChannel!")
await interaction.response.send_message("Heidi sagt: Gib mal DM Nummer süße*r!", ephemeral=True) _ = await interaction.response.send_message("Heidi sagt: Gib mal DM Nummer süße*r!", ephemeral=True)
return return
insults = [ insults = [
@ -375,10 +477,9 @@ async def insult(
"Richtiger Gesichtsgünther ey!", "Richtiger Gesichtsgünther ey!",
] ]
await member.dm_channel.send(random.choice(insults)) _ = await member.dm_channel.send(random.choice(insults))
await interaction.response.send_message( _ = await interaction.response.send_message(
"Anzeige ist raus!", "Anzeige ist raus!", ephemeral=True
ephemeral=True
) # with ephemeral = True only the caller can see the answer ) # with ephemeral = True only the caller can see the answer

44
flake.lock generated
View File

@ -2,15 +2,14 @@
"nodes": { "nodes": {
"devshell": { "devshell": {
"inputs": { "inputs": {
"nixpkgs": "nixpkgs", "nixpkgs": "nixpkgs"
"systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1701787589, "lastModified": 1741473158,
"narHash": "sha256-ce+oQR4Zq9VOsLoh9bZT8Ip9PaMLcjjBUHVPzW5d7Cw=", "narHash": "sha256-kWNaq6wQUbUMlPgw8Y+9/9wP0F8SHkjy24/mN3UAppg=",
"owner": "numtide", "owner": "numtide",
"repo": "devshell", "repo": "devshell",
"rev": "44ddedcbcfc2d52a76b64fb6122f209881bd3e1e", "rev": "7c9e793ebe66bcba8292989a68c0419b737a22a0",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -21,14 +20,14 @@
}, },
"flake-utils": { "flake-utils": {
"inputs": { "inputs": {
"systems": "systems_2" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1701680307, "lastModified": 1731533236,
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=", "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725", "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -39,11 +38,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1677383253, "lastModified": 1722073938,
"narHash": "sha256-UfpzWfSxkfXHnb4boXZNaKsAcUrZT9Hw+tao1oZxd08=", "narHash": "sha256-OpX0StkL8vpXyWOGUD6G+MA26wAXK6SpT94kLJXo6B4=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "9952d6bc395f5841262b006fbace8dd7e143b634", "rev": "e36e9f57337d0ff0cf77aceb58af4c805472bfae",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -55,11 +54,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1701693815, "lastModified": 1758446476,
"narHash": "sha256-7BkrXykVWfkn6+c1EhFA3ko4MLi3gVG0p9G96PNnKTM=", "narHash": "sha256-5rdAi7CTvM/kSs6fHe1bREIva5W3TbImsto+dxG4mBo=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "09ec6a0881e1a36c29d67497693a67a16f4da573", "rev": "a1f79a1770d05af18111fbbe2a3ab2c42c0f6cd0",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -90,21 +89,6 @@
"repo": "default", "repo": "default",
"type": "github" "type": "github"
} }
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
} }
}, },
"root": "root", "root": "root",

View File

@ -5,41 +5,32 @@
inputs.flake-utils.url = "github:numtide/flake-utils"; inputs.flake-utils.url = "github:numtide/flake-utils";
inputs.devshell.url = "github:numtide/devshell"; inputs.devshell.url = "github:numtide/devshell";
outputs = { self, nixpkgs, flake-utils, devshell }: outputs = {
flake-utils.lib.eachDefaultSystem (system: self,
let nixpkgs,
flake-utils,
devshell,
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = import nixpkgs { pkgs = import nixpkgs {
inherit system; inherit system;
config.allowUnfree = true; config.allowUnfree = true;
overlays = [ devshell.overlays.default ]; overlays = [devshell.overlays.default];
}; };
myPython = pkgs.python311.withPackages (p: with p; [ python = pkgs.python313.withPackages (p:
# Basic with p; [
rich
# Discord
discordpy
python-dotenv python-dotenv
pynacl
# Scraping discordpy
# beautifulsoup4 pynacl # DiscordPy Voice Support
# requests
# MachineLearning
# torch-rocm
# torchvision-rocm
# numpy
# matplotlib
# nltk
]); ]);
in { in {
devShell = pkgs.devshell.mkShell { devShell = pkgs.devshell.mkShell {
name = "HeidiBot"; name = "HeidiBot";
packages = with pkgs; [ packages = with pkgs; [
myPython python
# nodePackages.pyright # LSP # nodePackages.pyright # LSP
]; ];

BIN
heidi-sounds/basic/1200 Fuß.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/basic/Yippee.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/bg3/Disgusting.mp3 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/bg3/Hahaha.mp3 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/bg3/Honk.mp3 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/bg3/Start talking.mp3 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/bg3/This group is full of weirdos.mp3 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/christus/Anna Ficken.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/christus/Ching Chang Hon.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/christus/FDP.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/christus/Learn Fucking Japanese.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Alter Ego.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Dusch dich.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Florian Reiter Pfeife Blasen.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Frikadelle als Mülla Milz.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/HALLO.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Holland.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Juten Aabnd.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/LlamaLlama.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Loddar.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Mülla Milz Muuh.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Müllküweh.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Schönn Juten Abnd.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Soko Soko Lade.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/henri/Top Fit.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/ipp/Ew Brother Ew.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/ipp/Metal Pipe.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/julian/Schweizer Porno.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/jungs/Heeheeheehee Short.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/jungs/Heeheeheehee.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/jungs/Hurensohn.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/jungs/Trichter Saufen.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/kaptn/Gänsehosen.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marc/DIGGAAAAH.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marc/Trailerpark Kokain.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marc/VoiceMail.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius/Boi.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius/I have Cancer.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Boy Kisser Central.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Feinstes Huuuuuhn.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Hakenkreuze Malen.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Kurrva Bobr.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Mist.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Schaltet ab.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Sharmuta.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/marius2/Yoda Busts Nuts.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/pantoffel/Du Sau Alder.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/thezdoc/187.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/vinz/Olaf JaJaJa.mkv (Stored with Git LFS) Normal file

Binary file not shown.

BIN
heidi-sounds/warframe/Grineer.mkv (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -1,22 +1,49 @@
import configparser import asyncio
from discord import app_commands, Message, VoiceState from configparser import ConfigParser
import os
from types import CoroutineType
from typing import Any, Callable, override
from discord import Message, VoiceState
from discord.activity import Activity
from discord.app_commands.tree import CommandTree
from discord.client import Client
from discord.enums import ActivityType, Status, StatusDisplayType
from discord.flags import Intents
from discord.member import Member
from discord.state import VoiceChannel
from heidi_constants import * from heidi_config import USER_CONFIG_SCHEME, ConfigSection, FlagsConfigKey
from heidi_helpers import * from heidi_constants import CONFIGPATH, LINUS_GUILD, TEST_GUILD, USERCONFIGNAME
from heidi_helpers import create_author_based_message_predicate, play_voice_line_for_member
class HeidiClient(discord.Client): class HeidiClient(Client):
def __init__(self, *, intents: discord.Intents): def __init__(self, *, intents: Intents):
super().__init__(status="Nur eine kann GNTM werden!", intents=intents) client_activity: Activity = Activity(
name="GNTM",
url="https://www.joyn.de/serien/germanys-next-topmodel",
type=ActivityType.competing,
state="Nur eine kann es werden!",
# details="Details",
# platform="Platform",
status_display_type=StatusDisplayType.state,
)
super().__init__(
activity=client_activity,
status=Status.online,
intents=intents,
)
# Separate object that keeps all application command state # Separate object that keeps all application command state
self.tree = app_commands.CommandTree(self) self.tree: CommandTree = CommandTree(self)
# Handle persistent user configuration # Handle persistent user configuration
self.user_config = configparser.ConfigParser() self.user_config: ConfigParser = ConfigParser()
if not os.path.exists(f"{CONFIGPATH}/{USERCONFIGNAME}"): if not os.path.exists(f"{CONFIGPATH}/{USERCONFIGNAME}"):
open(f"{CONFIGPATH}/{USERCONFIGNAME}", "x") # Create the file
self.user_config.read(f"{CONFIGPATH}/{USERCONFIGNAME}") _ = open(f"{CONFIGPATH}/{USERCONFIGNAME}", "x")
_ = self.user_config.read(f"{CONFIGPATH}/{USERCONFIGNAME}")
self.update_to_default_user_config() self.update_to_default_user_config()
self.print_user_config() self.print_user_config()
@ -24,43 +51,53 @@ class HeidiClient(discord.Client):
# on_message_triggers is a map with tuples of two functions: (predicate, action) # on_message_triggers is a map with tuples of two functions: (predicate, action)
# the predicate receives the message as argument # the predicate receives the message as argument
# if the predicate is true the action is performed # if the predicate is true the action is performed
self.on_message_triggers = { self.on_message_triggers: dict[
Callable[[Message], bool],
Callable[[Message], CoroutineType[Any, Any, None]],
] = {
# lambda m: m.author.nick.lower() in self.models.get_in_names(): self.autoreact_to_girls, # lambda m: m.author.nick.lower() in self.models.get_in_names(): self.autoreact_to_girls,
lambda m: "jeremy" in m.author.nick.lower(): self._autoreact_to_jeremy, create_author_based_message_predicate(["jeremy"]): self._autoreact_to_jeremy,
lambda m: "kardashian" in m.author.nick.lower() create_author_based_message_predicate(["kardashian", "jenner"]): self._autoreact_to_kardashian,
or "jenner" in m.author.nick.lower(): self._autoreact_to_kardashian,
} }
# automatic actions on voice state changes # automatic actions on voice state changes
# on_voice_state_triggers is a map with tuples of two functions: (predicate, action) # on_voice_state_triggers is a map with tuples of two functions: (predicate, action)
# the predicate receives the member, before- and after-state as arguments # the predicate receives the member, before- and after-state as arguments
# if the predicate is true, the action is performed # if the predicate is true, the action is performed
self.on_voice_state_triggers = { self.on_voice_state_triggers: dict[
lambda m, b, a: b.channel != a.channel Callable[[Member, VoiceState, VoiceState], bool],
and a.channel is not None Callable[[Member, VoiceState, VoiceState], CoroutineType[Any, Any, None]],
and isinstance(a.channel, VoiceChannel): self._play_entrance_sound, ] = {
lambda member, before, after: before.channel != after.channel
and after.channel is not None
and isinstance(after.channel, VoiceChannel): self._play_entrance_sound,
} }
# Synchronize commands to guilds # Synchronize commands to guilds
async def setup_hook(self): @override
async def setup_hook(self) -> None:
self.tree.copy_global_to(guild=LINUS_GUILD) self.tree.copy_global_to(guild=LINUS_GUILD)
await self.tree.sync(guild=LINUS_GUILD) _ = await self.tree.sync(guild=LINUS_GUILD)
self.tree.copy_global_to(guild=TEST_GUILD) self.tree.copy_global_to(guild=TEST_GUILD)
await self.tree.sync(guild=TEST_GUILD) _ = await self.tree.sync(guild=TEST_GUILD)
def update_to_default_user_config(self) -> None: def update_to_default_user_config(self) -> None:
""" """
Adds config keys to the config, if they don't exist yet. Adds config keys to the config, if they don't exist yet.
This writes the user config file. This writes the user config file.
""" """
user_config_sections = ["ENTRANCE.SOUND"]
for section in user_config_sections: for section, keys in USER_CONFIG_SCHEME.items():
if section not in self.user_config: if section not in self.user_config:
print(f"Adding section {section} to {CONFIGPATH}/{USERCONFIGNAME}") print(f"Adding section {section} to {CONFIGPATH}/{USERCONFIGNAME}")
self.user_config[section] = dict() self.user_config[section] = dict()
for key, default in keys:
if key not in self.user_config[section].keys():
print(f"Adding key {key} with default value {default} to section {section}")
self.user_config[section][key] = default
self.write_user_config() self.write_user_config()
def print_user_config(self) -> None: def print_user_config(self) -> None:
@ -119,9 +156,13 @@ class HeidiClient(discord.Client):
This function is set in on_voice_state_triggers and triggered by the on_voice_state_update event. This function is set in on_voice_state_triggers and triggered by the on_voice_state_update event.
""" """
disable_join_sound_if_alone: bool = self.user_config[ConfigSection.FLAGS.value][
FlagsConfigKey.DISABLE_JOIN_SOUND_IF_ALONE.value
] == str(True)
# Don't play anything when no other users are present # Don't play anything when no other users are present
if ( if (
member is not None disable_join_sound_if_alone
and member.voice is not None and member.voice is not None
and member.voice.channel is not None and member.voice.channel is not None
and len(member.voice.channel.members) <= 1 and len(member.voice.channel.members) <= 1
@ -129,9 +170,7 @@ class HeidiClient(discord.Client):
print("Not playing entrance sound, as no other members are present") print("Not playing entrance sound, as no other members are present")
return return
soundpath: Union[str, None] = self.user_config["ENTRANCE.SOUND"].get( soundpath: str | None = self.user_config["ENTRANCE.SOUND"].get(member.name, None)
member.name, None
)
if soundpath is None: if soundpath is None:
print(f"User {member.name} has not set an entrance sound") print(f"User {member.name} has not set an entrance sound")

19
heidi_config.py Normal file
View File

@ -0,0 +1,19 @@
from enum import Enum
class ConfigSection(Enum):
FLAGS = "FLAGS"
ENTRANCE_SOUND = "ENTRANCE.SOUND"
class FlagsConfigKey(Enum):
DISABLE_JOIN_SOUND_IF_ALONE = "disable_join_sound_if_alone"
# NOTE: This is the default configuration scheme
USER_CONFIG_SCHEME: dict[str, list[tuple[str, str]]] = {
ConfigSection.FLAGS.value: [
(FlagsConfigKey.DISABLE_JOIN_SOUND_IF_ALONE.value, str(True)),
],
ConfigSection.ENTRANCE_SOUND.value: [],
}

View File

@ -1,29 +1,28 @@
import os import os
import discord from discord.object import Object
from dotenv import load_dotenv from dotenv import load_dotenv
# This is run when this file is imported # This is run when this file is imported
load_dotenv() HAS_VARIABLES: bool = load_dotenv()
print("Debug: Importing heidi_constants.py") print("Debug: Importing heidi_constants.py")
# ================================================================================================ # # =========================================================================== #
# ================================================================================================ # # =========================================================================== #
# NOTE: Always set this correctly: DOCKER: bool = os.getenv("DOCKER") == str(True)
DOCKER = os.getenv("DOCKER") == "True" # =========================================================================== #
# ================================================================================================ # # =========================================================================== #
# ================================================================================================ #
# Constants # Constants
CONFIGPATH = "/config" if DOCKER else "." CONFIGPATH: str = "/config" if DOCKER else "."
USERCONFIGNAME = "Heidi_User.conf" USERCONFIGNAME: str = "Heidi_User.conf"
SOUNDDIR: str = "/sounds" if DOCKER else "./heidi-sounds" SOUNDDIR: str = "/sounds" if DOCKER else "./heidi-sounds"
# IDs of the servers Heidi is used on # IDs of the servers Heidi is used on
LINUS_GUILD = discord.Object(id=431154792308408340) LINUS_GUILD: Object = Object(id=431154792308408340)
TEST_GUILD = discord.Object(id=821511861178204161) TEST_GUILD: Object = Object(id=821511861178204161)
# Channel IDs # Channel IDs
HEIDI_SPAM_ID = 822223476101742682 HEIDI_SPAM_ID: int = 822223476101742682

View File

@ -1,11 +1,12 @@
import asyncio import asyncio
import functools import functools
from typing import Union from types import CoroutineType
from typing import Any, Callable
import discord from discord import Interaction, Message, VoiceChannel, Member, VoiceClient
from discord import Interaction, VoiceChannel, Member from discord.player import FFmpegPCMAudio
from heidi_constants import * from heidi_constants import SOUNDDIR
print("Debug: Importing heidi_helpers.py") print("Debug: Importing heidi_helpers.py")
@ -15,14 +16,15 @@ print("Debug: Importing heidi_helpers.py")
# 1. @enforce_channel(ID) is added to a function, which evaluates to decorate with the channel_id in its closure # 1. @enforce_channel(ID) is added to a function, which evaluates to decorate with the channel_id in its closure
# 2. The function is passed to decorate(function), # 2. The function is passed to decorate(function),
def enforce_channel(channel_id): def enforce_channel(channel_id: int):
""" """
Only run a function if called from the correct channel. Only run a function if called from the specified voice channel.
""" """
def decorate(function):
def decorate(function: Callable[..., CoroutineType[Any, Any, None]]):
@functools.wraps(function) @functools.wraps(function)
async def wrapped(*args, **kwargs): async def wrapped(*args: *tuple[Interaction, *tuple[Any, ...]], **kwargs: int):
""" """
Sends an interaction response if the interaction is not triggered from the heidi_spam channel. Sends an interaction response if the interaction is not triggered from the heidi_spam channel.
""" """
@ -30,7 +32,7 @@ def enforce_channel(channel_id):
# Do not call the decorated function if the channel_id doesn't match # Do not call the decorated function if the channel_id doesn't match
if not interaction.channel_id == channel_id: if not interaction.channel_id == channel_id:
await interaction.response.send_message("Heidi sagt: Geh in heidi_spam du dulli", ephemeral=True) _ = await interaction.response.send_message("Heidi sagt: Geh in heidi_spam du dulli", ephemeral=True)
return return
await function(*args, **kwargs) await function(*args, **kwargs)
@ -40,12 +42,34 @@ def enforce_channel(channel_id):
return decorate return decorate
# Reactions --------------------------------------------------------------------------------------
def create_author_based_message_predicate(names: list[str]) -> Callable[[Message], bool]:
"""
Create a predicate that determines if a message was written by a certain author.
For usage with on_message_triggers.
"""
def handler(message: Message) -> bool:
for name in names:
if (
isinstance(message.author, Member)
and message.author.nick is not None
and name.lower() in message.author.nick.lower()
):
return True
return False
return handler
# Sounds ----------------------------------------------------------------------------------------- # Sounds -----------------------------------------------------------------------------------------
# @todo Normalize volume when playing
async def play_voice_line( async def play_voice_line(
interaction: Union[Interaction, None], interaction: Interaction | None,
voice_channel: VoiceChannel, voice_channel: VoiceChannel,
board: str, board: str,
sound: str, sound: str,
@ -54,23 +78,22 @@ async def play_voice_line(
Play a voice line in the specified channel. Play a voice line in the specified channel.
""" """
try: try:
open(f"{SOUNDDIR}/{board}/{sound}") # Check if the file exists
_ = open(f"{SOUNDDIR}/{board}/{sound}")
except IOError: except IOError:
print(f"Error: Invalid soundfile {SOUNDDIR}/{board}/{sound}!") print(f"Error: Invalid soundfile {SOUNDDIR}/{board}/{sound}!")
if interaction is not None: if interaction is not None:
await interaction.response.send_message( _ = await interaction.response.send_message(
f'Heidi sagt: "{board}/{sound}" kanninich finden bruder', f'Heidi sagt: "{board}/{sound}" kanninich finden bruder', ephemeral=True
ephemeral=True
) )
return return
if interaction is not None: if interaction is not None:
await interaction.response.send_message(f'Heidi sagt: "{board}/{sound}"', ephemeral=True) _ = await interaction.response.send_message(f'Heidi sagt: "{board}/{sound}"', ephemeral=True)
audio_source = discord.FFmpegPCMAudio( # TODO: Normalize volume when playing
f"{SOUNDDIR}/{board}/{sound}" audio_source: FFmpegPCMAudio = FFmpegPCMAudio(f"{SOUNDDIR}/{board}/{sound}") # only works from docker
) # only works from docker voice_client: VoiceClient = await voice_channel.connect()
voice_client = await voice_channel.connect()
voice_client.play(audio_source) voice_client.play(audio_source)
while voice_client.is_playing(): while voice_client.is_playing():
@ -80,7 +103,7 @@ async def play_voice_line(
async def play_voice_line_for_member( async def play_voice_line_for_member(
interaction: Union[Interaction, None], interaction: Interaction | None,
member: Member, member: Member,
board: str, board: str,
sound: str, sound: str,
@ -97,7 +120,7 @@ async def play_voice_line_for_member(
): ):
print("User not in (valid) voice channel!") print("User not in (valid) voice channel!")
if interaction is not None: if interaction is not None:
await interaction.response.send_message("Heidi sagt: Komm in den Channel!", ephemeral=True) _ = await interaction.response.send_message("Heidi sagt: Komm in den Channel!", ephemeral=True)
return return
voice_channel: VoiceChannel = member.voice.channel voice_channel: VoiceChannel = member.voice.channel

2
pyproject.toml Normal file
View File

@ -0,0 +1,2 @@
[tool.black]
line-length = 120

2
setup.cfg Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length = 120