From 28383daf7d34a228f2cf3f32e44cf1dafc1668f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Deuchnord?= Date: Sun, 25 Jul 2021 15:45:14 +0200 Subject: [PATCH] Add support for command aliases --- .gitignore | 3 ++- _twitchbot/config.py | 17 +++++++++++++++-- _twitchbot/twitchbot.py | 13 ++++++------- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index c26f084..0b24f1a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ config.json -docker-compose.yml \ No newline at end of file +docker-compose.yml +__pycache__ \ No newline at end of file diff --git a/_twitchbot/config.py b/_twitchbot/config.py index d3061fe..851de2a 100644 --- a/_twitchbot/config.py +++ b/_twitchbot/config.py @@ -19,19 +19,22 @@ import json from os import environ from enum import Enum +from typing import Union class Command: name: str message: str + aliases: [str] - def __init__(self, name: str, message: str): + def __init__(self, name: str, message: str, aliases: [str] = []): self.name = name self.message = message + self.aliases = aliases @classmethod def from_dict(cls, params: dict): - return Command(params['name'], params['message']) + return Command(params['name'], params['message'], params.get('aliases', [])) class TimerStrategy(Enum): @@ -114,6 +117,16 @@ class Config: Timer.from_dict(params.get('timer', {})) ) + def find_command(self, command: str) -> Union[None, Command]: + if command.startswith(self.command_prefix): + command = command[1:] + + for c in self.commands: + if c.name == command or command in c.aliases: + return c + + return None + def get_config(file_path: str): with open(file_path, 'r') as config_file: diff --git a/_twitchbot/twitchbot.py b/_twitchbot/twitchbot.py index fc379fa..5a78851 100644 --- a/_twitchbot/twitchbot.py +++ b/_twitchbot/twitchbot.py @@ -17,7 +17,7 @@ import irc3 -from .config import get_config, TimerStrategy +from .config import TimerStrategy from random import shuffle from datetime import datetime, timedelta @@ -57,12 +57,11 @@ class TwitchBot: @irc3.event(irc3.rfc.PRIVMSG) def on_msg(self, target, mask, data, **_): - print(target) - for command in self.config.commands: - if ('%s ' % data.lower()).startswith('%s%s ' % (self.config.command_prefix, command.name.lower())): - print('%s: %s%s' % (mask, self.config.command_prefix, command.name)) - self.bot.privmsg(target, self._parse_variables(command.message, mask)) - break + command = self.config.find_command(data.lower().split(' ')[0]) + + if command is not None: + print('%s: %s%s' % (mask, self.config.command_prefix, command.name)) + self.bot.privmsg(target, self._parse_variables(command.message, mask)) self.nb_messages_since_timer += 1 self.play_timer()