<commit_before>""" Plugin for built-in commands.

This script works just like any of the plugins in plugins/
"""

import importlib
import inspect
import logging
import random
from datetime import datetime, timedelta

import discord
import asyncio

from pcbot import utils, Config, Annotate, config
import plugins
client = plugins.client  # type: discord.Client


sub = asyncio.subprocess
lambdas = Config("lambdas", data={})
lambda_config = Config("lambda-config", data=dict(imports=[], blacklist=[]))

code_globals = {}


@plugins.command(name="help", aliases="commands")
async def help_(message: discord.Message, command: str.lower=None, *args):
    """ Display commands or their usage and description. """
    # Display the specific command
    if command:
        if command.startswith(config.command_prefix):
            command = command[len(config.command_prefix):]

        cmd = plugins.get_command(command)
        if not cmd:
            return

        # Get the specific command with arguments and send the help
        cmd = plugins.get_sub_command(cmd, *args)
        await client.say(message, utils.format_help(cmd))

    # Display every command
    else:
        commands = []

        for plugin in plugins.all_values():
            if getattr(plugin, "__commands", False):  # Massive pile of shit that works (so sorry)
                commands.extend(
                    cmd.name_prefix.split()[0] for cmd in plugin.__commands
                    if not cmd.hidden and
                    (not getattr(getattr(cmd, "function"), "owner", False) or
                     utils.is_owner(message.author))
                )

        commands = ", ".join(sorted(commands))

        m = "**Commands**: ```{0}```Use `{1}help <command>`, `{1}<command> {2}` or " \
            "`{1}<command> {3}` for command specific help.".format(
            commands, config.command_prefix, *config.help_arg)
        await client.say(message, m)


@plugins.command(hidden=True)
async def setowner(message: discord.Message):
    """ Set the bot owner. Only works in private messages. """
    if not message.channel.is_private:
        return

    assert not utils.owner_cfg.data, "An owner is already set."

    owner_code = str(random.randint(100, 999))
    logging.critical("Owner code for assignment: {}".format(owner_code))

    await client.say(message,
                     "A code has been printed in the console for you to repeat within 60 seconds.")
    user_code = await client.wait_for_message(timeout=60, channel=message.channel, content=owner_code)

    assert user_code, "You failed to send the desired code."

    if user_code:
        await client.say(message, "You have been assigned bot owner.")
        utils.owner_cfg.data = message.author.id
        utils.owner_cfg.save()


@plugins.command()
@utils.owner
async def stop(message: discord.Message):
    """ Stops the bot. """
    await client.say(message, "\N{COLLISION SYMBOL}\N{PISTOL}")
    await plugins.save_plugins()
    await client.logout()


@plugins.command()
@utils.owner
async def update(message: discord.Message):
    """ Update the bot by running `git pull`."""
    process = await sub.create_subprocess_exec("git", "pull", stdout=sub.PIPE)
    result, _ = process.communicate()
    await client.say(message, "```diff\n{}```".format(result.decode("utf-8")))


@plugins.command()
@utils.owner
async def game(message: discord.Message, name: Annotate.Content=None):
    """ Stop playing or set game to `name`. """
    await client.change_presence(game=discord.Game(name=name, type=0))
    await client.say(message, "**Set the game to** `{}`.".format(name) if name else "**No longer playing.**")


@game.command()
@utils.owner
async def stream(message: discord.Message, url: str, title: Annotate.Content):
    """ Start streaming a game. """<commit_msg>Refix update command.<commit_after>""" Plugin for built-in commands.

This script works just like any of the plugins in plugins/
"""

import importlib
import inspect
import logging
import random
from datetime import datetime, timedelta

import discord
import asyncio

from pcbot import utils, Config, Annotate, config
import plugins
client = plugins.client  # type: discord.Client


sub = asyncio.subprocess
lambdas = Config("lambdas", data={})
lambda_config = Config("lambda-config", data=dict(imports=[], blacklist=[]))

code_globals = {}


@plugins.command(name="help", aliases="commands")
async def help_(message: discord.Message, command: str.lower=None, *args):
    """ Display commands or their usage and description. """
    # Display the specific command
    if command:
        if command.startswith(config.command_prefix):
            command = command[len(config.command_prefix):]

        cmd = plugins.get_command(command)
        if not cmd:
            return

        # Get the specific command with arguments and send the help
        cmd = plugins.get_sub_command(cmd, *args)
        await client.say(message, utils.format_help(cmd))

    # Display every command
    else:
        commands = []

        for plugin in plugins.all_values():
            if getattr(plugin, "__commands", False):  # Massive pile of shit that works (so sorry)
                commands.extend(
                    cmd.name_prefix.split()[0] for cmd in plugin.__commands
                    if not cmd.hidden and
                    (not getattr(getattr(cmd, "function"), "owner", False) or
                     utils.is_owner(message.author))
                )

        commands = ", ".join(sorted(commands))

        m = "**Commands**: ```{0}```Use `{1}help <command>`, `{1}<command> {2}` or " \
            "`{1}<command> {3}` for command specific help.".format(
            commands, config.command_prefix, *config.help_arg)
        await client.say(message, m)


@plugins.command(hidden=True)
async def setowner(message: discord.Message):
    """ Set the bot owner. Only works in private messages. """
    if not message.channel.is_private:
        return

    assert not utils.owner_cfg.data, "An owner is already set."

    owner_code = str(random.randint(100, 999))
    logging.critical("Owner code for assignment: {}".format(owner_code))

    await client.say(message,
                     "A code has been printed in the console for you to repeat within 60 seconds.")
    user_code = await client.wait_for_message(timeout=60, channel=message.channel, content=owner_code)

    assert user_code, "You failed to send the desired code."

    if user_code:
        await client.say(message, "You have been assigned bot owner.")
        utils.owner_cfg.data = message.author.id
        utils.owner_cfg.save()


@plugins.command()
@utils.owner
async def stop(message: discord.Message):
    """ Stops the bot. """
    await client.say(message, "\N{COLLISION SYMBOL}\N{PISTOL}")
    await plugins.save_plugins()
    await client.logout()


@plugins.command()
@utils.owner
async def update(message: discord.Message):
    """ Update the bot by running `git pull`."""
    process = sub.create_subprocess_exec("git", "pull", stdout=sub.PIPE)
    result, _ = await process.communicate()
    await client.say(message, "```diff\n{}```".format(result.decode("utf-8")))


@plugins.command()
@utils.owner
async def game(message: discord.Message, name: Annotate.Content=None):
    """ Stop playing or set game to `name`. """
    await client.change_presence(game=discord.Game(name=name, type=0))
    await client.say(message, "**Set the game to** `{}`.".format(name) if name else "**No longer playing.**")


@game.command()
@utils.owner
async def stream(message: discord.Message, url: str, title: Annotate.Content):
    """ Start streaming a game. """
{'fraction_non_alphanumeric': 0.1271849726063136, 'fraction_numerical': 0.004956952778502478, 'mean_word_length': 3.1987951807228914, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, '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': 2, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7510120', 'n_tokens_mistral': 2266, 'n_tokens_neox': 2203, 'n_words': 656}