Esempio n. 1
0
async def mathgame(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        set_ongoing(cmd.name, pld.msg.channel.id)
        if pld.args:
            try:
                diff = int(pld.args[0])
                if diff < 1:
                    diff = 1
                elif diff > 9:
                    diff = 9
            except ValueError:
                diff = 3
        else:
            diff = 3
        max_num = diff * 8
        easy_operators = ['+', '-']
        hard_operators = ['*', '/']
        math_operators = easy_operators + hard_operators
        problem_string = str(secrets.randbelow(max_num))
        allotted_time = 7
        kud_reward = 2
        for x in range(0, diff):
            num = secrets.randbelow(max_num) + 1
            oper = secrets.choice(math_operators)
            if oper in easy_operators:
                kud_reward += 1
                allotted_time += 3
            else:
                kud_reward += 4
                allotted_time += 9
            problem_string += f' {oper} {num}'
        result = round(eval(problem_string), 2)
        problem_string = problem_string.replace('*', 'x').replace('/', '÷')
        question_embed = discord.Embed(
            color=0x3B88C3, title=f'#⃣  You have {allotted_time} seconds.')
        question_embed.description = f'{problem_string} = ?'
        await pld.msg.channel.send(embed=question_embed)

        def check_answer(msg):
            """

            :param msg:
            :type msg:
            :return:
            :rtype:
            """
            if pld.msg.channel.id == msg.channel.id:
                try:
                    an_num = float(msg.content)
                    if an_num == result:
                        correct = True
                    else:
                        correct = False
                except ValueError:
                    correct = False
            else:
                correct = False
            return correct

        try:
            answer_message = await cmd.bot.wait_for('message',
                                                    check=check_answer,
                                                    timeout=allotted_time)
            await cmd.db.add_resource(answer_message.author.id, 'currency',
                                      kud_reward, cmd.name, pld.msg)
            author = answer_message.author.display_name
            currency = cmd.bot.cfg.pref.currency
            win_title = f'🎉 Correct, {author}, it was {result}. You won {kud_reward} {currency}!'
            win_embed = discord.Embed(color=0x77B255, title=win_title)
            await pld.msg.channel.send(embed=win_embed)
        except asyncio.TimeoutError:
            timeout_title = f'🕙 Time\'s up! It was {result}...'
            timeout_embed = discord.Embed(color=0x696969, title=timeout_title)
            await pld.msg.channel.send(embed=timeout_embed)
        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is already one ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
Esempio n. 2
0
async def purge(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.msg.author.permissions_in(pld.msg.channel).manage_messages:
        if not is_ongoing(cmd.name, pld.msg.channel.id):
            set_ongoing(cmd.name, pld.msg.channel.id)
            pld.args = [a.lower() for a in pld.args]
            purge_images = 'attachments' in pld.args
            purge_emotes = 'emotes' in pld.args
            until_pin = 'untilpin' in pld.args
            purge_filter = None
            for i, arg in enumerate(pld.args):
                if arg.startswith('content:'):
                    purge_filter = ' '.join([arg.split(':')[1]] +
                                            pld.args[i + 1:])
                    break

            async def get_limit_and_target():
                """

                :return:
                :rtype:
                """
                user = cmd.bot.user
                limit = 100
                if pld.msg.mentions:
                    user = pld.msg.mentions[0]
                    if len(pld.args) == 2:
                        try:
                            limit = int(pld.args[0])
                        except ValueError:
                            limit = 100
                else:
                    if pld.args:
                        user = None
                        try:
                            limit = int(pld.args[0])
                        except ValueError:
                            limit = 100
                if until_pin:
                    channel_hist = await pld.msg.channel.history(limit=limit
                                                                 ).flatten()
                    for n, log in enumerate(channel_hist):
                        if log.pinned:
                            limit = n - 1
                if limit > 100:
                    limit = 100
                return limit, user

            count, target = await get_limit_and_target()

            def is_emotes(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                clean = False
                if msg.content:
                    for piece in msg.content.split():
                        piece = piece.strip()
                        # matches custom emote
                        if re.search(r'<a?:\w+:\d+>', piece):
                            clean = True
                        # matches global emote
                        elif re.search(r':\w+:', piece):
                            clean = True
                        # matches Unicode emote
                        elif len(piece) == 1 and category(piece) == 'So':
                            clean = True
                        else:
                            clean = False
                            break
                return clean

            def purge_target_check(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                clean = False
                if not msg.pinned:
                    if msg.author.id == target.id:
                        if purge_images:
                            if msg.attachments:
                                clean = True
                        elif purge_emotes:
                            clean = is_emotes(msg)
                        elif purge_filter:
                            if purge_filter.lower() in msg.content.lower():
                                clean = True
                        else:
                            clean = True
                return clean

            def purge_wide_check(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                clean = False
                if not msg.pinned:
                    if purge_images:
                        if msg.attachments:
                            clean = True
                    elif purge_emotes:
                        clean = is_emotes(msg)
                    elif purge_filter:
                        if purge_filter.lower() in msg.content.lower():
                            clean = True
                    else:
                        clean = True
                return clean

            try:
                await pld.msg.delete()
            except discord.NotFound:
                pass
            deleted = []
            # noinspection PyBroadException
            try:
                if target:
                    deleted = await pld.msg.channel.purge(
                        limit=count, check=purge_target_check)
                else:
                    deleted = await pld.msg.channel.purge(
                        limit=count, check=purge_wide_check)
            except Exception:
                pass
            response = ok(f'Deleted {len(deleted)} Messages')
            log_embed = generate_log_embed(pld.msg, target, pld.msg.channel,
                                           deleted)
            await log_event(cmd.bot, pld.settings, log_embed, 'log_purges')
            if is_ongoing(cmd.name, pld.msg.channel.id):
                del_ongoing(cmd.name, pld.msg.channel.id)
            try:
                del_response = await pld.msg.channel.send(embed=response)
                await asyncio.sleep(5)
                await del_response.delete()
            except discord.NotFound:
                pass
            return
        else:
            response = error('There is already one ongoing.')
    else:
        response = denied('Access Denied. Manage Messages needed.')
    await pld.msg.channel.send(embed=response)
async def slow_buy(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    currency = cmd.bot.cfg.pref.currency
    if not is_ongoing(cmd.name, pld.msg.author.id):
        set_ongoing(cmd.name, pld.msg.author.id)
        upgrade_file = await cmd.bot.db.get_profile(pld.msg.author.id,
                                                    'upgrades') or {}
        upgrade_text = ''
        upgrade_index = 0
        for upgrade in upgrade_list:
            upgrade_index += 1
            upgrade_id = upgrade.get('id')
            upgrade_level = upgrade_file.get(upgrade_id, 0)
            base_price = upgrade.get('cost')
            upgrade_price = get_price(base_price, upgrade_level)
            next_upgrade = upgrade_level + 1
            upgrade_text += f'\n**{upgrade_index}**: Level {next_upgrade} {upgrade["name"]}'
            upgrade_text += f' - {upgrade_price} {currency}'
            upgrade_text += f'\n > {upgrade["desc"]}'
        upgrade_list_embed = discord.Embed(color=0xF9F9F9,
                                           title='🛍 Profession Upgrade Shop')
        upgrade_list_embed.description = upgrade_text
        upgrade_list_embed.set_footer(
            text='Please input the number of the upgrade you want.')
        upgrade_number, timeout = await int_dialogue(cmd.bot, pld.msg,
                                                     upgrade_list_embed, 1,
                                                     len(upgrade_list))
        if not timeout:
            upgrade = upgrade_list[upgrade_number - 1]
            current_kud = await cmd.db.get_resource(pld.msg.author.id,
                                                    'currency')
            current_kud = current_kud.current
            upgrade_id = upgrade['id']
            upgrade_level = upgrade_file.get(upgrade_id, 0)
            base_price = upgrade['cost']
            upgrade_price = get_price(base_price, upgrade_level)
            if current_kud >= upgrade_price:
                new_upgrade_level = upgrade_level + 1
                upgrade_file.update({upgrade_id: new_upgrade_level})
                await cmd.db.set_profile(pld.msg.author.id, 'upgrades',
                                         upgrade_file)
                await cmd.db.del_resource(pld.msg.author.id, 'currency',
                                          upgrade_price, cmd.name, pld.msg)
                response = ok(
                    f'Upgraded your {upgrade["name"]} to Level {new_upgrade_level}.'
                )
            else:
                response = discord.Embed(
                    color=0xa7d28b,
                    title=f'💸 You don\'t have enough {currency}.')
        else:
            response = discord.Embed(color=0x696969,
                                     title='🕙 Sorry, you timed out.')
        if is_ongoing(cmd.name, pld.msg.author.id):
            del_ongoing(cmd.name, pld.msg.author.id)
    else:
        response = error('You already have a shop open.')
    await pld.msg.channel.send(embed=response)
Esempio n. 4
0
async def sell(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if is_ongoing(cmd.name, pld.msg.author.id):
        return
    set_ongoing(cmd.name, pld.msg.author.id)
    item_core = await get_item_core(cmd.db)
    currency = cmd.bot.cfg.pref.currency
    if pld.args:
        inv = await cmd.db.get_inventory(pld.msg.author.id)
        if inv:
            lookup = ' '.join(pld.args)
            if lookup.lower() == 'all':
                ender = 's' if len(inv) > 1 else ''
                worth = sum([
                    item_core.get_item_by_file_id(ient['item_file_id']).value
                    for ient in inv
                ])
                question = f'❔ Are you sure you want to sell {len(inv)} item{ender} worth {worth} {currency}?'
                quesbed = discord.Embed(color=0xF9F9F9, title=question)
                sell_confirm, timeout = await bool_dialogue(
                    cmd.bot, pld.msg, quesbed, True)
                if sell_confirm:
                    value = 0
                    count = 0
                    for invitem in inv.copy():
                        item_ob_id = item_core.get_item_by_file_id(
                            invitem['item_file_id'])
                        value += item_ob_id.value
                        count += 1
                        await cmd.db.del_from_inventory(
                            pld.msg.author.id, invitem['item_id'])
                    await cmd.db.add_resource(pld.msg.author.id, 'currency',
                                              value, cmd.name, pld.msg)
                    response = discord.Embed(color=0xc6e4b5)
                    response.title = f'💶 You sold {count} item{ender} for {value} {currency}.'
                else:
                    response = discord.Embed(color=0xBE1931,
                                             title='❌ Item sale canceled.')
            elif lookup.lower() == 'duplicates':
                value = 0
                count = 0
                existing_ids = []
                for invitem in inv.copy():
                    file_id = invitem['item_file_id']
                    if file_id in existing_ids:
                        item_ob_id = item_core.get_item_by_file_id(file_id)
                        value += item_ob_id.value
                        count += 1
                        await cmd.db.del_from_inventory(
                            pld.msg.author.id, invitem['item_id'])
                    else:
                        existing_ids.append(file_id)
                await cmd.db.add_resource(pld.msg.author.id, 'currency', value,
                                          cmd.name, pld.msg)
                ender = 's' if count > 1 else ''
                response = discord.Embed(color=0xc6e4b5)
                response.title = f'💶 You sold {count} duplicate{ender} for {value} {currency}.'
            else:
                request_count = 1
                if len(pld.args) > 1:
                    if pld.args[0].isdigit():
                        request_count = int(pld.args[0])
                        lookup = ' '.join(pld.args[1:])
                item_o = item_core.get_item_by_name(lookup)
                count = 0
                value = 0
                if item_o:
                    for _ in range(request_count):
                        item = await cmd.db.get_inventory_item(
                            pld.msg.author.id, item_o.file_id)
                        if item:
                            value += item_o.value
                            count += 1
                            await cmd.db.del_from_inventory(
                                pld.msg.author.id, item['item_id'])
                        else:
                            break
                if count > 0:
                    await cmd.db.add_resource(pld.msg.author.id, 'currency',
                                              value, cmd.name, pld.msg)
                    ender = 's' if count > 1 else ''
                    response = discord.Embed(color=0xc6e4b5)
                    response.title = f'💶 You sold {count} {item_o.name}{ender} for {value} {currency}.'
                else:
                    if not lookup.isdigit():
                        response = not_found(
                            f'I didn\'t find any {lookup} in your inventory.')
                    else:
                        response = not_found(f'Sell {lookup} of what?')
        else:
            response = discord.Embed(color=0xc6e4b5,
                                     title='💸 Your inventory is empty...')
    else:
        response = error('Nothing inputted.')
    if is_ongoing(cmd.name, pld.msg.author.id):
        del_ongoing(cmd.name, pld.msg.author.id)
    response.set_author(name=pld.msg.author.display_name,
                        icon_url=user_avatar(pld.msg.author))
    await pld.msg.channel.send(embed=response)
async def mangachargame(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        try:
            set_ongoing(cmd.name, pld.msg.channel.id)
            mal_icon = 'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png'
            wait_embed = discord.Embed(color=0x1d439b)
            wait_embed.set_author(name='Hunting for a good specimen...',
                                  icon_url=mal_icon)
            working_response = await pld.msg.channel.send(embed=wait_embed)
            if pld.args:
                if pld.args[0].lower() == 'hint':
                    hint = True
                else:
                    hint = False
            else:
                hint = False
            ani_order = secrets.randbelow(3) * 50
            if ani_order:
                ani_top_list_url = f'https://myanimelist.net/topmanga.php?limit={ani_order}'
            else:
                ani_top_list_url = 'https://myanimelist.net/topmanga.php'
            async with aiohttp.ClientSession() as session:
                async with session.get(
                        ani_top_list_url) as ani_top_list_session:
                    ani_top_list_html = await ani_top_list_session.text()
            ani_top_list_data = html.fromstring(ani_top_list_html)
            ani_list_objects = ani_top_list_data.cssselect('.ranking-list')
            ani_choice = secrets.choice(ani_list_objects)
            ani_url = ani_choice[1][0].attrib['href']
            async with aiohttp.ClientSession() as session:
                async with session.get(
                        f'{ani_url}/characters') as ani_page_session:
                    ani_page_html = await ani_page_session.text()
            ani_page_data = html.fromstring(ani_page_html)
            cover_object = ani_page_data.cssselect('.ac')[0]
            anime_cover = cover_object.attrib['src']
            anime_title = cover_object.attrib['alt'].strip()
            character_object_list = ani_page_data.cssselect('.borderClass')
            character_list = []
            for char_obj in character_object_list:
                if 'href' in char_obj[0].attrib:
                    if char_obj[1].text_content().strip() == 'Main':
                        character_list.append(char_obj)
            char_choice = secrets.choice(character_list)
            char_url = char_choice[0].attrib['href']
            async with aiohttp.ClientSession() as session:
                async with session.get(char_url) as char_page_session:
                    char_page_html = await char_page_session.text()
            char_page_data = html.fromstring(char_page_html)
            char_img_obj = char_page_data.cssselect('.borderClass')[0][0][0][0]
            char_img = char_img_obj.attrib['src']
            char_name = ' '.join(
                char_img_obj.attrib['alt'].strip().split(', '))
            await working_response.delete()
            question_embed = discord.Embed(color=0x1d439b)
            question_embed.set_image(url=char_img)
            question_embed.set_footer(text='You have 30 seconds to guess it.')
            question_embed.set_author(name=anime_title,
                                      icon_url=anime_cover,
                                      url=char_img)
            kud_reward = None
            name_split = char_name.split()
            for name_piece in name_split:
                if kud_reward is None:
                    kud_reward = len(name_piece)
                else:
                    if kud_reward >= len(name_piece):
                        kud_reward = len(name_piece)
            if hint:
                kud_reward = kud_reward // 2
                scrambled_name = scramble(char_name)
                question_embed.description = f'Name: {scrambled_name}'
            await pld.msg.channel.send(embed=question_embed)

            def check_answer(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                if pld.msg.channel.id == msg.channel.id:
                    if msg.content.lower() in char_name.lower().split():
                        correct = True
                    elif msg.content.lower() == char_name.lower():
                        correct = True
                    else:
                        correct = False
                else:
                    correct = False
                return correct

            try:
                answer_message = await cmd.bot.wait_for('message',
                                                        check=check_answer,
                                                        timeout=30)
                reward_mult = streaks.get(pld.msg.channel.id) or 0
                kud_reward = int(kud_reward * (1 + (reward_mult * 2.25) /
                                               (1.75 + (0.03 * reward_mult))))
                await cmd.db.add_resource(answer_message.author.id, 'currency',
                                          kud_reward, cmd.name, pld.msg)
                author = answer_message.author.display_name
                currency = cmd.bot.cfg.pref.currency
                streaks.update({pld.msg.channel.id: reward_mult + 1})
                win_title = f'🎉 Correct, {author}, it was {char_name}. You won {kud_reward} {currency}!'
                win_embed = discord.Embed(color=0x77B255, title=win_title)
                await pld.msg.channel.send(embed=win_embed)
            except asyncio.TimeoutError:
                if pld.msg.channel.id in streaks:
                    streaks.pop(pld.msg.channel.id)
                timeout_title = f'🕙 Time\'s up! It was {char_name} from {anime_title}...'
                timeout_embed = discord.Embed(color=0x696969,
                                              title=timeout_title)
                await pld.msg.channel.send(embed=timeout_embed)
        except (IndexError, KeyError):
            grab_error = error('I failed to grab a character, try again.')
            await pld.msg.channel.send(embed=grab_error)
        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is already one ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
Esempio n. 6
0
async def hangman(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    cache_key = 'hangman_word_cache'
    word_cache = await cmd.db.cache.get_cache(cache_key) or {}
    if not word_cache:
        dict_docs = await cmd.db[cmd.db.db_nam].DictionaryData.find({}).to_list(None)
        for ddoc in dict_docs:
            word = ddoc.get('word')
            if len(word) > 3 and len(word.split(' ')) == 1:
                word_cache.update({word: ddoc.get('description')})
        await cmd.db.cache.set_cache(cache_key, word_cache)
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        set_ongoing(cmd.name, pld.msg.channel.id)
        words = list(word_cache.keys())
        gallows = Gallows(secrets.choice(words))
        word_description = word_cache.get(gallows.word)
        kud_reward = gallows.count
        author = pld.msg.author.display_name
        hangman_resp = generate_response(gallows)
        hangman_msg = await pld.msg.channel.send(embed=hangman_resp)

        def check_answer(msg):
            """
            Checks if the answer message is correct.
            :param msg: The message to check.
            :type msg: discord.Message
            :return:
            :rtype:
            """
            if pld.msg.channel.id != msg.channel.id:
                return
            if pld.msg.author.id != msg.author.id:
                return
            if len(msg.content) == 1:
                if msg.content.isalpha():
                    correct = True
                else:
                    correct = False
            else:
                correct = False
            return correct

        finished = False
        timeout = False
        while not timeout and not finished:
            try:
                answer_message = await cmd.bot.wait_for('message', check=check_answer, timeout=30)
                letter = answer_message.content.lower()
                if letter in gallows.word:
                    if letter not in gallows.right_letters:
                        gallows.right_letters.append(letter)
                else:
                    if letter.upper() not in gallows.wrong_letters:
                        gallows.wrong_letters.append(letter.upper())
                        gallows.use_part()
                hangman_msg = await send_hangman_msg(pld.msg, hangman_msg, generate_response(gallows))
                finished = gallows.victory or gallows.dead
            except asyncio.TimeoutError:
                timeout = True
                timeout_title = '🕙 Time\'s up!'
                timeout_embed = discord.Embed(color=0x696969, title=timeout_title)
                timeout_embed.add_field(name=f'It was {gallows.word}.', value=word_description)
                await pld.msg.channel.send(embed=timeout_embed)

        if gallows.dead:
            lose_title = f'💥 Ooh, sorry {author}, it was {gallows.word}'
            final_embed = discord.Embed(color=0xff3300, title=lose_title)
            await pld.msg.channel.send(embed=final_embed)
        elif gallows.victory:
            await cmd.db.add_resource(pld.msg.author.id, 'currency', kud_reward, cmd.name, pld.msg)
            currency = cmd.bot.cfg.pref.currency
            win_title = f'🎉 Correct, {author}, it was {gallows.word}. You won {kud_reward} {currency}!'
            win_embed = discord.Embed(color=0x77B255, title=win_title)
            await pld.msg.channel.send(embed=win_embed)

        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is one already ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
Esempio n. 7
0
async def trivia(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    global streaks
    if await cmd.bot.cool_down.on_cooldown(cmd.name, pld.msg.author):
        timeout = await cmd.bot.cool_down.get_cooldown(cmd.name,
                                                       pld.msg.author)
        on_cooldown = discord.Embed(
            color=0xccffff,
            title=f'❄ On cooldown for another {timeout} seconds.')
        await pld.msg.channel.send(embed=on_cooldown)
        return
    try:
        if not is_ongoing(cmd.name, pld.msg.author.id):
            set_ongoing(cmd.name, pld.msg.author.id)
            allotted_time = 20
            trivia_api_url = 'https://opentdb.com/api.php?amount=1'
            cat_chosen = False
            if pld.args:
                catlook = pld.args[-1].lower()
                for cat in categories:
                    cat_alts = categories.get(cat)
                    if catlook in cat_alts:
                        trivia_api_url += f'&category={cat}'
                        cat_chosen = True
                        break
                diflook = pld.args[0].lower()
                if diflook in ['easy', 'medium', 'hard']:
                    trivia_api_url += f'&difficulty={diflook}'
                    cat_chosen = True
            async with aiohttp.ClientSession() as session:
                async with session.get(trivia_api_url) as number_get:
                    number_response = await number_get.read()
                    try:
                        data = json.loads(number_response).get('results')[0]
                    except json.JSONDecodeError:
                        if is_ongoing(cmd.name, pld.msg.author.id):
                            del_ongoing(cmd.name, pld.msg.author.id)
                        decode_error = error('Could not retrieve a question.')
                        await pld.msg.channel.send(embed=decode_error)
                        return
            await cmd.bot.cool_down.set_cooldown(cmd.name, pld.msg.author, 30)
            question = data['question']
            question = ftfy.fix_text(question)
            question = re.sub(r'([*_~`])', r'\\\1',
                              question)  # escape markdown formatting
            category = data['category']
            correct_answer = data['correct_answer']
            correct_answer = ftfy.fix_text(correct_answer)
            incorrect_answers = data['incorrect_answers']
            difficulty = data['difficulty']
            reward_mult = streaks.get(
                pld.msg.author.id) or 0 if not cat_chosen else 0
            kud_reward = int(
                (awards.get(difficulty) or '10') *
                (1 + (reward_mult * 2.25) / (1.75 + (0.03 * reward_mult))))
            choice_list = [correct_answer] + incorrect_answers
            choice_list = shuffle_questions(choice_list)
            choice_number = 0
            choice_lines = []
            for choice in choice_list:
                choice_number += 1
                choice_line = f'[{choice_number}] {choice}'
                choice_lines.append(choice_line)
            choice_text = '\n'.join(choice_lines)
            choice_text = ftfy.fix_text(choice_text)
            if difficulty == 'easy':
                starter = 'An'
            else:
                starter = 'A'
            question_embed = discord.Embed(color=0xF9F9F9,
                                           title='❔ Here\'s a question!')
            question_embed.description = f'{starter} {difficulty} one from the {category} category.'
            question_embed.add_field(name='Question',
                                     value=question,
                                     inline=False)
            question_embed.add_field(name='Choices',
                                     value=f'```py\n{choice_text}\n```',
                                     inline=False)
            question_embed.set_footer(
                text='Input the number of your chosen answer.')
            question_embed.set_author(name=pld.msg.author.display_name,
                                      icon_url=user_avatar(pld.msg.author))
            await pld.msg.channel.send(embed=question_embed)

            def check_answer(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                if pld.msg.channel.id != msg.channel.id:
                    return
                if pld.msg.author.id != msg.author.id:
                    return
                if msg.content.isdigit():
                    if abs(int(msg.content)) <= len(choice_lines):
                        return True
                    else:
                        return
                elif msg.content.title() in choice_list:
                    return True

            try:
                answer_message = await cmd.bot.wait_for('message',
                                                        check=check_answer,
                                                        timeout=allotted_time)
                try:
                    answer_index = int(answer_message.content) - 1
                except ValueError:
                    answer_index = None
                correct_index = get_correct_index(choice_list, correct_answer)
                if answer_index == correct_index or answer_message.content.lower(
                ) == correct_answer.lower():
                    if cat_chosen:
                        streaks.update(
                            {pld.msg.author.id: reward_mult + 0.005})
                    else:
                        streaks.update({pld.msg.author.id: reward_mult + 1})
                    await cmd.db.add_resource(answer_message.author.id,
                                              'currency', kud_reward, cmd.name,
                                              pld.msg)
                    author = answer_message.author.display_name
                    currency = cmd.bot.cfg.pref.currency
                    win_title = f'🎉 Correct, {author}, it was {correct_answer}. You won {kud_reward} {currency}!'
                    final_embed = discord.Embed(color=0x77B255,
                                                title=win_title)
                else:
                    if pld.msg.author.id in streaks:
                        streaks.pop(pld.msg.author.id)
                    lose_title = f'💣 Ooh, sorry, it was {correct_answer}...'
                    final_embed = discord.Embed(color=0x262626,
                                                title=lose_title)
                await pld.msg.channel.send(embed=final_embed)
            except asyncio.TimeoutError:
                if pld.msg.author.id in streaks:
                    streaks.pop(pld.msg.author.id)
                timeout_title = f'🕙 Time\'s up! It was {correct_answer}...'
                timeout_embed = discord.Embed(color=0x696969,
                                              title=timeout_title)
                await pld.msg.channel.send(embed=timeout_embed)
            if is_ongoing(cmd.name, pld.msg.author.id):
                del_ongoing(cmd.name, pld.msg.author.id)
        else:
            ongoing_error = error('There is already one ongoing.')
            await pld.msg.channel.send(embed=ongoing_error)
    except Exception:
        if is_ongoing(cmd.name, pld.msg.author.id):
            del_ongoing(cmd.name, pld.msg.author.id)
        raise
Esempio n. 8
0
async def sequencegame(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if is_ongoing(cmd.name, pld.msg.author.id):
        ongoing_error = error('There is already one ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
        return
    try:
        set_ongoing(cmd.name, pld.msg.author.id)
        chosen = [secrets.choice(first_symbols) for _ in range(4)]
        title = f'🎯 {pld.msg.author.display_name}, you have 90 seconds for each attempt.'
        desc = f'Symbols you can use: {"".join(first_symbols)}'
        start_embed = discord.Embed(color=0xf9f9f9)
        start_embed.add_field(name=title, value=desc)
        await pld.msg.channel.send(embed=start_embed)

        def answer_check(msg):
            """

            :param msg:
            :type msg:
            :return:
            :rtype:
            """
            if pld.msg.author.id != msg.author.id:
                return
            if pld.msg.channel.id != msg.channel.id:
                return

            message_args = [
                char for char in msg.content if char in all_symbols
            ]
            if len(message_args) != 4:
                return

            for arg in message_args:
                if arg in all_symbols:
                    return True

        finished = False
        victory = False
        timeout = False
        tries = 0
        while not finished and tries < 6:
            try:
                answer = await cmd.bot.wait_for('message',
                                                check=answer_check,
                                                timeout=90)
                correct, results = check_answer(answer.content, chosen)
                tries += 1
                if correct:
                    finished = True
                    victory = True
                    currency = cmd.bot.cfg.pref.currency
                    await cmd.db.add_resource(answer.author.id, 'currency', 50,
                                              cmd.name, pld.msg)
                    win_title = f'🎉 Correct, {answer.author.display_name}. You won 50 {currency}!'
                    win_embed = discord.Embed(color=0x77B255, title=win_title)
                    await pld.msg.channel.send(embed=win_embed)
                else:
                    attempt_title = f'💣 {answer.author.display_name} {tries}/6: {"".join(results)}'
                    attempt_embed = discord.Embed(color=0x262626,
                                                  title=attempt_title)
                    await pld.msg.channel.send(embed=attempt_embed)
            except asyncio.TimeoutError:
                finished = True
                victory = False
                timeout = True
                timeout_title = f'🕙 Time\'s up {pld.msg.author.display_name}! It was {"".join(chosen)}'
                timeout_embed = discord.Embed(color=0x696969,
                                              title=timeout_title)
                await pld.msg.channel.send(embed=timeout_embed)

        if not victory and not timeout:
            lose_title = f'💥 Ooh, sorry {pld.msg.author.display_name}, it was {"".join(chosen)}'
            final_embed = discord.Embed(color=0xff3300, title=lose_title)
            await pld.msg.channel.send(embed=final_embed)
        del_ongoing(cmd.name, pld.msg.author.id)
    except Exception:
        if is_ongoing(cmd.name, pld.msg.author.id):
            del_ongoing(cmd.name, pld.msg.author.id)
        raise
Esempio n. 9
0
async def vnchargame(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        try:
            set_ongoing(cmd.name, pld.msg.channel.id)
            vndb_icon = 'https://i.imgur.com/YrK5tQF.png'
            wait_embed = discord.Embed(color=0x1d439b)
            wait_embed.set_author(name='Hunting for a good specimen...',
                                  icon_url=vndb_icon)
            working_response = await pld.msg.channel.send(embed=wait_embed)
            if pld.args:
                if pld.args[0].lower() == 'hint':
                    hint = True
                else:
                    hint = False
            else:
                hint = False
            vn_url_list = []
            vn_top_list_url = 'https://vndb.org/v/all?q=;fil=tagspoil-0;rfil=;o=d;s=pop;p=1'
            async with aiohttp.ClientSession() as session:
                async with session.get(vn_top_list_url) as vn_top_list_session:
                    vn_top_list_html = await vn_top_list_session.text()
            vn_top_list_data = html.fromstring(vn_top_list_html)
            list_items = vn_top_list_data.cssselect('.tc1')
            for list_item in list_items:
                if 'href' in list_item[0].attrib:
                    vn_url = list_item[0].attrib['href']
                    if vn_url.startswith(
                            '/v') and not vn_url.startswith('/v/'):
                        vn_url = f'https://vndb.org{vn_url}'
                        vn_url_list.append(vn_url)
            vn_url_choice = secrets.choice(vn_url_list)
            async with aiohttp.ClientSession() as session:
                async with session.get(
                        f'{vn_url_choice}/chars') as vn_details_page_session:
                    vn_details_page_html = await vn_details_page_session.text()
            vn_details_page = html.fromstring(vn_details_page_html)
            vn_title = vn_details_page.cssselect(
                '.stripe')[0][0][1].text_content().strip()
            vn_image = vn_details_page.cssselect('.vnimg')[0][0].attrib['src']
            character_objects = vn_details_page.cssselect('.chardetails')[:8]
            character = secrets.choice(character_objects)
            char_img = character[0][0].attrib['src']
            char_name = character[1][0][0][0][0].text.strip()
            await working_response.delete()
            question_embed = discord.Embed(color=0x225588)
            question_embed.set_image(url=char_img)
            question_embed.set_footer(text='You have 30 seconds to guess it.')
            question_embed.set_author(name=vn_title,
                                      icon_url=vn_image,
                                      url=char_img)
            kud_reward = None
            name_split = char_name.split()
            for name_piece in name_split:
                if kud_reward is None:
                    kud_reward = len(name_piece)
                else:
                    if kud_reward >= len(name_piece):
                        kud_reward = len(name_piece)
            if hint:
                kud_reward = kud_reward // 2
                scrambled_name = scramble(char_name)
                question_embed.description = f'Name: {scrambled_name}'
            await pld.msg.channel.send(embed=question_embed)

            def check_answer(msg):
                """

                :param msg:
                :type msg:
                :return:
                :rtype:
                """
                if pld.msg.channel.id == msg.channel.id:
                    if msg.content.lower() in char_name.lower().split():
                        correct = True
                    elif msg.content.lower() == char_name.lower():
                        correct = True
                    else:
                        correct = False
                else:
                    correct = False
                return correct

            try:
                answer_message = await cmd.bot.wait_for('message',
                                                        check=check_answer,
                                                        timeout=30)
                reward_mult = streaks.get(pld.msg.channel.id) or 0
                kud_reward = int(kud_reward * (1 + (reward_mult * 2.25) /
                                               (1.75 + (0.03 * reward_mult))))
                await cmd.db.add_resource(answer_message.author.id, 'currency',
                                          kud_reward, cmd.name, pld.msg)
                author = answer_message.author.display_name
                currency = cmd.bot.cfg.pref.currency
                streaks.update({pld.msg.channel.id: reward_mult + 1})
                win_title = f'🎉 Correct, {author}, it was {char_name}. You won {kud_reward} {currency}!'
                win_embed = discord.Embed(color=0x77B255, title=win_title)
                await pld.msg.channel.send(embed=win_embed)
            except asyncio.TimeoutError:
                if pld.msg.channel.id in streaks:
                    streaks.pop(pld.msg.channel.id)
                timeout_title = f'🕙 Time\'s up! It was {char_name} from {vn_title}...'
                timeout_embed = discord.Embed(color=0x696969,
                                              title=timeout_title)
                await pld.msg.channel.send(embed=timeout_embed)
        except (IndexError, KeyError):
            grab_error = error('I failed to grab a character, try again.')
            await pld.msg.channel.send(embed=grab_error)
        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is already one ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
Esempio n. 10
0
async def connectfour(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        set_ongoing(cmd.name, pld.msg.channel.id)
        competitor, curr_turn = None, pld.msg.author
        color = pld.args[0][0].lower() if pld.args else None
        player, bot = ('b', 'r') if color == 'b' else ('r', 'b')
        if pld.msg.mentions:
            if pld.msg.mentions[
                    0].id != pld.msg.author.id and not pld.msg.mentions[0].bot:
                competitor = bot
                bot = None
            else:
                ender = 'another bot' if pld.msg.mentions[0].bot else 'yourself'
                self_embed = error(f'You can\'t play against {ender}.')
                await pld.msg.channel.send(embed=self_embed)
                return

        board = ConnectFourBoard()
        user_av = user_avatar(pld.msg.author)
        board_resp = generate_response(user_av, pld.msg.author, board.make)
        board_msg = await pld.msg.channel.send(embed=board_resp)
        [await board_msg.add_reaction(num) for num in nums]

        def check_emote(reac, usr):
            """
            Checks for a valid message reaction.
            :param reac: The reaction to validate.
            :type reac: discord.Reaction
            :param usr: The user who reacted to the message.
            :type usr: discord.Member
            :return:
            :rtype: bool
            """
            same_author = usr.id == curr_turn.id
            same_message = reac.message.id == board_msg.id
            valid_reaction = str(reac.emoji) in nums
            return same_author and same_message and valid_reaction

        finished, winner, win = False, None, False
        last_bot_move = 3
        while not finished:
            try:
                ae, au = await cmd.bot.wait_for('reaction_add',
                                                check=check_emote,
                                                timeout=30)
                await check_emotes(cmd.bot, ae.message)
                piece = player if curr_turn.id == pld.msg.author.id else competitor
                opponent = pld.msg.guild.me if bot else pld.msg.mentions[0]
                next_player = pld.msg.author if curr_turn != pld.msg.author else opponent
                board_resp = generate_response(
                    user_av, next_player,
                    board.edit(nums.index(str(ae.emoji)), piece))
                board_msg = await send_board_msg(pld.msg, board_msg,
                                                 board_resp)
                full, winner, win = board.winner
                finished = win or full
                if not finished:
                    if not competitor:
                        # Bot takes turn
                        await asyncio.sleep(2)
                        last_bot_move = bot_choice = board.bot_move(
                            last_bot_move)
                        board_resp = generate_response(
                            user_av, pld.msg.author,
                            board.edit(bot_choice, bot))
                        board_msg = await send_board_msg(
                            pld.msg, board_msg, board_resp)
                        full, winner, win = board.winner
                        finished = win or full
                    else:
                        if curr_turn == pld.msg.author:
                            curr_turn = pld.msg.mentions[0]
                        else:
                            curr_turn = pld.msg.author

            except asyncio.TimeoutError:
                timeout_title = f'🕙 Time\'s up {curr_turn.display_name}!'
                timeout_embed = discord.Embed(color=0x696969,
                                              title=timeout_title)
                await pld.msg.channel.send(embed=timeout_embed)
                if is_ongoing(cmd.name, pld.msg.channel.id):
                    del_ongoing(cmd.name, pld.msg.channel.id)
                return

        if winner:
            if bot:
                if winner == getattr(board, player):
                    color, icon, resp = 0x3B88C3, '💎', 'You win'
                else:
                    color, icon, resp = 0x292929, '💣', 'You lose'
            else:
                color, icon, resp = 0x3B88C3, '💎', f'{curr_turn.display_name} wins'
        else:
            color, icon, resp = 0xFFCC4D, '🔥', 'It\'s a draw'
        response = discord.Embed(color=color, title=f'{icon} {resp}!')
        await pld.msg.channel.send(embed=response)
        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is already one ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
Esempio n. 11
0
async def unscramblegame(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    cache_key = 'unscramble_word_cache'
    word_cache = await cmd.db.cache.get_cache(cache_key) or {}
    if not word_cache:
        dict_docs = await cmd.db[cmd.db.db_nam
                                 ].DictionaryData.find({}).to_list(None)
        for ddoc in dict_docs:
            word = ddoc.get('word')
            if len(word) > 3 and len(word.split(' ')) == 1:
                word_cache.update({word: ddoc.get('description')})
        await cmd.db.cache.set_cache(cache_key, word_cache)
    if not is_ongoing(cmd.name, pld.msg.channel.id):
        set_ongoing(cmd.name, pld.msg.channel.id)
        words = list(word_cache.keys())
        word_choice = secrets.choice(words)
        word_description = word_cache.get(word_choice)
        kud_reward = len(word_choice)
        scrambled = scramble(word_choice.title())
        question_embed = discord.Embed(color=0x3B88C3,
                                       title=f'🔣 {scrambled}')
        await pld.msg.channel.send(embed=question_embed)

        def check_answer(msg):
            """
            Checks if the answer message is correct.
            :param msg: The message to check.
            :type msg: discord.Message
            :return:
            :rtype:
            """
            if pld.msg.channel.id == msg.channel.id:
                if msg.content.lower() == word_choice.lower():
                    correct = True
                else:
                    correct = False
            else:
                correct = False
            return correct

        try:
            answer_message = await cmd.bot.wait_for('message',
                                                    check=check_answer,
                                                    timeout=30)
            await cmd.db.add_resource(answer_message.author.id, 'currency',
                                      kud_reward, cmd.name, pld.msg)
            author = answer_message.author.display_name
            currency = cmd.bot.cfg.pref.currency
            win_title = f'🎉 Correct, {author}, it was {word_choice}. You won {kud_reward} {currency}!'
            win_embed = discord.Embed(color=0x77B255, title=win_title)
            await pld.msg.channel.send(embed=win_embed)
        except asyncio.TimeoutError:
            timeout_title = '🕙 Time\'s up!'
            timeout_embed = discord.Embed(color=0x696969, title=timeout_title)
            timeout_embed.add_field(name=f'It was {word_choice.lower()}.',
                                    value=word_description)
            await pld.msg.channel.send(embed=timeout_embed)
        if is_ongoing(cmd.name, pld.msg.channel.id):
            del_ongoing(cmd.name, pld.msg.channel.id)
    else:
        ongoing_error = error('There is one already ongoing.')
        await pld.msg.channel.send(embed=ongoing_error)
async def exportincidents(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    file = None
    if pld.msg.author.permissions_in(pld.msg.channel).manage_messages:
        if not is_ongoing(cmd.name, pld.msg.guild.id):
            set_ongoing(cmd.name, pld.msg.guild.id)
            icore = get_incident_core(cmd.db)
            response, target = None, None
            identifier, incidents = None, None
            title = '🗃️ Gathering all '
            if pld.args:
                if len(pld.args) == 2:
                    identifier = pld.args[0].lower()
                    if (pld.msg.mentions or identifier
                            == 'variant') and identifier in identifiers:
                        if identifier == 'moderator':
                            target = pld.msg.mentions[0]
                            incidents = await icore.get_all_by_mod(
                                pld.msg.guild.id, target.id)
                            title += f'incidents issued by {target.name}.'
                        elif identifier == 'target':
                            target = pld.msg.mentions[0]
                            incidents = await icore.get_all_by_target(
                                pld.msg.guild.id, target.id)
                            title += f'incidents for {target.name}.'
                        else:
                            target = pld.args[1].lower()
                            if target in variants:
                                incidents = await icore.get_all_by_variant(
                                    pld.msg.guild.id, target)
                                title += f'{target} incidents.'
                            else:
                                response = error('Invalid variant.')
                    else:
                        response = error('Invalid identifier.')
            else:
                incidents = await icore.get_all(pld.msg.guild.id)
                title += 'incidents.'
            if not response:
                if incidents:
                    response = discord.Embed(color=0x226699, title=title)
                    response.set_footer(
                        text='A text file will be sent to you shortly.')
                    if identifier:
                        modifier = f'{identifier.title()}: {target.title() if identifier == "variant" else target.name}'
                    else:
                        modifier = 'All'
                    file_name = make_export_file(pld.msg.guild.name, incidents,
                                                 modifier)
                    file = discord.File(f'cache/{file_name}', file_name)
                else:
                    if identifier:
                        response = error(
                            f'No incidents found for that {identifier}.')
                    else:
                        response = error('This server has no incidents.')
        else:
            response = error('There is already one ongoing.')
    else:
        response = denied('Access Denied. Manage Messages needed.')
    if is_ongoing(cmd.name, pld.msg.guild.id):
        del_ongoing(cmd.name, pld.msg.guild.id)
    await pld.msg.channel.send(embed=response)
    if file:
        try:
            await pld.msg.author.send(file=file)
        except (discord.NotFound, discord.Forbidden):
            denied_response = error(
                'I was unable to DM you, please adjust your settings.')
            await pld.msg.channel.send(pld.msg.author.mention,
                                       embed=denied_response)