示例#1
0
    async def cmd(self, ctx):
        """Starts up the prompt"""
        if ctx.message.channel.id in self.sessions:
            await ctx.send('Already running a Terminal session '
                           'in this channel. Exit it with `exit()` or `quit`')
            return

        # Rereading the values that were already read in __init__ to ensure its always up to date
        try:
            self.settings = dataIO.load_json(
                abspath(dirname(argv[0])) + '/settings/terminal_settings.json')
        except Exception:
            # Pretend its the worst case and reset the settings
            check_file()
            self.settings = dataIO.load_json(
                abspath(dirname(argv[0])) + '/settings/terminal_settings.json')

        self.prefix = self.settings['prefix']
        self.alias = self.settings['alias']
        self.os = self.settings['os']

        self.sessions.update({ctx.message.channel.id: getcwd()})
        await ctx.send('Enter commands after {} to execute them.'
                       ' `exit()` or `quit` to exit.'.format(
                           self.prefix.replace("`", "\\`")))
示例#2
0
async def on_ready():
    ###
    if hasattr(bot, 'all_cmds') and not bot.all_cmds: bot.all_cmds = {}
    if hasattr(bot, 'running_tasks') and not bot.running_tasks: bot.running_tasks = []
    if hasattr(bot, 'from_serversetup') and not bot.from_serversetup: bot.from_serversetup = {}
    if hasattr(bot, 'running_chapters') and not bot.from_serversetup: bot.running_chapters = {}
    if hasattr(bot, 'chapters_json') and not bot.from_serversetup: bot.chapters_json = {}
    if hasattr(bot, 'anti_raid') and not bot.anti_raid: bot.anti_raid = ArManager.get_ar_data()
    if hasattr(bot, 'currently_afk') and not bot.currently_afk: bot.currently_afk = AfkManager.return_whole_afk_list()
    if hasattr(bot, 'moderation_blacklist') and not bot.moderation_blacklist: bot.moderation_blacklist = {-1: 'dummy'}
    if hasattr(bot, 'reaction_roles') and not bot.reaction_roles: bot.reaction_roles = RRManager.return_whole_rr_list()
    ###
    bot.config = dataIOa.load_json('config.json')
    bot.config['BOT_DEFAULT_EMBED_COLOR'] = int(f"0x{bot.config['BOT_DEFAULT_EMBED_COLOR_STR'][-6:]}", 16)
    bot.uptime = datetime.datetime.utcnow()
    # bot.ranCommands = 0
    bot.help_command = Help()
    bot.logger = logging.getLogger('my_app')
    bot.logger.setLevel(logging.INFO)

    # log formatter -> Credit: appu#4444
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    if not os.path.exists("logs"):
        os.makedirs("logs/error")
        os.makedirs("logs/info")
        os.makedirs("logs/workers")
    logHandler = handlers.RotatingFileHandler('logs/info/info.log', maxBytes=5000, backupCount=20, encoding='utf-8')
    logHandler.setLevel(logging.INFO)
    logHandler.setFormatter(formatter)
    errorLogHandler = handlers.RotatingFileHandler('logs/error/error.log', maxBytes=5000, backupCount=20,
                                                   encoding='utf-8')
    errorLogHandler.setLevel(logging.ERROR)
    errorLogHandler.setFormatter(formatter)

    # fixes bug when bot restarted but log file retained loghandler. this will remove any
    # handlers it already had and replace with new ones initialized above
    for hdlr in list(bot.logger.handlers):
        print(hdlr)
        bot.logger.removeHandler(hdlr)
    bot.logger.addHandler(logHandler)
    bot.logger.addHandler(errorLogHandler)
    bot.help_command = Help()
    bot.logger.info("Bot logged in and ready.")
    print(discord.utils.oauth_url(bot.user.id) + '&permissions=8')
    print('------------------------------------------')
    if os.path.isfile("restart.json"):
        restartData = dataIOa.load_json("restart.json")
        try:
            guild = bot.get_guild(restartData["guild"])
            channel = guild.get_channel(restartData["channel"])
            await channel.send("Restarted.")
        except:
            print(f'---{datetime.datetime.utcnow().strftime("%c")}---')
            trace = traceback.format_exc()
            bot.logger.error(trace)
            print(trace)
            print("couldn't send restarted message to channel.")
        finally:
            os.remove("restart.json")
示例#3
0
    async def createclubs(self, ctx, *, clubs):
        """Multiple clubs"""
        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        clubs = clubs.split()
        for c in clubs:
            c = c.lower()
            if c in clubs_data:
                c = c.replace('@', '@\u200b')
                return await ctx.send(f'💢 `{c}` already exists')

        ret = ""
        for c in clubs:
            c = c.lower()
            clubs_data[c] = {
                'creator': ctx.message.author.id,
                'desc': f"[create clubs command]"
                f"({ctx.message.jump_url})",
                'members': [ctx.message.author.id],
                'pings': 0
            }
            ret += f"✅ {c}\n"
        clbs = '\n'.join([f'`{c.lower()}`' for c in clubs])
        confirm = await dutils.prompt(
            ctx,
            f"This will create the club(s):\n{clbs}".replace('@', '@\u200b'))
        if confirm:
            dataIOa.save_json(path, clubs_data)
            await ctx.send(ret)
        else:
            await ctx.send("Cancelling.")
示例#4
0
    async def clubinfo(self, ctx, club_name):
        """Display info for a club if it exists"""
        club_name = club_name.lower()

        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        if club_name in clubs_data:
            club = clubs_data[club_name]
            creator = ctx.guild.get_member(int(club['creator']))
            mems = [(str(ctx.guild.get_member(u))) for u in club['members']
                    if ctx.guild.get_member(u)]
            em = Embed(
                title=f'Club: {club_name}',
                color=creator.color,
                description=f'**Creator:** {creator.mention} ({creator.name})\n'
                f'**Description:** {club["desc"]}\n'
                f'**Ping count:** {club["pings"]}\n\n'
                f'**Members:** {", ".join(mems)}')
            await ctx.send(embed=em)
        else:
            suggestion = self.findMostSimilar(club_name, [*clubs_data])
            emote_test = utils.get(ctx.guild.emojis, name="HestiaNo")
            emote = "💢" if not emote_test else str(emote_test)
            await ctx.send(
                f'{emote} No such club found, did you perhaps mean `{suggestion}`'
            )
