<commit_before>"""
Discord.py wrapper class which inherits the
Bot class as it's parent
"""
import json, urllib.request, discord, re, time, sys, traceback
from cleverwrap import CleverWrap
from os import walk
from os.path import join, splitext, sep
from discord.ext import commands
from src.storage.db import database

BOT_DESCRIPTION = """
The bunkest bot - type '!help' for my commands, or say my name to chat with me. Type '!help [command] for more info
on a command (i.e. !help color)\n
"""

class BunkBot(commands.Bot):
    def __init__(self):
        super().__init__("!", None, BOT_DESCRIPTION, False)
        self.init: bool = False
        self.chat_timer = 9.5
        self.last_message_at = -1
        self.chat_bot: CleverWrap = None
        self.server: discord.Server = None
        self.bot_testing: discord.Channel = None
        self.mod_chat: discord.Channel = None
        self.vip_chat: discord.Channel = None
        self.role_streaming = None
        self.role_new = None
        self.load_cogs()


    # lifecycle hook - set up all
    # of the necessary and useful channels
    async def on_init(self):
        if self.init is False:
            self.init = True
            self.server = self.get_server(database.get("serverid"))

            for ro in self.server.roles:
                if ro.name == "streaming":
                    self.role_streaming = ro
                elif ro.name == "new":
                    self.role_new = ro

            for ch in self.server.channels:
                if ch.name == "bot-testing":
                    self.bot_testing = ch
                elif ch.name == "mod-chat":
                    self.mod_chat = ch
                elif ch.name == "vip-chat":
                    self.vip_chat = ch

            self.chat_bot = CleverWrap(database.get("cleverbot"))
            await self.say_to_channel(self.bot_testing, "Bot and database initialized. Syncing users and channels...")
            await self.sync_users()
            await self.sync_channels()


    # update the cogs database when
    # new cogs are added to the db
    @staticmethod
    def get_author(ctx: commands.Context, with_id=False) -> str:
        author: str = str(ctx.message.author)

        if not with_id:
            author = author.split("#")[0]

        return author


    # retrieve an array of the passed
    # message command arguments
    @staticmethod
    def get_cmd_params(ctx: commands.Context) -> list:
        if ctx is not None:
            return ctx.message.content.split()[1:]
        else:
            return []


    # check if the bot is still
    # having a conversation with someone
    @property
    def is_chatting(self):
        new_time = time.time() - self.last_message_at
        still_chatting = new_time < self.chat_timer

        if not still_chatting:
            self.last_message_at = -1

        return still_chatting


    # retrieve the author of the
    # given context
    def load_cogs(self) -> None:
        try:
            for path, dirs, files in walk(join("src", "cogs")):
                for f in files:
                    file_path: str = join(path, f)
                    cog_split: list = file_path.split("_")
                    if len(cog_split) > 1 and cog_split[1] == "cog.py":
                        sep_split: list = file_path.split(sep)
                        sep_split[len(sep_split)-1] = splitext(sep_split[len(sep_split)-1])[0]
                        self.load_extension(".".join(sep_split))
        except Exception as e:
            print(e)


    # sync the current server users with
    # those that already exist in the database
    async def sync_users(self) -> None:
        try:
            new_users: list = []
            for member in self.server.members:
                user_added: bool = database.check_user(member)
                if user_added:
                    await self.add_roles(member, self.role_new)
                    new_users.append(member.name)

            if len(new_users) > 0:
                new_user_list: str = "\n".join(new_users)
                new_user_msg: str = "Users synced. The following users have been added to the database: \n{0}".format(new_user_list)
                await self.say_to_channel(self.bot_testing, new_user_msg)
                await self.say_to_channel(self.mod_chat, new_user_msg)
            else:
                await self.say_to_channel(self.bot_testing, "Users synced. No new users added to database.")
        except Exception as e:
            self.handle_error(e, "sync_users", False)


    # update the channel references
    # to
    async def sync_channels(self) -> None:
        try:
            pass
        except Exception as e:
            self.handle_error(e, "sync_channels", False)


    # process each message that is sent
    # to the server - if bunkbot is chatting, continue to chat
    # otherwise, process the message as a command<commit_msg>added stream check during user sync<commit_after>"""
