<commit_before>from typing import Optional

import logging
import re

from pajbot.managers.adminlog import AdminLogManager
from pajbot.managers.db import DBManager
from pajbot.models.user import User

log = logging.getLogger(__name__)


class Dispatch:
    """
    Methods in this class accessible from commands
    """

    @staticmethod
    def add_win(bot, source, message, event, args):
        # XXX: this is ugly as fuck
        bot.kvi["br_wins"].inc()
        bot.me(f"{source} added a BR win!")

    @staticmethod
    def add_command(bot, source, message, event, args):
        """Dispatch method for creating commands.
        Usage: !add command ALIAS [options] RESPONSE
        See pajbot/managers/command.py parse_command_arguments for available options
        """

        if not message:
            return False

        # Make sure we got both an alias and a response
        message_parts = message.split()
        if len(message_parts) < 2:
            bot.whisper(source, "Usage: !add command ALIAS [options] RESPONSE")
            return False

        options, response = bot.commands.parse_command_arguments(message_parts[1:])

        if options is False:
            bot.whisper(source, "Invalid command")
            return False

        options["added_by"] = source.id

        alias_str = message_parts[0].replace("!", "").lower()
        action_type: str = options.get("action_type", "say")
        if response.startswith("/me") or response.startswith(".me"):
            action_type = "me"
            response = " ".join(response.split(" ")[1:])
        action = {"type": action_type, "message": response}

        command, new_command, alias_matched = bot.commands.create_command(alias_str, action=action, **options)
        if new_command is True:
            bot.whisper(source, f"Added your command (ID: {command.id})")

            log_msg = f"The !{command.command.split('|')[0]} command has been created"
            AdminLogManager.add_entry("Command created", source, log_msg)
            return True

        # At least one alias is already in use, notify the user to use !edit command instead
        bot.whisper(
            source,
            f"The alias {alias_matched} is already in use. To edit that command, use !edit command instead of !add command.",
        )
        return False

    @staticmethod
    def edit_command(bot, source, message, event, args):
        """Dispatch method for editing commands.
        Usage: !edit command ALIAS [options] RESPONSE
        See pajbot/managers/command.py parse_command_arguments for available options
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source, "Usage: !edit command ALIAS [options] RESPONSE")
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options["edited_by"] = source.id

            if options is False:
                bot.whisper(source, "Invalid command")
                return False

            alias = message_parts[0].replace("!", "").lower()<commit_msg>Migrate `add_command` function to `send_message_to_user` function (#1912)<commit_after>from typing import Optional

import logging
import re

from pajbot.managers.adminlog import AdminLogManager
from pajbot.managers.db import DBManager
from pajbot.models.user import User

log = logging.getLogger(__name__)


class Dispatch:
    """
    Methods in this class accessible from commands
    """

    @staticmethod
    def add_win(bot, source, message, event, args):
        # XXX: this is ugly as fuck
        bot.kvi["br_wins"].inc()
        bot.me(f"{source} added a BR win!")

    @staticmethod
    def add_command(bot, source, message, event, args):
        """Dispatch method for creating commands.
        Usage: !add command ALIAS [options] RESPONSE
        See pajbot/managers/command.py parse_command_arguments for available options
        """

        if not message:
            return False

        # Make sure we got both an alias and a response
        message_parts = message.split()
        if len(message_parts) < 2:
            bot.send_message_to_user(source, "Usage: !add command ALIAS [options] RESPONSE", event, method="whisper")
            return False

        options, response = bot.commands.parse_command_arguments(message_parts[1:])

        if options is False:
            bot.send_message_to_user(source, "Invalid command", event, method="whisper")
            return False

        options["added_by"] = source.id

        alias_str = message_parts[0].replace("!", "").lower()
        action_type: str = options.get("action_type", "say")
        if response.startswith("/me") or response.startswith(".me"):
            action_type = "me"
            response = " ".join(response.split(" ")[1:])
        action = {"type": action_type, "message": response}

        command, new_command, alias_matched = bot.commands.create_command(alias_str, action=action, **options)
        if new_command is True:
            bot.send_message_to_user(source, f"Added your command (ID: {command.id})", event, method="whisper")

            log_msg = f"The !{command.command.split('|')[0]} command has been created"
            AdminLogManager.add_entry("Command created", source, log_msg)
            return True

        # At least one alias is already in use, notify the user to use !edit command instead
        bot.send_message_to_user(
            source,
            f"The alias {alias_matched} is already in use. To edit that command, use !edit command instead of !add command.",
            event,
            method="whisper",
        )
        return False

    @staticmethod
    def edit_command(bot, source, message, event, args):
        """Dispatch method for editing commands.
        Usage: !edit command ALIAS [options] RESPONSE
        See pajbot/managers/command.py parse_command_arguments for available options
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source, "Usage: !edit command ALIAS [options] RESPONSE")
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options["edited_by"] = source.id

            if options is False:
                bot.whisper(source, "Invalid command")
                return False

            alias = message_parts[0].replace("!", "").lower()
{'fraction_non_alphanumeric': 0.09943011397720455, 'fraction_numerical': 0.002999400119976005, 'mean_word_length': 2.4644155844155846, 'pattern_counts': {'":': 4, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3664874', 'n_tokens_mistral': 1873, 'n_tokens_neox': 1814, 'n_words': 557}