示例#5
0
def check_file():
    jdict = {
        "prefix": ">",
        "alias": {
            'alias example': {
                'linux':
                'printf "Hello.\n'
                'This is an alias made using the magic of python."',
                'windows':
                'echo Hello. '
                'This is an alias made using the magic of python.'
            }
        },
        "os": {
            'windows': '{path}>',
            'linux': '{user}@{system}:{path} $ '
        },
        "cos": "default",
        "enabled": True
    }

    if not dataIO.is_valid_json(
            abspath(dirname(argv[0])) +
            '/settings/terminal_settings.json') or 'cc' in dataIO.load_json(
                abspath(dirname(argv[0])) +
                '/settings/terminal_settings.json'):
        print("[Terminal]Creating default settings.json...")
        dataIO.save_json(
            abspath(dirname(argv[0])) + '/settings/terminal_settings.json',
            jdict)
示例#6
0
 async def check_if_clubs_exist(self, ctx, clubs):
     path = 'data/clubs.json'
     dataIOa.create_file_if_doesnt_exist(path, '{}')
     clubs_data = dataIOa.load_json(path)
     for c in clubs:
         if c not in clubs_data:
             suggestion = self.findMostSimilar(c, [*clubs_data])
             emote_test = utils.get(ctx.guild.emojis, name="HestiaNo")
             emote = "💢" if not emote_test else str(emote_test)
             await ctx.send(
                 f'{emote} A club in your list is invalid, did you perhaps mean `{suggestion}`'
                 f' for that one? (invalid club: '
                 f'`{dutils.cleanUpBannedWords(["@everyone", "@here"], c)}`)'
             )
             return False
         club = clubs_data[c]
         mems = [
             ctx.guild.get_member(u) for u in club['members']
             if ctx.guild.get_member(u)
         ]
         if ctx.author not in mems and not ctx.author.guild_permissions.administrator:
             await ctx.send(
                 f"{self.get_emote_if_exists_else(ctx.guild, 'HestiaNo', '💢')} "
                 f"You can't ping a club you're not a part of (`{c}`)")
             return False
     return True
示例#7
0
    async def leaveclub(self, ctx, club_name):
        """Leave a club"""
        club_name = club_name.lower()

        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        if club_name in clubs_data:
            club = clubs_data[club_name]
            mems = [
                ctx.guild.get_member(u) for u in club['members']
                if ctx.guild.get_member(u)
            ]
            if ctx.author in mems:
                clubs_data[club_name]['members'].remove(ctx.author.id)
                dataIOa.save_json(path, clubs_data)
                await ctx.send(
                    f"{ctx.author.mention} has left the club {club_name}")
            else:
                return await ctx.send(
                    f"{self.get_emote_if_exists_else(ctx.guild, 'HestiaNo', '💢')} "
                    f"You are not even in this club")
        else:
            suggestion = self.findMostSimilar(club_name, [*clubs_data])
            emote_test = utils.get(ctx.guild.emojis, name="HestiaNo")
            emote = "💢" if not emote_test else str(emote_test)
            await ctx.send(
                f'{emote} No such club found, did you perhaps mean `{suggestion}`'
            )
示例#8
0
 def __init__(self, bot):
     self.bot = bot
     self.settings = dataIO.load_json(
         abspath(dirname(argv[0])) + '/settings/terminal_settings.json')
     self.prefix = self.settings['prefix']
     self.alias = self.settings['alias']
     self.os = self.settings['os']
     self.cos = self.settings['cos']
     self.enabled = self.settings['enabled']
     self.sessions = {}
示例#9
0
    async def pingclubs(self, ctx, *, clubs_and_rest_text):
        """Ping multiple clubs, please see detailed usage
        Syntax:
        `[p]ping2 club1 club2 club3; any other content you wish`
        `[p]ping2 club1 club2`
        Example:
        Club Yuri: ['user1', 'user2']
        Club Fate: ['user1', 'user3']
        This command works with the **OR** or **UNION** operator.
        When doing `[p]ping2 yuri fate; cool Eresh x Ishtar pics`
        The bot will ping the users: @user1 @user2 @user3
        """
        clubs = clubs_and_rest_text.rsplit(';', 1)[:1][0].split(' ')
        clubs = [c.lower() for c in clubs]
        clubs = list(set(clubs))
        if len(clubs) < 2:
            return await ctx.send("Need at least 2 clubs for this command")

        all_ok = await self.check_if_clubs_exist(ctx, clubs)

        if all_ok:
            path = 'data/clubs.json'
            dataIOa.create_file_if_doesnt_exist(path, '{}')
            clubs_data = dataIOa.load_json(path)
            mems_all = []
            clubs_all = ""
            for club_name in clubs:
                club = clubs_data[club_name]
                mems = [
                    ctx.guild.get_member(u) for u in club['members']
                    if ctx.guild.get_member(u)
                ]
                clubs_data[club_name]['pings'] += 1
                mems_all = list(set([*mems_all, *mems]))
                clubs_all += club_name + ', '
            dataIOa.save_json(path, clubs_data)

            pings = ['']
            cur_idx = 0
            for m in mems_all:
                pings[cur_idx] += m.mention + ' '
                if len(pings[cur_idx]) + len(clubs_all) > 1900:
                    cur_idx += 1
                    pings.append('')

            for p in pings:
                if p: await ctx.send(f'Clubs: {clubs_all[:-2]} {p}')