Discord.py wrapper class which inherits the
Bot class as it's parent
"""
import json, urllib.request, discord, re, time, sys, traceback
from cleverwrap import CleverWrap
from os import walk
from os.path import join, splitext, sep
from discord.ext import commands
from src.storage.db import database

BOT_DESCRIPTION = """
The bunkest bot - type '!help' for my commands, or say my name to chat with me. Type '!help [command] for more info
on a command (i.e. !help color)\n
"""

class BunkBot(commands.Bot):
    def __init__(self):
        super().__init__("!", None, BOT_DESCRIPTION, False)
        self.init: bool = False
        self.chat_timer = 9.5
        self.last_message_at = -1
        self.chat_bot: CleverWrap = None
        self.server: discord.Server = None
        self.bot_testing: discord.Channel = None
        self.mod_chat: discord.Channel = None
        self.vip_chat: discord.Channel = None
        self.role_streaming = None
        self.role_new = None
        self.load_cogs()


    # lifecycle hook - set up all
    # of the necessary and useful channels
    async def on_init(self):
        if self.init is False:
            self.init = True
            self.server = self.get_server(database.get("serverid"))

            for ro in self.server.roles:
                if ro.name == "streaming":
                    self.role_streaming = ro
                elif ro.name == "new":
                    self.role_new = ro

            for ch in self.server.channels:
                if ch.name == "bot-testing":
                    self.bot_testing = ch
                elif ch.name == "mod-chat":
                    self.mod_chat = ch
                elif ch.name == "vip-chat":
                    self.vip_chat = ch

            self.chat_bot = CleverWrap(database.get("cleverbot"))
            await self.say_to_channel(self.bot_testing, "Bot and database initialized. Syncing users and channels...")
            await self.sync_users()
            await self.sync_channels()


    # update the cogs database when
    # new cogs are added to the db
    @staticmethod
    def get_author(ctx: commands.Context, with_id=False) -> str:
        author: str = str(ctx.message.author)

        if not with_id:
            author = author.split("#")[0]

        return author


    # retrieve an array of the passed
    # message command arguments
    @staticmethod
    def get_cmd_params(ctx: commands.Context) -> list:
        if ctx is not None:
            return ctx.message.content.split()[1:]
        else:
            return []


    # check if the bot is still
    # having a conversation with someone
    @property
    def is_chatting(self):
        new_time = time.time() - self.last_message_at
        still_chatting = new_time < self.chat_timer

        if not still_chatting:
            self.last_message_at = -1

        return still_chatting


    # retrieve the author of the
    # given context
    def load_cogs(self) -> None:
        try:
            for path, dirs, files in walk(join("src", "cogs")):
                for f in files:
                    file_path: str = join(path, f)
                    cog_split: list = file_path.split("_")
                    if len(cog_split) > 1 and cog_split[1] == "cog.py":
                        sep_split: list = file_path.split(sep)
                        sep_split[len(sep_split)-1] = splitext(sep_split[len(sep_split)-1])[0]
                        self.load_extension(".".join(sep_split))
        except Exception as e:
            print(e)


    # sync the current server users with
    # those that already exist in the database
    async def sync_users(self) -> None:
        try:
            new_users: list = []
            for member in self.server.members:
                user_added: bool = database.check_user(member)
                if user_added:
                    await self.add_roles(member, self.role_new)
                    new_users.append(member.name)

                await self.check_user_streaming(member, member)

            if len(new_users) > 0:
                new_user_list: str = "\n".join(new_users)
                new_user_msg: str = "Users synced. The following users have been added to the database: \n{0}".format(new_user_list)
                await self.say_to_channel(self.bot_testing, new_user_msg)
                await self.say_to_channel(self.mod_chat, new_user_msg)
            else:
                await self.say_to_channel(self.bot_testing, "Users synced. No new users added to database.")
        except Exception as e:
            self.handle_error(e, "sync_users", False)


    # update the channel references
    # to
    async def sync_channels(self) -> None:
        try:
            pass
        except Exception as e:
            self.handle_error(e, "sync_channels", False)


    # process each message that is sent
    # to the server - if bunkbot is chatting, continue to chat
    # otherwise, process the message as a command
{'fraction_non_alphanumeric': 0.08949533460419384, 'fraction_numerical': 0.0026086084077455605, 'mean_word_length': 1.9137679041216018, 'pattern_counts': {'":': 12, '<': 5, '<?xml version=': 0, '>': 17, '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': '5150706', 'n_tokens_mistral': 2922, 'n_tokens_neox': 2808, 'n_words': 845}