示例#10
0
    async def createclub(self, ctx, club_name, *, description):
        """Create a new club
        Usage:
        `[p]createclub yuri A club for the greatest form of love`
        `[p]createclub pokemon Only true nerds allowed`
        `[p]createclub pits Thanks Appu.`
        After you have created a club it will be active once
        a server staff member will verify the club.
        """
        return await ctx.send(
            "Currently disabled here. Just use -createclubs. ALSO NO DESC, just club names!"
        )
        club_name = club_name.lower()
        if '*' in club_name or '*' in description:
            return await ctx.send(
                "The club name can not include the character `*`, please try again."
            )

        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)

        if club_name in clubs_data:
            return await ctx.send('💢 A club with this name already exists')

        ver_ch = ctx.guild.get_channel(self.verification_channel_id)
        if not ver_ch:
            return await ctx.send(
                "Can't find verification channel (check the id for that)")
        await ctx.send(
            "The club has been created, waiting for server staff aproval, you will be notified in dms"
            " once the club has been verified or denied.")
        em = Embed(
            title='A new club has been created',
            color=self.bot.config['BOT_DEFAULT_EMBED_COLOR'],
            description=f'**Club Name:** {club_name}\n'
            f'**Creator:** {ctx.author.mention} ({ctx.author.name}) id: {ctx.author.id}\n'
            f'**Description:** {description}')
        em.set_footer(text='Press the appropriate emote to verify or deny it')
        m = await ver_ch.send(embed=em)
        await m.add_reaction('✅')
        await m.add_reaction('❌')
示例#11
0
    async def pingclub(self,
                       ctx,
                       club_name,
                       *,
                       rest="Anything else that you'd like to add"):
        """Ping a club"""
        club_name = club_name.lower()

        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        if club_name in clubs_data:
            club = clubs_data[club_name]
            # creator = ctx.guild.get_member(int(club['creator']))
            mems = [
                ctx.guild.get_member(u) for u in club['members']
                if ctx.guild.get_member(u)
            ]
            if ctx.author not in mems and not ctx.author.guild_permissions.administrator:
                return await ctx.send(
                    f"{self.get_emote_if_exists_else(ctx.guild, 'HestiaNo', '💢')} "
                    f"You can't ping a club you're not a part of")
            pings = ['']
            clubs_data[club_name]['pings'] += 1
            dataIOa.save_json(path, clubs_data)
            cur_idx = 0
            for m in mems:
                pings[cur_idx] += m.mention + ' '
                if len(pings[cur_idx]) + len(club_name) > 1900:
                    cur_idx += 1
                    pings.append('')

            for p in pings:
                if p: await ctx.send(f'Club: {club_name} {p}')

        else:
            suggestion = self.findMostSimilar(club_name, [*clubs_data])
            emote_test = utils.get(ctx.guild.emojis, name="HestiaNo")
            emote = "💢" if not emote_test else str(emote_test)
            await ctx.send(
                f'{emote} No such club found, did you perhaps mean `{suggestion}`'
            )
示例#12
0
    async def deleteclubs(self, ctx, *, clubs_to_delete):
        """Delete clubs, seperate with a space if deleting many"""
        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        notIn = ""
        wasIn = ""
        for c in clubs_to_delete.split(' '):
            if c in clubs_data:
                del clubs_data[c]
                wasIn += f"{c} "
            else:
                notIn += f"{c} "

        # clbs = '\n'.join([f'`{c.lower()}`' for c in clubs_to_delete])
        confirm = await dutils.prompt(
            ctx, "https://tenor.com/view/are-you-sure"
            "-john-cena-ru-sure-about-dat-gif-14258954")
        if confirm:
            await ctx.send(f"Deleted: {wasIn}\nFailed to delete: {notIn}")
            dataIOa.save_json(path, clubs_data)
        else:
            await ctx.send("Cancelling.")
示例#13
0
    async def listclubsraw(self, ctx, *includes: discord.Member):
        """Display all clubs TITLES
        Optional parameter for checking which clubs members are a part of it, ex:
        `[p]listclubsraw Kiki`
        `[p]listclubsraw @Kiki`
        `[p]listclubsraw 174406433603846145`
        `[p]listclubsraw A B`
        `[p]listclubsraw Kiki Neil Snky`
        `[p]listclubsraw 174406433603846145 Neil @Rollin_Styles`
        For multiple members the command works with **and**
        meaning that in the first example it will
        find clubs where A and B are both in."""

        path = 'data/clubs.json'
        dataIOa.create_file_if_doesnt_exist(path, '{}')
        clubs_data = dataIOa.load_json(path)
        embeds = []
        if not includes:
            embeds = self.createEmbedsFromAllClubs2(clubs_data, 'All clubs')
        else:
            includes = list(includes)
            d_clubs = {}
            for k, v in clubs_data.items():
                mems = [
                    ctx.guild.get_member(u) for u in v['members']
                    if ctx.guild.get_member(u)
                ]
                intersection = list(set(includes) & set(mems))
                if len(intersection) == len(includes):
                    d_clubs[k] = v
            if not d_clubs:
                return await ctx.send("No clubs found for this querry.")
            embeds = self.createEmbedsFromAllClubs2(
                d_clubs, f'Clubs with: '
                f'{" and ".join([m.name for m in includes])}')

        await SimplePaginator(extras=embeds).paginate(ctx)
示例#14
0
    async def el_crawl(self, ctx, start_from_page: int, _driver=None):
        # if not await dutils.prompt(ctx, "Are you running this locally?"):
        #    return await ctx.send("Cancelled")
        await ctx.send("Starting to crawl")
        options = Options()
        options.headless = True
        options.add_argument('window-size=1920x1080')
        options.binary_location = r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
        c = r"A:\\Unsorted\\old-desktop-junk\\chromedriver_win32\\chromedriver.exe"
        if not _driver:
            driver = webdriver.Chrome(c, chrome_options=options)
        else:
            driver = _driver
        print('strating...')
        # driver.minimize_window()
        driver.get("https://animemusicquiz.com/?forceLogin=True")
        driver.implicitly_wait(10)
        eee = driver.find_element_by_xpath("""/html/body/div[1]/div/a""")
        eee.click()
        await asyncio.sleep(2)
        driver.implicitly_wait(3)

        for i in range(5):
            try:
                driver.get(f"https://animemusicquiz.com/")
                driver.find_element_by_xpath(
                    """//*[@id="adminPage"]/div/table/tbody"""
                )  # this is wrong btw
                break
            except:
                await asyncio.sleep(1)
                un = driver.find_element_by_xpath(
                    """//*[@id="loginUsername"]""")
                un.click()
                un.send_keys(ctx.bot.config['AMQ_USERNAME'])

                pw = driver.find_element_by_xpath(
                    """//*[@id="loginPassword"]""")
                pw.click()
                pw.send_keys(ctx.bot.config['AMQ_PASSWORD'])

                signIn = driver.find_element_by_xpath(
                    """//*[@id="loginButton"]""")
                signIn.click()
                print("Login")
                await asyncio.sleep(1)
                bbreak = True
                try:
                    contLog = driver.find_element_by_xpath(
                        """//*[@id="alreadyOnlineContinueButton"]""")
                    contLog.click()
                    break
                except:
                    pass
                try:
                    test = driver.find_element_by_xpath(
                        """//*[@id="mpPlayButton"]""")
                except:
                    bbreak = False
                if bbreak:
                    break

        driver.implicitly_wait(10)
        driver.get(
            f"https://animemusicquiz.com/admin/fixIds?known=true&page=1")

        cur_data = dataIOa.load_json('data/_amq/annMal.json')

        lp = 0
        for i in range(start_from_page, 200):
            driver.get(
                f"https://animemusicquiz.com/admin/fixIds?known=true&page={i}")
            print(f"page {i}")
            await asyncio.sleep(0.3)
            lastPage = False
            try:
                driver.find_element_by_xpath(
                    """//*[@id="adminPage"]/div/table/tbody/tr[2]""")
            except:
                lastPage = True
            if lastPage:
                print("Reached last page")
                break
            lp = i
            tbl2 = driver.find_elements_by_xpath(
                """//*[@id="adminPage"]/div/table/tbody/tr[position() > 1]""")
            for t in tbl2:
                mID = t.get_attribute("data-malid")
                aID = t.get_attribute("data-annid")
                # print(f'{aID} {t.text}')
                cur_data[str(aID)] = t.text

        dataIOa.save_json('data/_amq/annMal.json', cur_data)
        await ctx.send(
            f"Done. (Last page that worked was `{lp}` (for `docrawl`))")
        if not _driver:
            driver.close()
示例#15
0
    async def on_message(self, message):  # This is where the magic starts
        if message.channel.id in self.sessions and self.enabled and message.author.id == self.bot.config[
                'OWNER_ID']:
            # DO NOT DEL

            # TO DO:
            #  Whitelist & Blacklists that cant be modified by the bot

            if not dataIO.is_valid_json(
                    abspath(dirname(argv[0])) +
                    '/settings/terminal_settings.json'):
                check_file()
                self.settings = dataIO.load_json(
                    abspath(dirname(argv[0])) +
                    '/settings/terminal_settings.json')
                self.prefix = self.settings['prefix']
                self.alias = self.settings['alias']
                self.os = self.settings['os']
                self.cos = self.settings['cos']
                self.enabled = self.settings['enabled']

            if (message.content.startswith(self.prefix)
                    or message.content.startswith('debugprefixcmd')):

                if message.content.startswith(self.prefix):
                    command = message.content[len(self.prefix):]
                else:
                    command = message.content[len('debugprefixcmd'):]
                # check if the message starts with the command prefix

                if message.attachments:
                    command += ' ' + message.attachments[0]['url']

                if not command:  # if you have entered nothing it will just ignore
                    return

                if command in self.alias:
                    if self.alias[command][uname()[0].lower()]:
                        command = self.alias[command][uname()[0].lower()]
                    else:
                        command = self.alias[command]['linux']

                if (command == 'exit()' or command == 'quit'
                    ):  # commands used for quiting cmd, same as for repl

                    await message.channel.send('Exiting.')
                    self.sessions.pop(message.channel.id)
                    return

                if command.startswith('cd ') and command.split('cd ')[1]:
                    path = command.split('cd ')[1]
                    try:
                        oldpath = abspath(dirname(argv[0]))
                        chdir(self.sessions[message.channel.id])
                        chdir(path)
                        self.sessions.update({message.channel.id: getcwd()})
                        chdir(oldpath)
                        return
                    except FileNotFoundError:
                        shell = 'cd: {}: Permission denied'.format(path)
                    except PermissionError:
                        shell = 'cd: {}: No such file or directory'.format(
                            path)
                else:
                    try:
                        output = Popen(command,
                                       cwd=self.sessions[message.channel.id],
                                       shell=True,
                                       stdout=PIPE,
                                       stderr=STDOUT,
                                       stdin=DEVNULL).communicate()[0]
                        error = False
                    except CalledProcessError as err:
                        output = err.output
                        error = True

                    shell = output.decode('utf_8')

                if shell == "" and not error:
                    return

                shell = sub('/bin/sh: .: ', '', shell)

                if "\n" in shell[:-2]:
                    shell = '\n' + shell

                if self.cos == 'default':
                    cos = uname()[0].lower()
                else:
                    cos = self.cos

                path = self.sessions[message.channel.id]
                username = getuser()
                system = uname()[1]
                if cos in self.os:
                    user = self.os[cos].format(user=username,
                                               system=system,
                                               path=path)
                else:
                    user = self.os['linux'].format(user=username,
                                                   system=system,
                                                   path=path)

                result = []
                in_text = text = user + shell
                shorten_by = 12
                page_length = 2000
                num_mentions = text.count("@here") + text.count("@everyone")
                shorten_by += num_mentions
                page_length -= shorten_by
                while len(in_text) > page_length:
                    closest_delim = max(
                        [in_text.rfind(d, 0, page_length) for d in ["\n"]])
                    closest_delim = closest_delim if closest_delim != -1 else page_length
                    to_send = in_text[:closest_delim].replace(
                        "@everyone",
                        "@\u200beveryone").replace("@here", "@\u200bhere")
                    result.append(to_send)
                    in_text = in_text[closest_delim:]

                result.append(
                    in_text.replace("@everyone", "@\u200beveryone").replace(
                        "@here", "@\u200bhere"))

                # result = list(pagify(user + shell, shorten_by=12))

                for num, output in enumerate(result):
                    if num % 1 == 0 and num != 0:

                        note = await message.channel.send(
                            'There are still {} pages left.\n'
                            'Type `more` to continue.'
                            ''.format(len(result) - (num + 1)))

                        msg = await self.bot.wait_for(
                            'message',
                            check=lambda m: m.channel == message.channel and m.
                            author == message.author and m.content == 'more',
                            timeout=10)
                        try:
                            await note.delete()
                        except Exception:
                            pass

                        if msg is None:
                            return
                        else:
                            if output:
                                await message.channel.send(
                                    '```Bash\n{}```'.format(output))
                    else:
                        if output:
                            await message.channel.send(
                                '```Bash\n{}```'.format(output))
示例#16
0
Welcomemsg: id, content, desc, images, title, FK_GUILD
Logging: id, target_ch, type, FK_GUILD, FK_Hooks
Webhooks: id, url, id, target_ch, FK_GUILD, valid
"""
import json
import os
import discord
import aiohttp
from peewee import *
from datetime import datetime
from utils.dataIOa import dataIOa

DB = "data/serversetup.db"
db = SqliteDatabase(DB, pragmas={'foreign_keys': 1})

clr = dataIOa.load_json('config.json')['BOT_DEFAULT_EMBED_COLOR_STR'][-6:]


class BaseModel(Model):
    class Meta:
        database = db


class Guild(BaseModel):
    id = IntegerField(primary_key=True)
    muterole = IntegerField(null=True)
    modrole = IntegerField(null=True)
    ignored_chs_at_log = CharField(default="")
    censor_list = CharField(default="")
    disabled_onlyEnabled_cmds_and_chs = CharField(default="{}")
示例#17
0
    async def get_data_from_server(bot, config):
        ret = {}
        possible_for_bot = config['use_these']
        gs = config['saves_guild']
        for G in gs:
            g = bot.get_guild(int(G))
            if not g:
                raise Exception(f"Can't find the guild {G}")
            for k, v in config['saves_guild'][G]['categories'].items():
                if k not in possible_for_bot: continue

                # for i in {1..35}; do curl -v -X GET https://bestdori.com/api/characters/$i.json > $i.json; end; done
                # curl -v -X GET https://bestdori.com/api/characters/main.3.json > characters.main.3.json (not needed)
                # curl -v -X GET https://bestdori.com/api/cards/all.5.json > cards.all.5.json
                if k == 'bandori':
                    chars = {
                        k: v
                        for e in [{
                            i:
                            dataIOa.load_json(f'data/bandori/{i}.json')
                        } for i in range(1, 36)] for k, v in e.items()
                    }
                    cards = dataIOa.load_json(f'data/bandori/cards.all.5.json')
                    d = 0
                    pics = {}
                    for _, v in cards.items():
                        url = ""
                        country_codes = {
                            0: 'jp',
                            1: 'en',
                            2: 'tw',
                            3: 'cn',
                            4: 'kr'
                        }
                        country = country_codes[[
                            i for i, el in enumerate(v['releasedAt'])
                            if el is not None
                        ][0]]
                        card_type = []
                        asset = v['resourceSetName']
                        char = chars[v['characterId']]
                        char_name = char['characterName'][1]
                        char_color = char['colorCode'][-6:]
                        char_key = f"{char_name}_{char_color}"
                        if char_key not in pics: pics[char_key] = [[], []]
                        #if v['rarity'] in [1, 2]:
                        #    card_type = ['card_normal']
                        if v['rarity'] <= 2:
                            continue
                        if v['rarity'] > 2:
                            card_type = ['card_normal', 'card_after_training']
                        if v['type'] in ['kirafes', 'birthday']:
                            card_type.remove('card_normal')

                        for ct in card_type:
                            url = f'https://bestdori.com/assets/{country}/characters/resourceset/{asset}_rip/{ct}.png'

                            pics[char_key][0].append(
                                [type('obj', (object, ), {'url': url}), False])
                            # todo: add to pics
                            d = 0

                    ret[k] = pics
                    continue

                cat = g.get_channel(v)
                pics = {}
                for c in cat.channels:
                    if c.name == '_resp_specific': continue  # todo logic
                    color = "4f545c"
                    resps_for_char = []
                    msgs = await c.history().flatten()
                    attachements = []
                    for m in msgs:
                        #  url, is_nsfw
                        attachements.extend([[a, a.is_spoiler()]
                                             for a in m.attachments])
                        if m.content:
                            if m.content.lower().startswith('color: '):
                                color = m.content.lower().split(
                                    'color: ')[-1][-6:]
                            if m.content.lower().startswith(
                                    'resps:'):  # be sure it's resps:
                                rs = "resps:".join(
                                    m.content.split('resps:')[1:])
                                resps_for_char.extend(
                                    rs.split('```')[1].split('```')[0].split(
                                        '\n'))
                                for r in resps_for_char:
                                    if r == '': resps_for_char.remove(r)
                                a = 0
                    dk = (str(c).replace('-', ' ').title() if
                          not str(c).startswith('_') else str(c)[1:].title()
                          )  # _ at the start maens don't replace -
                    dk += f'_{color}'
                    pics[dk] = [attachements,
                                resps_for_char]  # indexes for ret stuff

                ret[k] = pics
        d = 0
        return ret
示例#18
0
import itertools
import json
import random

import discord
from discord.ext import commands
from discord import Member, Embed, File, utils
import os
import traceback
from models.claims import ClaimsManager, Claimed, UserSettings, History
from utils.dataIOa import dataIOa
import utils.checks as checks
import utils.discordUtils as dutils
import utils.timeStuff as tutils

conf = dataIOa.load_json('settings/claims_settings.json')
possible_for_bot = conf['use_these']


class Fun(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        # _ in channel names is not allowed!!
        # if you want an - instead of a space prefix ch name with _
        self.data = {}
        bot.loop.create_task(self.set_setup())
        self.just_claimed = {}
        self.possible = possible_for_bot  # THESE TWO HAVE TO BE THE SAME

    async def set_setup(self):
        if not self.bot.is_ready():
示例#19
0
    async def recc(self, event):
        # event.guild_id event.user_id event.message_id event.channel_id
        if event.channel_id == self.verification_channel_id:
            g = self.bot.get_guild(int(event.guild_id))
            ch = g.get_channel(int(event.channel_id))
            msg = await ch.fetch_message(event.message_id)
            if event.user_id == self.bot.config["CLIENT_ID"]:
                return  # in case the bot is adding reactions
            if msg.author.id == self.bot.config["CLIENT_ID"] and str(
                    event.emoji) in ['✅', '❌']:
                await msg.clear_reactions()
                try:
                    split = msg.embeds[0].description.split('\n')
                    club_title = split[0].split(' ')[-1]
                    club_creator = g.get_member(int(split[1].split(' ')[-1]))
                    club_desc = ' '.join(split[2].split(' ')[1:])
                    if str(event.emoji) == '✅':
                        path = 'data/clubs.json'
                        dataIOa.create_file_if_doesnt_exist(path, '{}')
                        clubs_data = dataIOa.load_json(path)
                        clubs_data[club_title] = {
                            'creator': club_creator.id,
                            'desc': club_desc,
                            'members': [club_creator.id],
                            'pings': 0
                        }
                        dataIOa.save_json(path, clubs_data)

                        await club_creator.send(
                            f'The club **{club_title}** has been approved ✅')
                        await ch.send(
                            f'The club **{club_title}** has been '
                            f'approved by {g.get_member(event.user_id)} ✅')
                    if str(event.emoji) == '❌':
                        await club_creator.send(
                            f'The club **{club_title}** has been denied ❌')
                        await ch.send(
                            f'The club **{club_title}** has been '
                            f'denied by {g.get_member(event.user_id)} ❌')
                except:
                    pass
                await msg.add_reaction('🔖')
        if event.channel_id == 795720249462882354:
            if event.user_id == self.bot.config["CLIENT_ID"]:
                return  # in case the bot is adding reactions
            g = self.bot.get_guild(int(event.guild_id))
            ch = g.get_channel(int(event.channel_id))
            msg = await ch.fetch_message(event.message_id)
            dic = {(ll.split(' ')[0]).replace('<a:', '<:'):
                   (' '.join(ll.split(' ')[1:])).strip()
                   for ll in msg.content.split('\n')}
            d = 0
            add = event.event_type == 'REACTION_ADD'
            e = str(event.emoji).replace('<a:', '<:')
            if e in dic:
                club_name = dic[e]
                club_name = club_name.lower()
                path = 'data/clubs.json'
                dataIOa.create_file_if_doesnt_exist(path, '{}')
                clubs_data = dataIOa.load_json(path)
                club = clubs_data[club_name]
                mems = [(g.get_member(u)).id for u in club['members']
                        if g.get_member(u)]
                # rch = g.get_channel(470822975676088350)
                if event.user_id not in mems and add:
                    clubs_data[club_name]['members'].append(event.user_id)
                    dataIOa.save_json(path, clubs_data)
                    await ch.send(
                        f"<@{event.user_id}> has joined the club **{club_name}** ✅",
                        delete_after=5)
                if event.user_id in mems and not add:
                    clubs_data[club_name]['members'].remove(event.user_id)
                    dataIOa.save_json(path, clubs_data)
                    await ch.send(
                        f"<@{event.user_id}> has left the club **{club_name}** ❌",
                        delete_after=5)
示例#20
0
    async def get_groups(self, ctx, max_gaps: int, *, clubs_and_rest_text):
        """Get groups so there is no gaps use | to ignore people (more than 100 (-100) for just clubs)"""
        just_club = False
        if max_gaps > 99:
            just_club = True
            max_gaps -= 100
        ignore_mems = []
        if ' | ' in clubs_and_rest_text:
            spl = clubs_and_rest_text.split(' | ')
            c1 = spl[0]
            c2 = spl[1]
            for cc in c2.split(' '):
                im = await commands.MemberConverter().convert(ctx, cc)
                if im:
                    ignore_mems.append(im.id)
        else:
            c1 = clubs_and_rest_text
            c2 = ""

        clubs = c1.rsplit(';', 1)[:1][0].split(' ')
        clubs = [c.lower() for c in clubs]
        clubs = list(set(clubs))
        if len(clubs) < 2:
            return await ctx.send("Need at least 2 clubs for this command")
        if len(clubs) > 8:
            return await ctx.send("No more than 8 clubs!")

        all_ok = await self.check_if_clubs_exist(ctx, clubs)

        if all_ok:
            path = 'data/clubs.json'
            dataIOa.create_file_if_doesnt_exist(path, '{}')
            clubs_data = dataIOa.load_json(path)
            mems_all = []
            all_ids = []
            for club_name in clubs:
                club = clubs_data[club_name]
                #mems = [ctx.guild.get_member(u) for u in club['members'] if ctx.guild.get_member(u)]
                mems = [u for u in club['members'] if ctx.guild.get_member(u)]
                mems_all.append({"clb": club_name, "membs": sorted(mems)})
                all_ids = list({*all_ids, *mems})
            permutations = [t for t in itertools.permutations(mems_all)]
            # permutations = permutations[:len(permutations)//2]

            ok_permutations = []
            for p in permutations:
                if self.check_if_is_ok_for_all(p, all_ids, max_gaps,
                                               ignore_mems):
                    ok_permutations.append(p)

            res = []
            for cbs in ok_permutations:
                rs = []
                for c in cbs:
                    m = ""
                    if not just_club:
                        m = ", ".join([
                            f'{"~~" if u in ignore_mems else "**"}{str(ctx.guild.get_member(u))}{"~~" if u in ignore_mems else "**"}'
                            for u in c['membs'] if ctx.guild.get_member(u)
                        ])
                    rs.append(f'**__{c["clb"]}__** {m}')
                res.append('\n'.join(rs))

            if not res:
                return await ctx.send(f"No order for **{max_gaps}** max gaps")
            res = res[:len(res) // 2]
            if len(res) > 100:
                return await ctx.send(
                    "There's more than 100 different permutations. Too much!")
            await dutils.print_hastebin_or_file(ctx,
                                                '\n\n'.join(res),
                                                just_file=True)
示例#21
0
    async def el_mal(self, ctx, up_to_id: int, _driver=None):
        try:
            chid = 784815078041583638  # KOMUGI
            ch = ctx.guild.get_channel(chid)
            if not ch:
                return await ctx.send("Not in the right guild")
            if up_to_id != -999:
                up_to = await ch.fetch_message(up_to_id)
            else:
                up_to = None
                async for ms in ch.history(limit=None).filter(
                        lambda mm: mm.author.id == 593889007750873138):
                    up_to = ms
                    if '⬆' in [str(r.emoji) for r in ms.reactions]:
                        await ctx.send(
                            f"Id of last message: `{ms.id}` (next time you need to do `;amqmp3 -1 {ms.id}`"
                        )
                        break

            if not up_to:
                raise Exception("No messages found?")

            messages = await ch.history(
                limit=None,
                after=up_to.created_at -
                datetime.timedelta(microseconds=1)).flatten()

            await messages[0].add_reaction('⬇')
            await messages[-1].add_reaction('⬆')
            try:
                await messages[-1].pin()
            except:
                pass  # couldn't pin the pinned pin message

            await ctx.send(
                f"Fetching existing list for `{ctx.bot.config['MAL_USERNAME']}`"
            )
            annToMal = dataIOa.load_json('data/_amq/annMal.json')
            my_list = await self.get_anime_list_ids()
            pattern = r"anime_id\":(\d+),"
            malIds = list(set(re.findall(pattern, my_list)))

            to_add_to_mall = []
            for m in messages:
                try:
                    cnts = m.content.split('\n')
                    aid = cnts[7].split('ID:** ')[-1]
                except:
                    continue  # probably pin message
                if aid not in annToMal:
                    await m.add_reaction('⚠')
                    await ctx.send(embed=Embed(
                        description=f'[ANN **{aid}**]'
                        f'(https://www.animenewsnetwork.com/encyclopedia/'
                        f'anime.php?id={aid}) not in annToMal. '
                        f'Please run `docrawl PAGE_NUM` or add it manuallyy'))
                    continue
                mid = annToMal[aid].split(' ')[0]
                if mid not in malIds:
                    to_add_to_mall.append(mid)

            if not to_add_to_mall:
                await ctx.send("No new shows needed to be added ot MAL.")
                return False
            await ctx.send(
                "There are shows to add. Starting adding process now.")
            options = Options()
            options.headless = True
            options.add_argument('window-size=1920x1080')
            options.binary_location = r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
            c = r"A:\\Unsorted\\old-desktop-junk\\chromedriver_win32\\chromedriver.exe"
            if not _driver:
                driver = webdriver.Chrome(c, chrome_options=options)
            else:
                driver = _driver
            print('strating...')
            didnt_work = []
            if to_add_to_mall:
                driver.set_page_load_timeout(8)
                try:
                    driver.get("https://myanimelist.net/login.php")
                except:
                    pass
                driver.set_page_load_timeout(60)
                driver.implicitly_wait(10)
                # https://selenium-python.readthedocs.io/waits.html

                try:
                    driver.find_element_by_xpath(
                        """//*[@id="loginUserName"]""")
                except:
                    pass

                print("Got login page MAL")

                async def check_for_dmca_shiz():
                    driver.implicitly_wait(2)
                    try:
                        await asyncio.sleep(1)  # waiting a bit
                        privAgg = driver.find_element_by_xpath(
                            """//*[@id="qc-cmp2-ui"]/div[2]/div/button[3]""")
                        privAgg.click()
                    except:
                        pass
                    try:
                        await asyncio.sleep(1)
                        reeee = driver.find_element_by_xpath(
                            """//*[@id="gdpr-modal-bottom"]/div/div/div[2]/button"""
                        )
                        reeee.click()
                    except:
                        pass
                    driver.implicitly_wait(10)

                ded = 0
                exx = ""
                for pls in range(3):
                    try:
                        await asyncio.sleep(1)
                        await check_for_dmca_shiz()
                        un = driver.find_element_by_xpath(
                            """//*[@id="loginUserName"]""")
                        un.click()
                        un.send_keys(Keys.CONTROL, "a")
                        un.clear()
                        un.send_keys(self.bot.config['MAL_USERNAME'])
                        await check_for_dmca_shiz()
                        pw = driver.find_element_by_xpath(
                            """//*[@id="login-password"]""")
                        pw.click()
                        pw.send_keys(Keys.CONTROL, "a")
                        pw.clear()
                        pw.send_keys(self.bot.config['MAL_PASSWORD'])
                        await check_for_dmca_shiz()
                        signIn = driver.find_element_by_xpath(
                            """//*[@id="dialog"]/tbody/tr/td/form/div/p[6]/input"""
                        )
                        signIn.click()
                        print("Clicked sign in on MAL")
                        await asyncio.sleep(3)
                        break
                    except:
                        driver.save_screenshot(
                            'tmp/NANDEKOREWA_ExceptionAtLogin.png')
                        ded += 1
                        exx = traceback.format_exc()
                        print("Trying again zzzzzzzzzzzzzzzzzz")
                        pass
                if ded == 3:
                    print(exx)
                    raise
                to_add_to_mall = list(set(to_add_to_mall))
                await check_for_dmca_shiz()
                for mid in to_add_to_mall:
                    ok = await self.add_anime_to_list(mid, driver)
                    if not ok:
                        didnt_work.append(
                            f'<https://myanimelist.net/anime/{mid}>')
                        print(f'Failed to add {mid}')
                    else:
                        print(f'Added {mid}')
                    await asyncio.sleep(0.5)
                if not _driver:
                    driver.close()
            if didnt_work:
                driver.save_screenshot('tmp/NANDEKOREWA_DidntWork.png')
                jo = '\n'.join(didnt_work)
                await dutils.print_hastebin_or_file(
                    ctx,
                    f"These shows weren't added to mal for some reason:\n{jo}")
            else:
                await ctx.send("All parsed shows added to mal.\nIt's time for")
                if not _driver:
                    await ctx.send(self.gib_code)
                    # await ctx.send(f"copy the content to `toProcessNoMp3.json`\n"
                    #               f"then run `{dutils.bot_pfx_by_ctx(ctx)}catboxpls`")
            return True
        except:
            traceback.print_exc()
            await ctx.send("Something went wrong in el_mal!!")
            return False
            raise
示例#22
0
    async def el_catboxpls(self, ctx, auto=False):
        rets = []
        ret = ""
        to_ret = """
        socket.sendCommand({
            type: "library",
            command: "expandLibrary answer",
            data: {
                annId: [ANNID],
                annSongId: [ANNSONGID],
                url: "[URL]",
                resolution: 0    
            }
        })
                """
        data = dataIOa.load_json('data/_amq/toProcessNoMp3.json')
        dataIOa.save_json('data/_amq/BACKUP_toProcessNoMp3.json', data)
        # print("Saving temporary data, you'll need this later (in case of a crash)"
        #      " in order to make the final output btw.")
        uploaded = dataIOa.load_json('data/_amq/uploaded_name.json')
        uploaded_l = dataIOa.load_json('data/_amq/uploaded_links.json')
        cnt = 0
        while len(data) > 0:
            upl = data.pop()
            if int(upl["annID"]) in self.ignored_ann_ids:
                continue
            loop = asyncio.get_event_loop()
            ll = 'link_7'
            if 'link_4' in upl:
                ll = 'link_4'

            ee = get_valid_filename(upl["songName"])
            out = f'tmp/amq/{upl["annID"]}_{upl["annSongId"]}_{ee}.mp3'

            if not os.path.exists(out) or (os.path.exists(out) and
                                           (out not in uploaded)):
                fil = upl[ll].replace(
                    'files.',
                    'nl.')  # actually just use NL now that it's active
                await ctx.send(f"Creating **{out}** from <{fil}>")
                if os.path.exists(out):
                    os.remove(out)  # we go agane
                # fil = upl[ll]  # better safe than sorry zzzzzzzzzzzzzz
                # panic for no log basically | info
                LOGLEVEL = "panic"
                process = subprocess.Popen([
                    "ffmpeg", "-hide_banner", "-loglevel", LOGLEVEL, "-i", fil,
                    "-b:a", "320k", "-ac", "2", "-map", "a:0", out, "-y"
                ],
                                           stdout=subprocess.PIPE)
                await loop.run_in_executor(None, process.communicate)
                await asyncio.sleep(0.1)
                if not os.path.exists(out):
                    process = subprocess.Popen([
                        "ffmpeg", "-hide_banner", "-loglevel", LOGLEVEL, "-i",
                        fil, "-b:a", "320k", "-ac", "2", "-map", "a:0", out,
                        "-y"
                    ],
                                               stdout=subprocess.PIPE)
                    await loop.run_in_executor(None, process.communicate)
                    await asyncio.sleep(0.1)

            feedback = True
            if out not in uploaded:
                if not await self.is_catbox_alive():
                    await ctx.send("❗❗Catbox ded rn. Continue later..")
                    raise
                await ctx.send(f"Uploading **{out}**")
                ok, link = await self.upload_file_to_catbox(out, ctx)
            else:
                feedback = False
                ok = True
                link = uploaded_l[uploaded.index(out)]
            link = str(link).replace('\n', '').replace(' ', '')
            if not ok:
                await ctx.send("Something went wrong... Details:")
                print(link)
                await dutils.print_hastebin_or_file(ctx, f'```\n{link}```')
                raise

            uploaded.append(out)
            uploaded_l.append(link)
            dataIOa.save_json('data/_amq/uploaded_name.json', uploaded)
            dataIOa.save_json('data/_amq/uploaded_links.json', uploaded_l)
            ret += to_ret.replace('[ANNID]', str(upl["annID"])).replace('[ANNSONGID]', str(upl["annSongId"])). \
                replace('[URL]', str(link)). \
                replace('socket.sendCommand(', '').replace('})', '}')
            if feedback:
                await ctx.send(
                    to_ret.replace('[ANNID]', str(upl["annID"])).replace(
                        '[ANNSONGID]',
                        str(upl["annSongId"])).replace('[URL]', str(link)))
            if cnt < 20:
                ret += ','
                cnt += 1
            else:
                rets.append(ret)
                ret = ""
                cnt = 0
            if len(data) == 0 and ret:
                rets.append(ret)

            # dataIOa.save_json('data/_amq/toProcessNoMp3.json', data)  # NVM: wait why do you keep overwriting this?

        # await ctx.send("""```js
        # socket.sendCommand({
        #    type: "library",
        #    command: "expandLibrary questions"
        # })
        #        ```""")
        LB = "{"
        RB = "}"
        if not auto:
            await ctx.send(f"{ctx.author.mention} **All:**")

        deff = """function _sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }"""
        rr = "{socket.sendCommand(ex[ii]);\nconsole.log(ex[ii]);\nawait _sleep(700);}"
        rett = []
        for r in rets:
            rett.append(
                f'{deff}\n\nvar ex=[{r}]\nasync '
                f'function doIT(){LB}for(let ii=0;ii<ex.length;ii++){LB}{rr}{RB}return ex.length;{RB}'
                f'\nreturn await doIT();')
        if rett:
            await dutils.print_hastebin_or_file(
                ctx, '\n'.join(rett),
                just_file=True)  # for some reason hastebin sux
        return rett
示例#23
0
from utils.help import Help
import logging
import logging.handlers as handlers
from utils.dataIOa import dataIOa
import fileinput
import importlib
import utils.discordUtils as dutils
from models.bot import BotBlacklist, BotBanlist
from models.afking import AfkManager
from models.reactionroles import RRManager

intents = discord.Intents.default()
intents.members = True
intents.presences = True

Prefix = dataIOa.load_json('config.json')['BOT_PREFIX']
Prefix_Per_Guild = dataIOa.load_json('config.json')['B_PREF_GUILD']


def get_pre(_bot, _message):
    if isinstance(_message.channel, discord.DMChannel): return Prefix
    gid = str(_message.guild.id)
    if gid not in Prefix_Per_Guild: return Prefix
    return Prefix_Per_Guild[gid]


def get_pre_or_mention(_bot, _message):
    extras = [get_pre(_bot, _message)]
    return commands.when_mentioned_or(*extras)(_bot, _message)