Exemple #1
0
def view_profile(message: Message):
    users = check.users(message,
                        amount=1,
                        delete_duplicates=True,
                        must_be_participant=False)
    user: User = message.author
    if users:
        if isParticipant(message.author.id) and not isParticipant(users[0]):
            return [
                Mailbox().respond(
                    "I am sorry! To prevent any accidental spoilers, you cannot view the profile of dead players.",
                    True)
            ]
        user = message.channel.guild.get_member(users[0])
    model = ProfileModel.get_or_insert(user)
    em = Embed(
        title=f'Profile of {user.display_name}',
        description=model.bio,
    )
    em.set_author(name=user.display_name, icon_url=user.avatar_url)
    em.add_field(name="Age", value=str(model.display_age))
    em.add_field(name="Gender", value=model.gender)
    em.add_field(name="Credits", value=get_credits(user.id))
    em.add_field(name="Referral score", value=gen_get(user.id, 'refer_score'))
    if get_user(user.id)[4] > 0:
        em.add_field(name="Roulette Highscore", value=get_user(user.id)[4])
    return [
        Mailbox().embed(em, destination=message.channel.id, temporary=True)
    ]
def ignite(user_id):
    """This function ignites all powdered players that aren't pyromancer.
    The function assumes the player is a participant and has the correct role, so make sure to have filtered this out already.
    The function returns a Mailbox.

    user_id -> the player who ignites all powdered players"""

    uses = int(db_get(user_id,'uses'))
    if uses < 1:
        return Mailbox().respond("I am sorry! You currently cannot ignite anyone!",True)
    db_set(user_id,'uses',uses - 1)

    user_role = db_get(user_id,'role')
    user_channel = db_get(user_id,'channel')
    user_undead = int(db_get(user_id,'undead'))

    if user_undead == 1:
        answer = Mailbox().log("<@{}>, an undead **{}**, has pretended to ignite all powdered players.".format(user_id,user_role))
        answer.dm("Hey, you are undead, so your power won\'t work. But at least this won\'t blow your cover!",user_id)
        return answer.msg("Okay! All powdered players will die tomorrow.",user_channel)

    # Ignite all living players.
    for user in db.player_list(True,True):
        if db.isParticipant(user) and db_get(user,'role') != 'Pyromancer':
            db.add_kill(int(user),'Pyromancer',user_id)

    answer = Mailbox().log("The **{}** <@{}> has ignited all powdered players!".format(user_role,user_id))
    return answer.msg("Okay! All powdered players will die tomorrow.",user_channel)
Exemple #3
0
def users(message,amount = -1, delete_duplicates = True, must_be_participant = False):
    """Return the requested amount of user ids in a list. If the amount is -1, all users are given.

    Keyword arguments:
    message -> the Discord message to inspect
    amount -> the wanted amount of users in a list
    delete_duplicates -> filter out users that are mentioned twice in the message
    """
    user_table = [person.id for person in message.mentions]

    for argument in message.content.split(' '):
        response = emoji_to_player(argument)

        if response != None:
            user_table.append(int(response))

    if must_be_participant == True:
        for user in user_table:
            if not isParticipant(user):
                user_table.remove(user)

    if delete_duplicates == True:
        user_table = list(set(user_table))

    if max(amount,1) > len(user_table):
        return False

    if amount == -1:
        return user_table

    return [user_table[i] for i in range(amount)]
def flute_victory():
    """This function returns true if the flute players have won."""
    for user in db.player_list():
        if db.isParticipant(user):
            if db.db_get(user,'role') != 'Flute Player' and db.db_get(user,'enchanted') == 0:
                return False
    return True
def test_database():
    reset.reset(True)
    assert db.count_categories() == 0
    assert db.get_category() == None
    assert db.get_columns() == []
    assert db.poll_list() == []
    db.signup(1, 'Randium003', u':smirk:')
    assert db.get_user(1) == (1, u'Randium003', u':smirk:', 0, game_log,
                              'Spectator', 'Spectator', 0, 1, 0, 0, 0, 0, 0, 0,
                              0, 0, -1, 0, '', 0, 0, 0)
    assert db.db_get(1, 'channel') == game_log
    assert db.isParticipant(1) == False
    assert db.isParticipant(1, True) == True
    assert db.isParticipant(2) == False
    assert db.isParticipant(2, True) == False
    db.db_set(1, 'frozen', 1)
    assert db.poll_list() == [(1, u':smirk:', 1, 0)]

    db.add_category('24')
    assert db.count_categories() == 1
    assert db.get_category() == 24
    assert db.get_columns() == [(1, )]
    assert db.channel_get('1234555') == None
    db.add_channel('1234555', 1)
    assert db.get_category() == 24
    db.add_channel('12211', 1)
    assert db.get_category() == 24
    assert db.channel_get('1234555') == (u'1234555', u'1', u'0')
    assert db.channel_change_all(1, 0, 1) == [u'1234555', u'12211']
    assert db.channel_get('1234555') == (u'1234555', u'1', u'1')
    assert db.channel_get('12211') == (u'12211', u'1', u'1')
    db.set_user_in_channel('1234555', 1, 2)
    assert db.channel_get('1234555') == (u'1234555', u'1', u'2')
    assert db.channel_get('1234555', 1) == '2'
    assert db.channel_change_all(1, 2, 3) == [u'1234555']
    assert db.unabduct(1) == [u'1234555']
    db.signup(420, "BenTechy66", ":poop:")
    assert db.channel_get('12211') == (u'12211', u'1', u'1', u'0')
    assert db.freeze('1') == [u'1234555', u'12211']
    assert db.abduct('420') == []

    for i in range(max_channels_per_category - 2):
        assert db.get_category() == 24
        db.add_channel(10 * i, 608435446804 + 7864467 * i)
    assert db.count_categories() == 1
    assert db.get_category() == None
    reset.reset(True)
Exemple #6
0
def freeze_all(user_id):
    """This function allows the ice king to potentially freeze all their guessed players.
    The function assumes the ice king is a participant, so make sure to have filtered this out already.
    The function returns a Mailbox.

    Keyword arguments:
    user_id -> the ice king's id"""

    uses = int(db_get(user_id,'uses'))
    if uses < 1:
        return Mailbox().respond("I am sorry! You currently don't have the ability to submit a freezing list!",True)
    db_set(user_id,'uses',uses - 1)

    user_channel = int(db_get(user_id,'channel'))
    user_undead = int(db_get(user_id,'undead'))
    correct = 0
    incorrect = 0

    for frozone in db.get_freezers(user_id):
        if not db.isParticipant(frozone[0]) or int(db_get(frozone[0],'abducted')) == 1:
            db.delete_freezer(user_id,frozone[0])
        elif frozone[1] != db_get(frozone[0],'role'):
            incorrect += 1
        else:
            correct += 1

    if user_undead == 1:
        answer = Mailbox().msg("You have submitted a list that contains {} players. The result was **unsuccessful**. ".format(correct+incorrect),user_channel)
        answer.msg_add("This means that at least one role was incorrect!")
        answer.log("The **Undead** <@{}> has pretended to submit a freeze list.".format(user_id))
        answer.dm("Hey, you're **Undead**, so this list would've failed anyway - but this helps a little to keep up your cover! 😉",user_id)
        return answer

    if incorrect > 0:
        answer = Mailbox().msg("You have submitted a list that contains {} players. The result was **unsuccessful**. ".format(correct+incorrect),user_channel)
        answer.msg_add("This means that at least one role was incorrect!")
        answer.log("The **Ice King** <@{}> has submitted an **unsuccessful** freeze list. ".format(user_id))
        answer.log_add("The list contained {} guesses, of which {} were correct.".format(incorrect+correct,correct))
        return answer

    # This will execute if all users on the list are correct.
    answer = Mailbox().msg("You have submitted a list that contains {} players. The result was **successful**!\n".format(correct),user_channel)
    if correct > 4:
        answer.msg_add("Congratulations! You guessed them all correctly! ").msg_react('🎉')
    answer.msg_add("Your guessed users will now be frozen.")


    for supersuit in db.get_freezers(user_id):
        db_set(supersuit[0],'frozen',1)
        db.delete_freezer(user_id,supersuit[0])

        for channel_id in db.freeze(user_id):
            answer.edit_cc(channel_id,supersuit[0],2)

    # TODO: Give players access to frozen realm.

    return answer
def white_wolf_victory():
    """This function returns true if the white werewolf has won."""
    winner = 0
    for user in db.player_list():
        if db.isParticipant(user):
            if winner > 0:
                return False
            if db.db_get(user,'role') != 'White Werewolf':
                return False
            winner += 1
    return True
Exemple #8
0
def process(message, isGameMaster=False, isAdmin=False, isPeasant=False):
    user_id = message.author.id
    message_channel = message.channel.id

    help_msg = "**List of commands:**\n"

    args = message.content.split(' ')

    # =============================================================
    #
    #                         BOT COMMANDS
    #
    # =============================================================
    if isPeasant == True:

        if check.is_command(message, ['success'], False, unip):
            token = args[1]
            choice = args[2]

            if box.token_status(token) != 1:
                return [Mailbox().respond("Wrong status, buddy.")]

            data = box.get_token_data(token)
            given_options = [int(data[3]), int(data[4]), int(data[5])]

            if int(choice) not in given_options:
                return [
                    Mailbox().respond("Invalid choice!", True).spam(
                        "A webhook has given an invalid bug. This means one of the following two things;\n1. There's bug;\n2. Someone's trying to hack the bots through a webhook.\n\nBoth are not good."
                    )
                ]

            box.add_choice(token, choice)
            invt.take_item(int(box.get_token_data(token)[1]), int(choice[1:4]),
                           int(choice[4:7]))
            return [
                Mailbox().respond("Got it! *(I hope.)* Thanks.",
                                  True).thank(box.get_token_data(token)[11])
            ]

    # =============================================================
    #
    #                         ADMINISTRATOR
    #
    # =============================================================
    if isAdmin == True:
        help_msg += "\n __Admin commands:__\n"

        if is_command(message, ['gift']):
            target = check.users(message)
            if not target:
                return [
                    Mailbox().respond(
                        "No target provided! Please provide a target.", True)
                ]
            answer = Mailbox()

            for user_id in target:
                answer.gift(user_id)
            return [answer]

        if is_command(message, ['botanswer']):
            return [
                Mailbox().respond(
                    "Sounds pretty cool! How about you did something about it? *cough cough*"
                )
            ]

    elif is_command(message, ['delete_category', 'start']):
        return [
            Mailbox().respond(PERMISSION_MSG.format("Administrator"), True)
        ]

    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:
        help_msg += "\n__Game Master commands:__\n"

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Game Master"), True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):
        help_msg += "\n__Participant commands:__\n"

        user_undead = int(db_get(user_id, 'undead'))

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Participant"), True)]

    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    help_msg += '\n\n'

    if is_command(message, ['lead']):
        number = check.numbers(message)
        if not number:
            return [Mailbox().respond(gen.gain_leaderboard(user_id), True)]
        return [
            Mailbox().respond(gen.gain_leaderboard(user_id, max(number)), True)
        ]
    if is_command(message, ['lead'], True):
        msg = "**Usage:** Gain a list of the most active users on the server.\n\n`" + prefix + "leaderboard <number>`\n\n"
        msg += "**Example:** `" + prefix + "lead 10`.\nThe number is optional, and doesn't have to be given."
    help_msg += "`" + prefix + "leaderboard` - See an activity leaderboard.\n"

    if is_command(message, ['refer']):
        target = check.users(message, 1)
        if target[0] == user_id:
            return [
                Mailbox().respond("Sorry, bud! You cannot refer yourself.")
            ]
        if not target:
            return [
                Mailbox().respond(
                    "No target provided! Please provide us with a target!")
            ]
        if gen.update_refer(user_id, target[0]) == True:
            return [
                Mailbox().respond(
                    "Alright! Expect you and <@{}> to have some extra luck getting a lootbox soon... ;)"
                    .format(target[0])).gift(user_id).gift(target[0])
            ]
        return [
            Mailbox().respond("**ERROR:** You have already referred someone!")
        ]

    if is_command(message, ['rr', 'roulette', 'suicide']):
        return [roulette.surrender(True), roulette.take_shot(message)]
    if is_command(message, ['rr', 'roulette', 'suicide'], True):
        msg = "**Usage:** Play a game of Russian roulette!\n\n`" + prefix + "rr`\n\nTry it out! It's fun."
        return [Mailbox().respond(msg, True)]
    help_msg += "`" + prefix + "rr` - Play some Russian roulette!\n"

    if is_command(message, ['rs', 'roulscore', 'rscore']):
        target = check.users(message, 1)
        if not target:
            return [roulette.profile(message.author.id)]
        return [roulette.profile(target[0])]
    if is_command(message, ['rs', 'roulscore', 'rscore'], True):
        msg = "**Usage:** Check your current game progress.\n\n`" + prefix + "rs <user>`\n\n"
        msg += "**Example:** `" + prefix + "rs @Randium#6521`\nMentioning a user is optional."
        return [Mailbox().respond(msg, True)]
    help_msg += "`" + prefix + "rs` - See Russian Roulette score.\n"

    if roulette.is_playing(message.author):
        if is_command(message, ['surrender']):
            return [roulette.surrender(False, message.author)]
        if is_command(message, ['surrender'], True):
            msg = "**Usage:** Leave the game if you think you're gonna die.\n\n`" + prefix + "surrender`\n\nLeaving the game counts as a loss, but not as a death."
        help_msg += "`" + prefix + "surrender` - Leave the Russian roulette game.\n"

    # Profile commands
    profile_commands = process_profile(message=message,
                                       is_game_master=isGameMaster,
                                       is_admin=isAdmin,
                                       is_peasant=isPeasant)
    if profile_commands:
        return profile_commands

    help_msg += "\n`" + prefix + "age` - Set your age\n"
    help_msg += "`" + prefix + "bio` - Set your bio\n"
    help_msg += "`" + prefix + "gender` - Set your gender\n"
    help_msg += "`" + prefix + "profile` - View a player's profile\n"

    # --------------------------------------------------------------
    #                          HELP
    # --------------------------------------------------------------
    help_msg += "\n\n*If you have any more questions, feel free to ask any of the Game Masters!*"
    '''help'''
    if is_command(message, ['help']) and is_command(message, ['help'],
                                                    True) == False:
        return [Mailbox().respond(help_msg, True)]
    if is_command(message, ['help'], True):
        answer = Mailbox().respond(
            "Hey there! `" + prefix +
            "help` will give you a list of commands that you can use.")
        answer.respond_add(
            "\nIf you have any questions, feel free to ask any of the Game Masters!"
        )
        return [answer]

    if message.content.startswith(prefix):
        return [
            roulette.surrender(True),
            Mailbox().respond(
                "Sorry bud, couldn't find what you were looking for.", True)
        ]

    return [roulette.surrender(True)]
Exemple #9
0
def process(message, isGameMaster=False, isAdmin=False, isPeasant=False):
    user_id = message.author.id
    message_channel = message.channel.id

    help_msg = "**List of commands:**\n"

    # =============================================================
    #
    #                         BOT COMMANDS
    #
    # =============================================================
    if isPeasant == True:
        pass

    # =============================================================
    #
    #                         ADMINISTRATOR
    #
    # =============================================================
    if isAdmin == True:
        help_msg += "\n __Admin commands:__\n"

    elif is_command(message, ['delete_category', 'start']):
        return [
            Mailbox().respond(PERMISSION_MSG.format("Administrator"), True)
        ]

    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:
        help_msg += "\n__Game Master commands:__\n"

    elif is_command(
            message,
        ['addrole', 'assign', 'day', 'night', 'open_signup', 'whois']):
        return [Mailbox().respond(PERMISSION_MSG.format("Game Master"), True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):
        help_msg += "\n__Participant commands:__\n"

        user_undead = int(db_get(user_id, 'undead'))

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Participant"), True)]

    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    help_msg += '\n\n'

    profile_commands = process_profile(message=message,
                                       is_game_master=isGameMaster,
                                       is_admin=isAdmin,
                                       is_peasant=isPeasant)
    if profile_commands:
        return profile_commands

    help_msg += "`" + prefix + "age` - Set your age\n"
    help_msg += "`" + prefix + "bio` - Set your bio\n"
    help_msg += "`" + prefix + "gender` - Set your gender\n"
    help_msg += "`" + prefix + "profile` - View a player's profilen\n"

    # --------------------------------------------------------------
    #                          HELP
    # --------------------------------------------------------------
    help_msg += "\n\n*If you have any more questions, feel free to ask any of the Game Masters!*"
    '''help'''
    if is_command(message, ['help']) and is_command(message, ['help'],
                                                    True) == False:
        return [Mailbox().respond(help_msg, True)]
    if is_command(message, ['help'], True):
        answer = Mailbox().respond(
            "Hey there! `" + prefix +
            "help` will give you a list of commands that you can use.")
        answer.respond_add(
            "\nIf you have any questions, feel free to ask any of the Game Masters!"
        )
        return [answer]

    if message.content.startswith(prefix):
        return [
            Mailbox().respond(
                "Sorry bud, couldn't find what you were looking for.", True)
        ]

    return []
Exemple #10
0
async def process_message(message,result):
    #if "<@&{}>".format(config.game_master) in message.content:
        #stats.increment_stat("game_master_pings", 1)
        #stats.increment_user_stat(message.author.id, "game_master_pings", 1)

    if db.isParticipant(message.author.id,True,True,True):
        db_set(message.author.id,'activity',0)

    gamelog_channel = client.get_channel(int(config.game_log))
    botspam_channel = client.get_channel(int(config.bot_spam))
    storytime_channel = client.get_channel(int(config.story_time))

    # The temp_msg list is for keeping track of temporary messages for deletion.
    temp_msg = []

    for mailbox in result:

        # If a Mailbox says so, all existing polls will be evaluated.
        if mailbox.evaluate_polls == True:
            for poll in db.get_all_polls():
                # poll.msg_table -> list of message ids
                # poll.blamed -> name of killer
                # poll.purpose -> the reason of the kill

                poll_channel = client.get_channel(int(poll.channel))
                if poll_channel == None:
                    await botspam_channel.send("We got a problem! Could you send these results to the appropriate channel, please?")
                    poll_channel = botspam_channel

                user_table = []
                for msg in poll.msg_table:
                    poll_msg = await poll_channel.get_message(msg)
                    for emoji in poll_msg.reactions:
                        users = await emoji.users().flatten()

                        for person in users:
                            if db.isParticipant(person.id):
                                user_table.append([person.id,emoji.emoji])

                log, result, chosen_emoji = count_votes(user_table,poll.purpose,dy.get_mayor())

                await botspam_channel.send(log)
                await poll_channel.send(result)
                for graveyard in db.get_secret_channels("Graveyard"):
                    await client.get_channel(graveyard).send(result)

                chosen_one = db.emoji_to_player(chosen_emoji)

                if chosen_emoji != '' and chosen_one != None:
                    chosen_one = int(chosen_one)
                    if poll.purpose == 'lynch':
                        db.add_kill(chosen_one,'Innocent')
                    elif poll.purpose == 'Mayor':
                        dy.set_mayor(chosen_one)
                        member = gamelog_channel.guild.get_member(int(chosen_one))
                        if member != None:
                            await member.add_roles(get_role(gamelog_channel.guild.roles, config.mayor), reason="Promoting {} to Mayor".format(member.display_name))
                    elif poll.purpose == 'Reporter':
                        dy.set_reporter(chosen_one)
                        for channel_id in db.get_secret_channels("Reporter"):
                            mailbox.edit_cc(channel_id,chosen_one,1)
                        member = gamelog_channel.guild.get_member(int(chosen_one))
                        if member != None:
                            await member.add_roles(get_role(gamelog_channel.guild.roles, config.reporter), reason="Promoting {} to Reporter".format(member.display_name))
                    elif poll.purpose == 'wolf':
                        db.add_kill(chosen_one,'Werewolf',db.random_wolf())
                    elif poll.purpose == 'cult':
                        db.add_kill(chosen_one,'Cult Leader',db.random_cult())
                    elif poll.purpose == 'thing':
                        db.add_kill(chosen_one,'The Thing','')

        for user_id in mailbox.demotions:
            if user_id == message.author.id and message.guild == gamelog_channel.guild:
                member = message.author
            else:
                member = gamelog_channel.guild.get_member(int(user_id))

            if member != None:
                for role in member.roles:
                    if role.id == config.mayor:
                        await member.remove_roles(role, reason="Demoting the Mayor")
                    if role.id == config.reporter:
                        await member.remove_roles(role, reason="Demoting the Reporter")

        # Create a new shop instance
        for element in mailbox.shops:
            shop_data = db_shop.get_shop_config(element.shop_config)
            i = 1
            j = 0
            emoji_table = []
            page_amount = int(len(shop_data["items"])-1/20)+1


            for item in shop_data["items"]:
                if j % 20 == 0:
                    embed = discord.Embed(title="Shop (Page {}/{})".format(i,page_amount), description=shop_data["shop_description"], color=0x00ff00)

                embed.add_field(name="[{}] {}".format(item["emoji"], item["name"]), value="{} {}\n*{}*\n".format(item["price"], shop_data["currency"], item["description"]), inline=False) # Add item to shop
                emoji_table.append(emojize(item["emoji"]))
                j += 1

                if j % 20 == 0:
                    i += 1
                    response = await client.get_channel(int(element.destination)).send(embed=embed)
                    db_shop.add_shop(response.id)

                    for item in emoji_table:
                        await response.add_reaction(item)
                    emoji_table = []

            if j % 20 != 0:
                response = await client.get_channel(int(element.destination)).send(embed=embed)
                db_shop.add_shop(response.id)

                for item in emoji_table:
                    await response.add_reaction(item)

        # If the Mailbox has a message for the gamelog, this is where it's sent.
        for element in mailbox.gamelog:
            msg = await gamelog_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # If the Mailbox has a message for the botspam, this is where it's sent.
        for element in mailbox.botspam:
            msg = await botspam_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # If the Mailbox has a message for the storytime (in-game announcements) channel, this is where it's sent.
        for element in mailbox.storytime:
            msg = await storytime_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # The messages are sent here if they are a direct message to the one sending a command.
        for element in mailbox.answer:
            msg = await message.channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # The messages that are destined for a specific channel, are sent here.
        for element in mailbox.channel:

            # The following code is sent if the message is an embed.
            if element.embed:
                if element.destination == "spam":
                    msg = await botspam_channel.send(embed=element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
                else:
                    msg = await client.get_channel(int(element.destination)).send(embed=element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
            # The following code is sent if the message is a regular message.
            else:
                msg = await client.get_channel(int(element.destination)).send(element.content)
                for emoji in element.reactions:
                    await msg.add_reaction(emoji)
                if element.temporary == True:
                    temp_msg.append(msg)

        # DMs are sent here.
        for element in mailbox.player:
            member = client.get_user(int(element.destination))
            main_guild = botspam_channel.guild
            if member == None:
                member = main_guild.get_member(int(element.destination))
            if member == None:
                await message.channel.send("Couldn't send a DM to <@{}>!".format(element.destination))
                await botspam_channel.send(
                    "<@{}> has attempted to send a DM to <@{}>, but failed, because we couldn't find the specified user via `client.get_user`.".format(
                        message.author.id, element.destination))
            else:
                try:
                    msg = await member.send(element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
                except discord.errors.Forbidden:
                    botspam_channel.send('I wasn\'t allowed to send a DM to <@{}>! Here\'s the content:'.format(member.id))
                    botspam_channel.send(element.content)
                except Exception:
                    botspam_channel.send('I failed to send a DM to <@{}>! Could somebody send this, please?'.format(member.id))
                    botspam_channel.send(element.content)

        # Settings of existing channels are altered here.
        for element in mailbox.oldchannels:
            # element.channel - channel to be edited;
            # element.victim - person's permission to be changed;
            # element.number - type of setting to set to: see issue #83 for more info.

            print('Editing permissions of {} for channel {}...'.format(element.victim,element.channel))
            channel = client.get_channel(element.channel)
            user = client.get_user(int(element.victim))
            main_guild = botspam_channel.guild
            member = main_guild.get_member(int(element.victim))
            if member == None:
                if user == None:
                    await botspam_channel.send("That\'s problematic! I couldn\'t edit the cc info of <@{0}> *(<#{0}> <@&{0}> ?)*".format(element.victim))
                    print('Unable to locate member {}.'.format(element.victim))
                member = user
            if channel == None:
                await botspam_channel.send('Unable to edit channel <#{0}> *(<@{0}> <@&{0}> ?)*'.format(int(element.victim)))
            elif member != None:
                await remove_all_game_roles(member)
                if element.number == 0:
                    await channel.set_permissions(user, read_messages=False, send_messages=False)
                    try:
                        if int(db_get(member.id,'frozen')) == 0:
                            raise NotImplementedError("This is a purposeful error raise!")
                    except Exception:
                        if db.isParticipant(member.id):
                            await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                        elif db.isParticipant(member.id,True,True):
                            await member.add_roles(get_role(main_guild.roles, config.dead_participant), reason="Updating CC Permissions")
                        elif db.isParticipant(member.id,True,True,True):
                            await member.add_roles(get_role(main_guild.roles, config.suspended), reason="Updating CC Permissions")
                    else:
                        await member.add_roles(get_role(main_guild.roles, config.frozen_participant), reason="Updating CC Permissions")
                elif element.number == 1:
                    await channel.set_permissions(user, read_messages=True, send_messages=True)
                    await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                elif element.number == 2:
                    await channel.set_permissions(user, read_messages=True, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.frozen_participant), reason="Updating CC Permissions")
                elif element.number == 3:
                    await channel.set_permissions(user, read_messages=False, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                elif element.number == 4:
                    await channel.set_permissions(user, read_messages=True, send_messages=False)
                    if db.isParticipant(member.id,False,True):
                        await member.add_roles(get_role(main_guild.roles, config.dead_participant), reason="Updating CC Permissions")
                elif element.number == 5:
                    await channel.set_permissions(user, read_messages=True, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                elif element.number == 6:
                    await channel.set_permissions(user, read_messages=False, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                elif element.number == 7:
                    await channel.set_permissions(user, read_messages=False, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
                elif element.number == 8:
                    await channel.set_permissions(user, read_messages=False, send_messages=False)
                    await member.add_roles(get_role(main_guild.roles, config.suspended), reason="Updating CC Permissions")
                else:
                    await msg.channel.send('Something went wrong! Please contact a Game Master.')
                    return
                if db.isParticipant(element.victim,True,True):
                    db.set_user_in_channel(element.channel,element.victim,element.number)


        # New channels are created here.
        for element in mailbox.newchannels:
            # element.name - name of the channel;
            # element.owner - owner of the channel;
            # element.members - members of the channel
            # element.settlers - members for whom this shall become their home channel
            # element.secret - boolean if the channel is a secret channel

            if element.secret:
                element.owner = client.user.id

            if ' ' not in element.name:

                main_guild = botspam_channel.guild # Find the guild we're in

                if element.owner not in element.members:
                    element.members.append(element.owner)
                for buddy in element.settlers:
                    if buddy not in element.members:
                        msg = """**Warning:** I'm adding settlers to a channel!\nThis is should not be a problem, \
                        but it does at least indicate a flaw in the bot's code. Please, report this to the Game Masters!"""
                        await client.get_channel(message.channel).send(msg)
                        element.members.append(buddy)

                viewers = []
                frozones = []
                abductees = []
                deadies = []

                # Add dead people & spectators to cc
                if not element.secret:
                    for user in [dead_buddy for dead_buddy in db.player_list() if dead_buddy not in db.player_list(True)]:
                        element.members.append(user)

                # Categorize all players
                for user in element.members:
                    member = main_guild.get_member(user)

                    if member == None:
                        await botspam_channel.send("That\'s problematic! I couldn\'t add <@{0}> to a cc. *(<#{0}> <@&{0}> ?)*".format(element.victim))
                        await message.author.send("It doesn't seem like <@{}> is part of the server! I am sorry, I can't add them to your **conspiracy channel**.".format(user))
                    elif db.isParticipant(user,False,True) == True:
                        if int(db_get(user,'abducted')) == 1:
                            abductees.append(member)
                        elif int(db_get(user,'frozen')) == 1:
                            frozones.append(member)
                        elif db.isParticipant(user,False,False) == False:
                            deadies.append(member)
                        else:
                            viewers.append(member)
                    elif db_get(user,'role') == 'Suspended':
                        pass
                    else:
                        deadies.append(member)

                # Delete any potential duplicates
                viewers = list(set(viewers))
                frozones = list(set(frozones))
                abductees = list(set(abductees))
                deadies = list(set(deadies))

                # Role objects (based on ID)
                roles = main_guild.roles # Roles from the guild
                game_master_role = discord.utils.find(lambda r: r.id == game_master, roles)
                # TODO: Add read permissions for spectators if element.secret == False
                default_permissions = {
                    main_guild.default_role: discord.PermissionOverwrite(read_messages=False,send_messages=False),
                    game_master_role: discord.PermissionOverwrite(read_messages=True,send_messages=True),
                    client.user: discord.PermissionOverwrite(read_messages=True,send_messages=True),
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=True) for member in viewers
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=False) for member in frozones
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=False) for member in deadies
                    }
                }

                if not element.secret:
                    intro_msg = creation_messages.cc_intro([v.id for v in viewers])
                    reason_msg = 'CC requested by ' + message.author.name
                    title = "s{}_cc_{}".format(config.season,element.name)
                    category_name = 'S{} CCs PART {}'.format(config.season,db.count_categories(element.secret) + 1)
                else:
                    intro_msg = secret_messages.creation(element.name,[v.id for v in viewers])
                    reason_msg = 'Secret {} channel created.'.format(element.name)
                    title = "s{}_{}".format(config.season,element.name)
                    category_name = 'S{} Secret Channels Part {}'.format(config.season,db.count_categories(element.secret) + 1)

                # Create a new category if needed
                if db.get_category(element.secret) == None:
                    category = await main_guild.create_category(category_name, reason='It seems like we couldn\'t use our previous category! Don\'t worry, I just created a new one.')
                    db.add_category(category.id,element.secret)
                else:
                    category = main_guild.get_channel(db.get_category(element.secret))

                try:
                    # Create the text channel
                    channel = await main_guild.create_text_channel(
                        name=title,
                        category=category,
                        overwrites=default_permissions,
                        reason=reason_msg)
                    db.add_channel(channel.id,element.owner,element.secret)
                    if element.secret:
                        db.add_secret_channel(channel.id,element.name)

                        # If the channel is meant for an amulet holder, assign the amulet holder.
                        if element.name == 'Amulet_Holder':
                            for member in viewers:
                                if db_get(member.id,'role') == 'Amulet Holder':
                                    db_set(member.id,'amulet',channel.id)
                    if element.trashy:
                        db.add_trash_channel(channel.id)

                    await channel.send(intro_msg)

                    # Set all access rules in the database
                    for member in viewers:
                        db.set_user_in_channel(channel.id,member.id,1)
                    for member in frozones:
                        db.set_user_in_channel(channel.id,member.id,2)
                    for member in abductees:
                        db.set_user_in_channel(channel.id,member.id,3)
                    for member in deadies:
                        if db.isParticipant(member.id,True,True) == True:
                            db.set_user_in_channel(channel.id,member.id,4)


                except Exception as e: # Catch any thrown exceptions and send an error to the user.
                    await message.channel.send('It seems like I\'ve encountered an error! Please let the Game Masters know about this!')
                    await botspam_channel.send("Oi, Game Masters! I got a problem concerning channel creation for ya to fix.")
                    await botspam_channel.send(e)
                    raise e # Send the full log to Buddy1913 and his sketchy VM.

                # Give the settlers their own happy little residence
                for buddy in element.settlers:
                    db_set(buddy,"channel",channel.id)

            else:
                """This should not happen, but we'll use it, to prevent the bot from purposely causing an error
                everytime someone attempts to create a channel that contains spaces. 'cause believe me,
                that happens ALL the time."""
                msg = await message.channel.send("I\'m terribly sorry, but you can\'t use spaces in your channel name. Try again!")
                temp_msg.append(msg)


        # Polls are created here.
        for element in mailbox.polls:
            # element.channel
            # element.purpose
            # element.user_id
            # element.description

            msg = element.description + '\n'
            emoji_table = []
            msg_table = []
            i = 0

            for user in db.poll_list():
                if db.isParticipant(int(user[0])):
                    i += 1
                    msg += user[1] + " - <@" + str(user[0]) + "> "

                    if int(user[2]) + int(user[3]) > 0:
                        if int(user[2]) == 1:
                            msg += "**[FROZEN]** "
                        if int(user[3]) == 1:
                            msg += "**[ABDUCTED] **"
                    else:
                        emoji_table.append(user[1])

                    if i % 20 == 19:
                        if client.get_channel(int(element.channel)) == None:
                            await botspam_channel.send("Failed to send message in correct channel. ({})".format(element.channel))
                            msg = await botspam_channel.send(element.content)
                        else:
                            msg = await client.get_channel(int(element.channel)).send(msg)
                        for emoji in emoji_table:
                            await msg.add_reaction(emoji)
                        msg_table.append(msg)
                        emoji_table = []
                        msg = ''
                    else:
                        msg += '\n'

            if msg != '':
                msg = await client.get_channel(element.channel).send(msg)
                for emoji in emoji_table:
                    await msg.add_reaction(emoji)
                msg_table.append(msg)
            db.add_poll(msg_table,element.purpose,element.channel,element.user_id)
            await botspam_channel.send("A poll has been created in <#{}>!".format(element.channel))


        # Categories are deleted here.
        for element in mailbox.deletecategories:
            id = element.channel
            category = client.get_channel(id)
            if category != None:
                bot_message = await message.channel.send('Please react with 👍 to confirm deletion of category `' + category.name + '`.\n\nNote: This action will irreversibly delete all channels contained within the specified category. Please use with discretion.')
                await bot_message.add_reaction('👍')
                def check(reaction, user):
                    return user == message.author and str(reaction.emoji) == '👍'
                try:
                    reaction, user = await client.wait_for('reaction_add', timeout=30.0, check=check)
                except asyncio.TimeoutError:
                    await message.channel.send('Confirmation timed out.')
                    try:
                        await bot_message.delete()
                    except Exception:
                        pass
                else:
                    await message.channel.send('Ok, I\'ll get right on that.\n\n*This might take some time.*')
                    for channel in category.channels:
                        await channel.delete()
                    await category.delete()
                    await message.channel.send('\n:thumbsup: Channels and category deleted')
            else:
                await message.channel.send('Sorry, I couldn\'t find that category.')

        clean_time = len(mailbox.cleaners)
        if clean_time > 0:
            await botspam_channel.send("Cleaning up {} channels! This may take some time.".format(clean_time))

        for channel in mailbox.cleaners:

            trash_channel = client.get_channel(int(channel))

            if trash_channel != None:
                for message_id in db.empty_trash_channel(channel):
                    message = await trash_channel.get_message(int(message_id))
                    if message != None:
                        await message.delete()

    # Delete all temporary messages after about two minutes.
    await asyncio.sleep(120)
    for msg in temp_msg:
        try:
            await msg.delete()
        except Exception:
            # Unable to delete the message.
            # It was probaly already deleted or something.
            pass
Exemple #11
0
def process(message, isGameMaster = False):

    user_id = message.author.id
    message_channel = message.channel.id
    user_role = db_get(user_id,'role')

    '''testcc'''
    # This function is merely a temporary one, to test if the cc creation command is working properly.
    if is_command(message,['cc','testcc','test_cc']):
        members = check.users(message)
        if len(message.content.split(' ')) == 1 or members == False:
            msg = "**Incorrect syntax:** `" + prefix + "cc <name> <user> <user> <user> ...`\n\nExample: `" + prefix + "cc the_cool_ones @Randium#6521`"
            msg += "\n\nThe bot understands both mentions and emojis linked to players."
            return [Mailbox().respond(msg,True)]
        name = message.content.split(' ')[1]
        return [Mailbox().create_cc(name,user_id,members)]
    if is_command(message,['cc','testcc','test_cc'],True):
        msg = "**Usage:** `" + prefix + "cc <name> <user> <user> <user> ...`\n\nExample: `" + prefix + "cc the_cool_ones @Randium#6521`"
        msg += "\n\nThe bot understands both mentions and emojis linked to players."
        return [Mailbox().respond(msg,True)]

    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:

        '''addrole'''
        # Before the game starts, a list of roles is kept track of.
        # That list is the list of roles that will be dealt among the participants.
        # If the list is greater than the amount of participants, some random roles will be left out.
        # The game cannot start as long as this list is incomplete.
        if is_command(message,['addrole']):
            # TODO
            return todo()
        if is_command(message,['addrole'],True):
            # TODO
            return todo()

        '''assign'''
        # This command is used at the start of the game to assign all roles.
        # This will actually set their "fakerole" value, which will be transferred to their actual role once the game starts.
        if is_command(message,['assign']):
            role = check.roles(message,1)[0]
            user = check.users(message,1)[0]

            if role == False:
                return [Mailbox().respond("No role provided! Please provide us with a role!")]
            if user == False:
                return [Mailbox().respond("No user found! Please provide us with a user!")]

            db_set(user,'role',role)
            return [Mailbox().spam("You have successfully given <@{}> the role of the `{}`!".format(user,role))]

        if is_command(message,['assign'],True):
            msg = "**Usage:** `" + prefix + "assign <user> <role>`\n\nExample: `" + prefix
            msg += "assign @Randium#6521 Innocent`\nGame Master only command"
            return [Mailbox().spam(msg)]

        '''day'''
        # This command is used to initialize the day.
        if is_command(message,['day']):
            # TODO
            return todo()
        if is_command(message,['day'],True):
            # TODO
            return todo()

        '''open_signup'''
        # This command is started when a new game can be started.
        # Make sure the bot has reset itself beforehand.
        if is_command(message,['open_signup']):
            # TODO
            return todo()
        if is_command(message,['open_signup'],True):
            # TODO
            return todo()

        '''whois'''
        # This command reveals the role of a player.
        # To prevent spoilers, the response isn't made in the message's channel, but rather in the bot spam channel.
        if is_command(message,['whois']):
            user_table = check.users(message)
            identities = Mailbox()

            if user_table == False:
                return [Mailbox().respond("**ERROR:** No user provided!")]

            for user in user_table:
                emoji = db_get(user,'emoji')
                role = db_get(user,'role')
                if emoji == None or role == None:
                    identities.spam("**ERROR:** Could not find user <@{}> in database.".format(user))
                else:
                    msg = "{} - <@{}> has the role of the `{}`!".format(emoji,user,role)
                    identities.spam(msg)

            return [identities]

        if is_command(message,['whois'],True):
            msg = "**Usage:** `" + prefix + "whois <user1> <user2> ...`\n\n"
            msg += "Example: `" + prefix + "whois @Randium#6521`\nGame Master only command"
            return [Mailbox().respond(msg,True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):

        '''add'''
        # This command allows users to add users to a conspiracy.
        # This command will not trigger if the user doesn't own the conspiracy channel.
        if is_command(message,['add']):
            members_to_add = check.users(message)
            if members_to_add == False:
                return [Mailbox().respond("I am sorry! I couldn't find the user you were looking for!",True)]
            if is_owner(user_id,message.channel.id) == False:
                return [Mailbox().respond("I\'m sorry, you can only use this in conspiracy channels where you are the owner!")]
            command = Mailbox()
            for x in members_to_add:
                command.edit_cc(x,channel_id,1)
            return [command.respond("Insert Randium's comment here")]

        if is_command(message,['add'],True):
            # TODO
            return todo()

        '''cc'''
        # This command allows users to create a conspiracy channel.
        if is_command(message, ['cc']):
            if len(message.content.split(' ')) < 2:
                    return [Mailbox().respond("**Invalid syntax:**\n\n`" + prefix + "cc <name> <user1> <user2> <user3> ...`\n\n**Example:** `" + prefix + "cc the_cool_guys @Randium#6521`")]

            channel_members = check.users(message)
            if channel_members == False:
                channel_members = []
            if user_id not in channel_members:
                channel_members.append(user_id)

            num_cc_owned = int(db_get(user_id,'ccs'))

            if num_cc_owned >= max_cc_per_user:
                answer = Mailbox().dm("You have reached the amount of conspiracy channels one may own!", user_id)
                return answer.dm("If you want more conspiracy channels, please request permission from one of the Game Masters.", user_id)

            db_set(user_id,'ccs',number_cc_owned + 1)
            return Mailbox.create_cc(message.content.split(' ')[1], user_id, channel_members)

        if is_command(message,['cc'],True):
            # TODO
            return todo()

        '''info'''
        # This command allows users to view information about a conspiracy channel.
        # Says the user must be in a cc if they're not.
        if is_command(message,['info']):
            guild = message.channel.guild
            try:
                owner_id = channel_get(message.channel.id,'owner')
            except:
                return[Mailbox().respond('Sorry, but it doesn\'t look like you\'re in a CC! If you are, please alert a Game Master as soon as possible.')]
            if owner_id != None:
                owner_object = guild.get_member(int(owner_id))
            embed = Embed(color=0x00cdcd, title='Conspiracy Channel Info')
            if owner_object != None and owner_id != None:
                embed.add_field(name='Channel Owner', value='<@' + owner_id + '>')
                embed.set_thumbnail(url=owner_object.avatar_url)
            elif owner_id == None:
                return [Mailbox().respond('Sorry, but it doesn\'t look like you\'re in a CC! If you are, please alert a Game Master as soon as possible.')]
            else:
                try:
                    owner_name = db_get(owner_id,'name')
                    if str(owner_name) == 'None':
                        owner_name = 'Sorry, an error was encountered. Please alert a Game Master.'
                except:
                    owner_name == 'Sorry, an error was encountered. Please alert a Game Master.'

                embed.add_field(name='Channel Owner', value=owner_name)

            embed.add_field(name='Channel Name', value=message.channel.name)
            embed.add_field(name='Participants', value='[Bob Roberts], [Dummy], [Randium], [BenTechy66], [Ed588]')
            embed.set_footer(text='Conspiracy Channel Information requested by ' + message.author.nick)
            return [Mailbox().embed(embed, message.channel.id)]
        if is_command(message,['info'],True):
            # TODO
            return todo()

        '''myrole'''
        # This command sends the user's role back to them in a DM.
        if is_command(message,['myrole']):
            return [Mailbox().dm("Your role is **{}**.".format(db_get(message.author.id,'role')), message.author.id,False,[db_get(message.author.id,'emoji')])]
        if is_command(message,['myrole'],True):
            # TODO
            return todo()

        '''remove'''
        # This command removes a given user from a conspiracy channel.
        # A user should not get removed if they're the channel owner.
        if is_command(message,['remove']):
            members_to_remove = check.users(message)
            if is_owner(user_id,channel_id) == False:
                return [Mailbox().respond("I\'m sorry, but you cannot use this command over here!")]
            command = Mailbox()
            for x in members_to_remove:
                if is_owner(x,channel_id) == True:
                    return [Mailbox().respond("The owner of a CC can\'t be removed! Please try again.")]
                command.edit_cc(x,channel_id,0)
            return [command.respond("Insert Randium's comment here")]

        if is_command(message,['remove'],True):
            # TODO
            return todo()

        # =======================================================
        #                ROLE SPECIFIC COMMANDS
        # =======================================================
        if personal_channel(user_id,message_channel) == True:

            '''give_amulet'''
            # This command can be executed by everyone, but only in one channel.
            # That's the amulet channel.
            # To be worked out how exactly.
            if is_command(message,['give_amulet']):
                # TODO
                return todo()
            if is_command(message,['give_amulet'],True):
                # TODO
                return todo()

            '''assassinate'''
            # Assassin's command; kill a victim
            if is_command(message,['assassinate','kill']) and user_role == "Assassin":
                # TODO
                return todo()
            if is_command(message,['assassinate','kill'],True) and user_role == "Assassin":
                # TODO
                return todo()

            '''aura'''
            # The command for aura tellers
            if is_command(message,['aura','tell','vision']) and user_role == "Aura Teller":
                # TODO
                return todo()
            if is_command(message,['aura','tell','vision'],True) and user_role == "Aura Teller":
                # TODO
                return todo()

            '''barber_kill'''
            # Barber kill - to assassinate a victim during the day
            if is_command(message,['assassinate','barber_kill','cut']) and user_role == "Barber":
                # TODO
                return todo()
            if is_command(message,['assassinate','barber_kill','cut'],True) and user_role == "Barber":
                # TODO
                return todo()

            '''seek'''
            # Crowd seeker's power
            if is_command(message,['crowd','seek']) and user_role == "Crowd Seeker":
                # TODO
                return todo()
            if is_command(message,['crowd','seek'],True) and user_role == "Crowd Seeker":
                # TODO
                return todo()

            '''kiss'''
            # Cupid's power to fall in love with someone.
            if is_command(message,['kiss','love','shoot']) and user_role == "Cupid":
                # TODO
                return todo()
            if is_command(message,['kiss','love','shoot'],True) and user_role == "Cupid":
                # TODO
                return todo()

            '''follow'''
            # The command that allows the dog to choose a side.
            if is_command(message,['bark','become','choose','follow']) and user_role == "Dog":
                # TODO
                return todo()
            if is_command(message,['bark','become','choose','follow'],True) and user_role == "Dog":
                # TODO
                return todo()

            '''execute'''
            # This command allows the executioner to choose a replacement target.
            if is_command(message,['choose','execute']) and user_role == "Executioner":
                # TODO
                return todo()
            if is_command(message,['choose','execute'],True) and user_role == "Executioner":
                # TODO
                return todo()

            '''undoom'''
            # The Exorcist's command.
            if is_command(message,['exercise','exorcise','undoom']) and user_role == "Exorcist":
                # TODO
                return todo()
            if is_command(message,['exercise','exorcise','undoom'],True) and user_role == "Exorcist":
                # TODO
                return todo()

            '''inspect'''
            # The fortune teller's command.
            if is_command(message,['forsee','inspect','see','tell']) and user_role == "Fortune Teller":
                # TODO
                return todo()
            if is_command(message,['forsee','inspect','see','tell'],True) and user_role == "Fortune Teller":
                # TODO
                return todo()

            '''silence'''
            # Grandma's command.
            if is_command(message,['knit','knot','silence']) and user_role == "Grandma":
                # TODO
                return todo()
            if is_command(message,['knit','knot','silence'],True) and user_role == "Grandma":
                # TODO
                return todo()

            '''hook'''
            # The hooker's command
            if is_command(message,['f**k','hook','sleep']) and user_role == "Hooker":
                # TODO
                return todo()
            if is_command(message,['f**k','hook','sleep'],True) and user_role == "Hooker":
                # TODO
                return todo()

            '''hunt'''
            # The huntress' command. Used to keep track of whom will be shot.
            if is_command(message,['hunt','shoot']) and user_role == "Huntress":
                # TODO
                return todo()
            if is_command(message,['hunt','shoot'],True) and user_role == "Huntress":
                # TODO
                return todo()

            '''unfreeze'''
            # The innkeeper's command
            if is_command(message,['melt','unfreeze']) and user_role == "Innkeeper":
                # TODO
                return todo()
            if is_command(message,['melt','unfreeze'],True) and user_role == "Innkeeper":
                # TODO
                return todo()

            '''copy'''
            # The Look-Alike's command
            if is_command(message,['copy','imitate','mirror','resemble']) and user_role == "Look-Alike":
                # TODO
                return todo()
            if is_command(message,['copy','imitate','mirror','resemble'],True) and user_role == "Look-Alike":
                # TODO
                return todo()

            '''holify'''
            # The Priest's command
            if is_command(message,['holify','sacrify','water']) and user_role == "Priest":
                # TODO
                return todo()
            if is_command(message,['holify','sacrify','water'],True) and user_role == "Priest":
                # TODO
                return todo()

            '''purify'''
            # The Priestess' command
            if is_command(message,['heal','light','purify','sacrify']) and user_role == "Priestess":
                # TODO
                return todo()
            if is_command(message,['heal','light','purify','sacrify'],True) and user_role == "Priestess":
                # TODO
                return todo()

            '''threaten'''
            # The Raven's command
            if is_command(message,['threaten','raven']) and user_role == "Raven":
                # TODO
                return todo()
            if is_command(message,['threaten','raven'],True) and user_role == "Raven":
                # TODO
                return todo()

            '''reveal'''
            # The Royal Knight's command
            if is_command(message,['end','prevent','reveal','stop']) and user_role == "Royal Knight":
                # TODO
                return todo()
            if is_command(message,['end','prevent','reveal','stop'],True) and user_role == "Royal Knight":
                # TODO
                return todo()

            '''life'''
            # The witch' command to use her life potion
            if is_command(message,['heal','life','save']) and user_role == "Witch":
                # TODO
                return todo()
            if is_command(message,['heal','life','save'],True) and user_role == "Witch":
                # TODO
                return todo()

            '''death'''
            # The witch' command to use her death potion
            if is_command(message,['death','kill','murder','poison']) and user_role == "Witch":
                # TODO
                return todo()
            if is_command(message,['death','kill','murder','poison'],True) and user_role == "Witch":
                # TODO
                return todo()

            '''çurse'''
            # The curse caster's command
            if is_command(message,['cast','corrupt','curse']) and user_role == "Curse Caster":
                # TODO
                return todo()
            if is_command(message,['cast','corrupt','curse'],True) and user_role == "Curse Caster":
                # TODO
                return todo()

            '''infect'''
            # The infected wolf's command
            if is_command(message,['cough','infect','sneeze','turn']) and user_role == "Infected Wolf":
                # TODO
                return todo()
            if is_command(message,['cough','infect','sneeze','turn'],True) and user_role == "Infected Wolf":
                # TODO
                return todo()

            '''devour'''
            # The Lone wolf's command
            if is_command(message,['chew','devour','eat','kill','munch']) and user_role == "Lone Wolf":
                # TODO
                return todo()
            if is_command(message,['chew','devour','eat','kill','munch'],True) and user_role == "Lone Wolf":
                # TODO
                return todo()

            '''disguise'''
            # The tanner's command
            if is_command(message,['change','cloth','disguise','hide']) and user_role == "Tanner":
                # TODO
                return todo()
            if is_command(message,['change','cloth','disguise','hide'],True) and user_role == "Tanner":
                # TODO
                return todo()

            '''inspect'''
            # The Warlock's command
            if is_command(message,['forsee','inspect','see','tell']) and user_role == "Priestess":
                # TODO
                return todo()
            if is_command(message,['forsee','inspect','see','tell'],True) and user_role == "Priestess":
                # TODO
                return todo()

            '''devour'''
            # The white werewolf's command
            if is_command(message,['chew','devour','eat','kill','munch']) and user_role == "White Werewolf":
                # TODO
                return todo()
            if is_command(message,['chew','devour','eat','kill','munch'],True) and user_role == "White Werewolf":
                # TODO
                return todo()

            '''wager'''
            # The devil's command
            if is_command(message,['choose','wager']) and user_role == "Devil":
                # TODO
                return todo()
            if is_command(message,['choose','wager'],True) and user_role == "Devil":
                # TODO
                return todo()

            '''enchant'''
            # The flute player's command
            if is_command(message,['enchant','flute']) and user_role == "Flute Player":
                # TODO
                return todo()
            if is_command(message,['enchant','flute'],True) and user_role == "Flute Player":
                # TODO
                return todo()

            '''unite'''
            # The horseman's command
            if is_command(message,['apocalypse','clean','unite']) and user_role == "Horseman":
                # TODO
                return todo()
            if is_command(message,['apocalypse','clean','unite'],True) and user_role == "Horseman":
                # TODO
                return todo()

            '''guess'''
            # The ice king's command to add a guess about a user to their list.
            # Note that this command could/should be usable at any time, as long as the submit command isn't
            if is_command(message,['add','guess','freeze']) and user_role == "Ice King":
                # TODO
                return todo()
            if is_command(message,['add','guess','freeze'],True) and user_role == "Ice King":
                # TODO
                return todo()

            '''submit'''
            # The ice king's command to submit the list of people of whom they have guessed their roles.
            if is_command(message,['guess_that','freeze_all','submit']) and user_role == "Ice King":
                # TODO
                return todo()
            if is_command(message,['guess_that','freeze_all','submit'],True) and user_role == "Ice King":
                # TODO
                return todo()

            '''powder'''
            # Powder a player
            if is_command(message,['creeper','powder']) and user_role == "Pyromancer":
                # TODO
                return todo()
            if is_command(message,['creeper','powder'],True) and user_role == "Pyromancer":
                # TODO
                return todo()

            '''abduct'''
            # To kidnap players
            if is_command(message,['abduct','add','kidnap','swamp']) and user_role == "The Thing":
                # TODO
                return todo()
            if is_command(message,['abduct','add','kidnap','swamp'],True) and user_role == "The Thing":
                # TODO
                return todo()

            '''create_swamp'''
            # To create a new swamp with all victims
            if is_command(message,['abduct_all','create_swamp','start_cliche_horror_movie']) and user_role == "The Thing":
                # TODO
                return todo()
            if is_command(message,['abduct_all','create_swamp','start_cliche_horror_movie'],True) and user_role == "The Thing":
                # TODO
                return todo()

    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    '''age'''
    # Allows users to set their age.
    if is_command(message,['age']):
        # TODO
        return todo()
    if is_command(message,['age'],True):
        # TODO
        return todo()

    '''profile'''
    # This command allows one to view their own profile
    # When giving another player's name, view that player's profile
    if is_command(message,['profile']):
        # TODO
        return todo()
    if is_command(message,['profile'],True):
        # TODO
        return todo()

    '''signup'''
    # This command signs up the player with their given emoji, assuming there is no game going on.
    if is_command(message,['signup']):
        emojis = check.emojis(message)
        choice_emoji = ""

        if emojis == False:
            msg = "**Incorrect syntax:** `" + prefix + "signup <emoji>`\n\nExample: `" + prefix + "signup :smirk:`"
            return [Mailbox().respond(msg,True)]

        for emoji in emojis:
            if emoji_to_player(emoji) == None:
                choice_emoji = emoji
                break

        if isParticipant(user_id,True,True):
            if choice_emoji == "":
               return [Mailbox().respond("You are already signed up with the {} emoji! Also, your emoji was occupied.".format(db_get(user_id,'emoji')),True)]
            db_set(user_id,'emoji',choice_emoji)
            reaction = Mailbox().respond("You have successfully changed your emoji to the {} emoji!".format(choice_emoji))
            return [reaction.spam("<@{}> has changed their emoji to the {} emoji.".format(user_id,choice_emoji))]

        if emoji == "":
            if len(choice_emojis) == 1:
                return [Mailbox().respond("I am sorry! Your chosen emoji was already occupied.",True)]
            return [Mailbox().respond("I am sorry, but all of your given emojis were already occupied! Such bad luck.",True)]
        signup(user_id,message.author.name,choice_emoji)
        reaction = Mailbox().respond("You have successfully signed up with the {} emoji!".format(choice_emoji))
        return [reaction.spam("<@{}> has signed up with the {} emoji.".format(user_id,choice_emoji))]
    # Help command
    if is_command(message,['signup'],True):
        msg = "**Usage:** `" + prefix + "signup <emoji>`\n\nExample: `" + prefix + "signup :smirk:`"
        return [Mailbox().respond(msg,True)]

    if message.content.startswith(prefix):
        return [Mailbox().respond("Sorry bud, couldn't find what you were looking for.",True)]

    return []
def viliager_victory():
    """This function returns true if the town's win condition has been met."""
    for user in db.player_list():
        if db.isParticipant(user) and user not in villager_team:
            return False
    return True
def wolf_victory():
    """This function returns true if the wolves' win condition has been met."""
    for user in db.player_list():
        if db.isParticipant(user) and user not in wolf_team:
            return False
    return True
Exemple #14
0
def process(message, isGameMaster=False, isAdmin=False, isPeasant=False):
    user_id = message.author.id
    message_channel = message.channel.id

    help_msg = "**List of commands:**\n"

    args = message.content.split(' ')

    # =============================================================
    #
    #                         BOT COMMANDS
    #
    # =============================================================
    if isPeasant == True:
        pass

    # =============================================================
    #
    #                         ADMINISTRATOR
    #
    # =============================================================
    if isAdmin == True:
        help_msg += "\n __Admin commands:__\n"

    elif is_command(message, ['delete_category', 'start']):
        return [
            Mailbox().respond(PERMISSION_MSG.format("Administrator"), True)
        ]

    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:
        help_msg += "\n__Game Master commands:__\n"

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Game Master"), True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):
        help_msg += "\n__Participant commands:__\n"

        user_undead = int(db_get(user_id, 'undead'))

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Participant"), True)]

    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    help_msg += '\n\n'

    if is_command(message, ['inv', 'inventory', 'bal', 'balance']):
        answer = Mailbox().dm("**__YOUR CURRENT BALANCE__**", user_id)
        for item in items.jget("items"):
            if has_item(user_id, item["code"]):
                answer.dm_add('\n' + item["name"] + ' - *(' +
                              has_item(user_id, item["code"], False) + ')*')
        return [answer]
    if is_command(message, ['inv', 'inventory', 'bal', 'balance'], True):
        return todo()
    help_msg += "`" + prefix + "inventory` - View your inventory.\n"

    # --------------------------------------------------------------
    #                          HELP
    # --------------------------------------------------------------
    help_msg += "\n\n*If you have any more questions, feel free to ask any of the Game Masters!*"
    '''help'''
    if is_command(message, ['help']) and is_command(message, ['help'],
                                                    True) == False:
        return [Mailbox().respond(help_msg, True)]
    if is_command(message, ['help'], True):
        answer = Mailbox().respond(
            "Hey there! `" + prefix +
            "help` will give you a list of commands that you can use.")
        answer.respond_add(
            "\nIf you have any questions, feel free to ask any of the Game Masters!"
        )
        return [answer]

    if message.content.startswith(prefix):
        return [
            Mailbox().respond(
                "Sorry bud, couldn't find what you were looking for.", True)
        ]

    return []
async def check_time():
    print('   | > Waiting for client to be ready')
    await client.wait_until_ready()
    print('   | > Event loop triggered')
    await asyncio.sleep(1)

    while True:
        time = datetime.datetime.now()
        current_hour = str(time.hour - 1)

        # Give the hour signal
        if str(time.hour) != current_hour:
            print("--> We've reached the hour! It's now %s00 hours." %
                  (time.hour))
            current_hour = str(time.hour)

            # Set each user's activity one up.
            for user in db.player_list():
                activity = db.db_get(user, 'activity')
                db.db_set(user, 'activity', activity + 1)

                if db.isParticipant(user):
                    if activity_hours - activity == 24:
                        await client.get_channel(bot_spam).send(
                            prefix + "warn <@{}>".format(user))
                    elif activity >= activity_hours:
                        await client.get_channel(bot_spam).send(
                            prefix + "idle <@{}>".format(user))

            # Set each shop's age one up.
            age_shop()

            # Purge activity
            purge_activity()

            # Give free credits in the middle of the night.
            if str(time.hour) == "0":
                await client.get_channel(welcome_channel).send(
                    'Gonna send some credits! Get ready!')
                deal_credits()

            # Give the day signal
            if str(time.hour) == "8":
                if dy.get_stage() != "NA":
                    print('Another day has started!')
                    await client.get_channel(bot_spam).send(prefix + "pay")
                else:
                    await client.get_channel(bot_spam).send(
                        "Beep boop! Another day has begun!")

            # Give the night signal
            if str(time.hour) == "21":
                if dy.get_stage() != "NA":
                    print('Another night has begun!')
                    await client.get_channel(bot_spam).send(prefix + "pight")
                else:
                    await client.get_channel(bot_spam).send(
                        "Beep boop! The night has started!")

            # Make a backup of the database
            newpath = 'backup/{}_{}/{}_{}h/'.format(time.year, time.month,
                                                    time.day, time.hour)
            if not os.path.exists(newpath):
                os.makedirs(newpath)
            open(
                'backup/{}_{}/{}_{}h/{}_backup_game.db'.format(
                    time.year, time.month, time.day, time.hour, time.minute),
                'a').close()
            open(
                'backup/{}_{}/{}_{}h/{}_backup_general.db'.format(
                    time.year, time.month, time.day, time.hour, time.minute),
                'a').close()
            open(
                'backup/{}_{}/{}_{}h/{}_backup_stats.json'.format(
                    time.year, time.month, time.day, time.hour, time.minute),
                'a').close()
            open(
                'backup/{}_{}/{}_{}h/{}_backup_dynamic.json'.format(
                    time.year, time.month, time.day, time.hour, time.minute),
                'a').close()
            open(
                'backup/{}_{}/{}_{}h/{}_backup_config.py'.format(
                    time.year, time.month, time.day, time.hour, time.minute),
                'a').close()
            copy(
                config.database,
                'backup/{}_{}/{}_{}h/{}_backup_game.db'.format(
                    time.year, time.month, time.day, time.hour, time.minute))
            copy(
                config.general_database,
                'backup/{}_{}/{}_{}h/{}_backup_general.db'.format(
                    time.year, time.month, time.day, time.hour, time.minute))
            copy(
                config.stats_file,
                'backup/{}_{}/{}_{}h/{}_backup_stats.json'.format(
                    time.year, time.month, time.day, time.hour, time.minute))
            copy(
                config.dynamic_config,
                'backup/{}_{}/{}_{}h/{}_backup_dynamic.json'.format(
                    time.year, time.month, time.day, time.hour, time.minute))
            copy(
                'config.py', 'backup/{}_{}/{}_{}h/{}_backup_config.py'.format(
                    time.year, time.month, time.day, time.hour, time.minute))

            await asyncio.sleep(75)

        await asyncio.sleep(10)
Exemple #16
0
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    gamelog_channel = client.get_channel(int(config.game_log))
    botspam_channel = client.get_channel(int(config.bot_spam))
    storytime_channel = client.get_channel(int(config.story_time))

    # Check if the message author has the Game Master role
    isGameMaster = False
    if message.guild == gamelog_channel.guild:
        if game_master in [y.id for y in message.guild.get_member(message.author.id).roles]:
            isGameMaster = True

    isAdmin = False
    if message.guild == gamelog_channel.guild:
        if administrator in [y.id for y in message.guild.get_member(message.author.id).roles]:
            isAdmin = True

    result = process(message,isGameMaster,isAdmin)

    temp_msg = []

    for mailbox in result:

        if mailbox.evaluate_polls == True:
            for poll in db.get_all_polls():
                # poll.msg_table -> list of message ids
                # poll.blamed -> name of killer
                # poll.purpose -> the reason of the kill

                poll_channel = client.get_channel(int(poll.channel))
                if poll_channel == None:
                    await botspam_channel.send("We got a problem! Could you send these results to the appropriate channel, please?")
                    poll_channel = botspam_channel

                user_table = []
                for msg in poll.msg_table:
                    poll_msg = await poll_channel.get_message(msg)
                    for emoji in poll_msg.reactions:
                        users = await emoji.users().flatten()

                        for person in users:
                            if db.isParticipant(person.id):
                                user_table.append([person.id,emoji.emoji])

                log, result, chosen_emoji = count_votes(user_table,poll.purpose)

                await gamelog_channel.send(log)
                await poll_channel.send(result)

                chosen_one = db.emoji_to_player(chosen_emoji)

                if chosen_emoji != '' and chosen_one != None:
                    if poll.purpose == 'lynch':
                        db.add_kill(chosen_one,'Innocent')
                    elif poll.purpose == 'Mayor':
                        # TODO: give Mayor role and add data to dynamic.json
                        pass
                    elif poll.purpose == 'Reporter':
                        # TODO: give Reporter role and add data to dynamic.json
                        pass
                    elif poll.purpose == 'wolf':
                        db.add_kill(chosen_one,'Werewolf',db.random_wolf())
                    elif poll.purpose == 'cult':
                        db.add_kill(chosen_one,'Cult Leader',db.random_cult())
                    elif poll.purpose == 'thing':
                        # TODO: kill poor victim
                        pass


        for element in mailbox.gamelog:
            msg = await gamelog_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        for element in mailbox.botspam:
            msg = await botspam_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        for element in mailbox.storytime:
            msg = await storytime_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        for element in mailbox.answer:
            msg = await message.channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        for element in mailbox.channel:
            if element.embed:
                if element.destination == "spam":
                    msg = await botspam_channel.send(embed=element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
                else:
                    msg = await client.get_channel(int(element.destination)).send(embed=element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
            else:
                msg = await client.get_channel(int(element.destination)).send(element.content)
                for emoji in element.reactions:
                    await msg.add_reaction(emoji)
                if element.temporary == True:
                    temp_msg.append(msg)

        for element in mailbox.player:
            member = client.get_user(element.destination)
            if member == None:
                await message.channel.send("Couldn't send a DM to <@{}>!".format(element.destination))
                await botspam_channel.send("<@{}> has attempted to send a DM to <@{}>, but failed, because we couldn't find the specified user via `get_user`.".format(message.author.id,element.destination))
            else:
                msg = await member.send(element.content)
                for emoji in element.reactions:
                    await msg.add_reaction(emoji)
                if element.temporary == True:
                    temp_msg.append(msg)

        for element in mailbox.oldchannels:
            # element.channel - channel to be edited;
            # element.victim - person's permission to be changed;
            # element.number - type of setting to set to:
                # 0 - no access     (no view, no type)
                # 1 - access        (view + type)
                # 2 - frozen        (view, no type)
                # 3 - abducted      (no view, no type)
                # 4 - dead          (dead role?)

            # 0 -> read = False
            # 1 -> read = True
            # 2 -> give frozen (if they don't have it yet)
            # 3 -> read = False
            # 4 -> give dead role + remove participant role
            # 5 -> mute
            # 6 -> also mute, no read

            channel = client.get_channel(element.channel)
            user = client.get_user(element.victim)
            main_guild = botspam_channel.guild
            member = main_guild.get_member(element.victim)
            await remove_all_game_roles(member)
            if element.number == 0:
                await channel.set_permissions(user, read_messages=False, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
            elif element.number == 1:
                await channel.set_permissions(user, read_messages=True, send_messages=True)
                await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
            elif element.number == 2:
                await channel.set_permissions(user, read_messages=True, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.frozen_participant), reason="Updating CC Permissions")
            elif element.number == 3:
                await channel.set_permissions(user, read_messages=False, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
            elif element.number == 4:
                await channel.set_permissions(user, read_messages=True, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.dead_participant), reason="Updating CC Permissions")
            elif element.number == 5:
                await channel.set_permissions(user, read_messages=True, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
            elif element.number == 6:
                await channel.set_permissions(user, read_messages=False, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.participant), reason="Updating CC Permissions")
            elif element.number == 7:
                await channel.set_permissions(user, read_messages=False, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.dead_participant), reason="Updating CC Permissions")
            elif element.number == 8:
                await channel.set_permissions(user, read_messages=False, send_messages=False)
                await member.add_roles(get_role(main_guild.roles, config.suspended), reason="Updating CC Permissions")
            else:
                await msg.channel.send('Something went wrong! Please contact a Game Master.')
                return
            if db.isParticipant(element.victim,True,True):
                db.set_user_in_channel(element.channel,element.victim,element.number)


        for element in mailbox.newchannels:
            # element.name - name of the channel;
            # element.owner - owner of the channel;
            # element.members - members of the channel
            # element.settlers - members for whom this shall become their home channel
            #
            # @Participant      - no view + type
            # @dead Participant - view + no type
            # @everyone         - no view + no type

            # All you need to do is create a channel where only the channel owner has access.
            # The other members are given access through another Mailbox.
            # You could make the work easier if you also posted a cc channel message already over here.

            if ' ' not in element.name:

                main_guild = botspam_channel.guild # Find the guild we're in

                if element.owner not in element.members:
                    element.members.append(element.owner)
                for buddy in element.settlers:
                    if buddy not in element.members:
                        msg = """**Warning:** I'm adding settlers to a channel!\nThis is should not be a problem, \
                        but it does at least indicate a flaw in the bot's code. Please, report this to the Game Masters!"""
                        await client.get_channel(message.channel).send(msg)
                        element.members.append(buddy)

                viewers = []
                frozones = []
                abductees = []
                deadies = []
                for user in element.members:
                    member = main_guild.get_member(user)

                    if member == None:
                        await message.author.send("It doesn't seem like <@{}> is part of the server! I am sorry, I can't add them to your **conspiracy channel**.".format(user))
                    elif db.isParticipant(user,False,True) == True:
                        if int(db_get(user,'abducted')) == 1:
                            abductees.append(member)
                        elif int(db_get(user,'frozen')) == 1:
                            frozones.append(member)
                        elif db.isParticipant(user,False,False) == False:
                            deadies.append(member)
                        else:
                            viewers.append(member)
                    else:
                        deadies.append(member)

                intro_msg = creation_messages.cc_intro([v.id for v in viewers])

                # Role objects (based on ID)
                roles = main_guild.roles # Roles from the guild
                game_master_role = discord.utils.find(lambda r: r.id == game_master, roles)
                default_permissions = {
                    main_guild.default_role: discord.PermissionOverwrite(read_messages=False,send_messages=False),
                    game_master_role: discord.PermissionOverwrite(read_messages=True,send_messages=True),
                    client.user: discord.PermissionOverwrite(read_messages=True,send_messages=True),
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=True) for member in viewers
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=False) for member in frozones
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,send_messages=False) for member in deadies
                    }
                }

                # Create a new category if needed
                if db.get_category() == None:
                    category = await main_guild.create_category('CC part {}'.format(db.count_categories()), reason='It seems like we couldn\'t use our previous category! Don\'t worry, I just created a new one.')
                    db.add_category(category.id)
                else:
                    category = main_guild.get_channel(db.get_category())

                try:
                    # Create the text channel
                    reason_msg = 'CC requested by ' + message.author.name
                    channel = await main_guild.create_text_channel(
                        name="s{}_{}".format(config.season,element.name),
                        category=category,
                        overwrites=default_permissions,
                        reason=reason_msg)
                    db.add_channel(channel.id,element.owner)
                    await channel.send(intro_msg)

                    # Set all access rules in the database
                    for member in viewers:
                        db.set_user_in_channel(channel.id,member.id,1)
                    for member in frozones:
                        db.set_user_in_channel(channel.id,member.id,2)
                    for member in abductees:
                        db.set_user_in_channel(channel.id,member.id,3)
                    for member in deadies:
                        if db.isParticipant(member.id,True,True) == True:
                            db.set_user_in_channel(channel.id,member.id,4)


                except Exception as e: # Catch any thrown exceptions and send an error to the user.
                    await message.channel.send('It seems like I\'ve encountered an error! Please let the Game Masters know about this!')
                    await botspam_channel.send("Oi, Game Masters! I got a problem concerning channel creation for ya to fix.")
                    await botspam_channel.send(e)
                    raise e # Send the full log to Buddy1913 and his sketchy VM.

                # Give the settlers their own happy little residence
                for buddy in element.settlers:
                    db_set(buddy,"channel",channel.id)

            else:
                """This should not happen, but we'll use it, to prevent the bot from purposely causing an error
                everytime someone attempts to create a channel that contains spaces. 'cause believe me,
                that happens ALL the time."""
                msg = await message.channel.send("I\'m terribly sorry, but you can\'t use spaces in your channel name. Try again!")
                temp_msg.append(msg)

        for element in mailbox.polls:
            # element.channel
            # element.purpose
            # element.user_id
            # element.description

            msg = element.description + '\n'
            emoji_table = []
            msg_table = []
            i = 0

            for user in db.poll_list():
                if db.isParticipant(int(user[0])):
                    i += 1
                    msg += user[1] + " - <@" + str(user[0]) + "> "

                    if int(user[2]) + int(user[3]) > 0:
                        if int(user[2]) == 1:
                            msg += "**[FROZEN]** "
                        if int(user[3]) == 1:
                            msg += "**[ABDUCTED] **"
                    else:
                        emoji_table.append(user[1])

                    if i % 20 == 19:
                        msg = await client.get_channel(element.channel).send(msg)
                        for emoji in emoji_table:
                            await msg.add_reaction(emoji)
                        msg_table.append(msg)
                        msg = ''
                    else:
                        msg += '\n'

            if msg != '':
                msg = await client.get_channel(element.channel).send(msg)
                for emoji in emoji_table:
                    await msg.add_reaction(emoji)
                msg_table.append(msg)
            db.add_poll(msg_table,element.purpose,element.channel,element.user_id)
            await botspam_channel.send("A poll has been created in <#{}>!".format(element.channel))

        for element in mailbox.deletecategories:
            id = element.channel
            category = client.get_channel(id)
            if category != None:
                bot_message = await message.channel.send('Please react with 👍 to confirm deletion of category `' + category.name + '`.\n\nNote: This action will irrevirsibly delete all channels contained within the specified category. Please use with discretion.')
                await bot_message.add_reaction('👍')
                def check(reaction, user):
                    return user == message.author and str(reaction.emoji) == '👍'
                try:
                    reaction, user = await client.wait_for('reaction_add', timeout=30.0, check=check)
                except asyncio.TimeoutError:
                    await message.channel.send('Confirmation timed out.')
                else:
                    await message.channel.send('Ok, I\'ll get right on that.\n\n*This might take some time.*')
                    for channel in category.channels:
                        await channel.delete()
                    await category.delete()
                    await message.channel.send('\n:thumbsup: Channels and category deleted')
            else:
                await message.channel.send('Sorry, I couldn\'t find that category.')

    # Delete all temporary messages after "five" seconds.
    await asyncio.sleep(120)
    for msg in temp_msg:
        await msg.delete()
def devil_victory():
    for user in db.player_list():
        if db.isParticipant(user) and db.db_get(user,'role') not in ['Devil','Demon']:
            if db.db_get(user,'souls') < 0:
                return False
    return True
Exemple #18
0
def use_item(item_code, message):
    user_id = message.author.id
    if not inventory.has_item(user_id, item_code):
        return Mailbox().dm(
            "I'm sorry. You do not have the correct item in your inventory!",
            user_id, True)

    # Invisibility cloak
    if item_code == 100:
        if not db.isParticipant(user_id):
            return Mailbox().dm(
                "You are not a participant! You cannot protect yourself if you're not playing.",
                user_id, True)

        db.db_set(user_id, 'sleepingover', 1)
        inventory.give_item(user_id, 100, -1)
        return Mailbox().dm(
            "You are protected for the night. No-one should be able to find you...",
            user_id
        ).log(
            "<@{}> has used an invisibility cloak to protect themselves for the night!"
            .format(user_id))

    # Bucket of water
    if item_code == 101:
        if not db.isParticipant(user_id):
            return Mailbox().dm(
                "You are not a participant! You cannot unpowder yourself if you're not playing.",
                user_id)

        inventory.give_item(user_id, 101, -1)
        answer = Mailbox().dm(
            "The bucket of water refreshed your senses. If you were powdered, this effect has been undone!",
            user_id)
        if int(db.db_get(user_id, 'powdered')) == 1:
            answer.log(
                "<@{}> has used a bucket of water. They are no longer powdered!"
                .format(user_id))
        else:
            answer.log(
                "<@{}> has used a bucket of water - they weren't powdered, however."
                .format(user_id))
        db.db_set(user_id, 'powdered', 0)
        return answer

    # Royal sword
    if item_code == 102:
        # TODO
        return todo(user_id)

    # Disguise
    if item_code == 103:
        if not db.isParticipant(user_id):
            return Mailbox().dm(
                "You are not a participant! You cannot disguise anyone if you're not playing.",
                user_id, True)

        role = check.roles(message, 1)
        if not role:
            return Mailbox().dm(
                "**INVALID SYNTAX:** No role provided! Please provide a role!",
                user_id, True)

        victim_id = check.users(message, 1, True, True)
        if not victim_id:
            victim_id = [user_id]
        victim_id = victim_id[0]

        user_role = db.db_get(user_id, 'role')

        victim_role = db.db_get(victim_id, 'role')
        victim_frozen = int(db.db_get(victim_id, 'frozen'))
        victim_abducted = int(db.db_get(victim_id, 'abducted'))

        if victim_abducted == 1:
            return Mailbox().dm(
                "After having finished your great disguise, it seems like you couldn\'t find your target! Where have they gone off to?",
                user_id, True)
        if victim_frozen == 1:
            return Mailbox().dm(
                "I am sorry, but <@{}> is too cold for that! You\'ll need a lot more than warm suit to get \'em warmed up."
                .format(victim_id), user_id, True)

        db.db_set(victim_id, 'fakerole', role)
        inventory.give_item(user_id, 103, -1)
        answer = Mailbox().dm(
            "You have successfully disguised <@{}> as the **{}**!".format(
                victim_id, role), user_id)

        answer.log(
            "With a disguise from their inventory, **{}** <@{}> has disguised <@{}>, the **{}**, as the **{}**!"
            .format(user_role, user_id, victim_id, victim_role, role))
        if victim_role == role:
            answer.log_add(
                "\n...does that sound stupid? *Of course!* But how are they supposed to know?"
            )
        return answer

    # Name tag
    if item_code == 104:
        # TODO
        return todo(user_id)

    # Med kit
    if item_code == 105:
        pass

    # Dagger
    if item_code == 106:
        if not db.isParticipant(user_id):
            return Mailbox().dm(
                "You are not a participant! You cannot attack anyone if you're not playing.",
                user_id, True)

        if user_id == victim_id:
            return Mailbox().respond(
                "I am sorry, but you cannot attempt suicide!\nNot because it's not an option, no, just because we want to see you SUFFER!",
                True)

        if int(db.db_get(victim_id, 'abducted')) == 1:
            return Mailbox().respond(
                "You attempted to attack <@{}>... but they don't seem to be around in town! That is strange."
                .format(victim_id), True)
        if int(db.db_get(victim_id, 'frozen')) == 1:
            return Mailbox().respond(
                "You wanted to pay a visit to <@{}>... but it seems they were frozen! Try again, please."
                .format(victim_id), True)

        inventory.give_item(user_id, 106, -1)
        db.add_kill(victim_id, 'Assassin', user_id)

        answer = Mailbox().dm(
            "You have successfully used a **Dagger** to assasinate <@{}>. They will die when the time shifts!",
            user_id, True)
        return answer.log(
            "<@{}> has used a **Dagger** to assassinate <@{}>.".format(
                user_id, victim_id))
def ice_victory():
    """This function returns true if the ice kings have won."""
    for user in db.player_list():
        if db.isParticipant(user) and db.db_get(user,'frozen') == 0 and db.db_get(user,'role') != 'Ice King':
            return False
    return True
Exemple #20
0
def process(message, isGameMaster=False, isAdmin=False, isPeasant=False):
    user_id = message.author.id
    message_channel = message.channel.id

    help_msg = "**List of commands:**\n"

    args = message.content.split(' ')

    # =============================================================
    #
    #                         BOT COMMANDS
    #
    # =============================================================
    if isPeasant == True:
        pass

    # =============================================================
    #
    #                         ADMINISTRATOR
    #
    # =============================================================
    if isAdmin == True:
        help_msg += "\n __Admin commands:__\n"

    elif is_command(message, ['delete_category','start']):
        return [Mailbox().respond(PERMISSION_MSG.format("Administrator"), True)]


    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:
        help_msg += "\n__Game Master commands:__\n"

        if is_command(message, ['userinv','userinventory']):
            target = check.users(message)
            if not target:
                return [Mailbox().respond("**INVALID SYNTAX:**\nNo target provided!",True)]

            answer = Mailbox().spam("**__<@{}>'S BALANCE__**".format(target[0]))

            for item in items.jget("items"):
                if has_item(target[0],item["code"]):
                    answer.spam_add('\n{}x - **'.format(has_item(target[0],item["code"],False)) + item["name"] + '**')
            return [answer]
        if is_command(message, ['userinv','userinventory'], True):
            return todo()
        help_msg += "`" + prefix + "userinv` - View a user's inventory.\n"

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Game Master"), True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):
        help_msg += "\n__Participant commands:__\n"

        user_undead = int(db_get(user_id,'undead'))

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Participant"), True)]


    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    help_msg += '\n\n'

    '''buy'''
    if is_command(message, ['buy']):
        number = check.numbers(message)
        if not number:
            return [Mailbox().dm("No amount provided! Please provide me with a number!",True)]
        answer = [Mailbox().dm(shop.buy(user_id,number[0],message.author.name),user_id)]
    if is_command(message, ['buy'], True):
        msg = "**Usage:** Buy an item from the shop.\n\n`" + prefix + "buy <n>`\n\n"
        msg += "**Example:** `" + prefix + "buy 1`"
        return [Mailbox().respond(msg,True)]
    help_msg += "`" + prefix + "buy` - Buy item from the shop.\n"

    '''inventory'''
    if is_command(message, ['inv','inventory','bal','balance']):
        answer = Mailbox().dm("**__YOUR CURRENT BALANCE__**",user_id)
        for item in items.jget("items"):
            if has_item(user_id,item["code"]):
                answer.dm_add('\n{}x - **'.format(has_item(user_id,item["code"],False)) + item["name"] + '**')
        return [answer]
    if is_command(message, ['inv','inventory','bal','balance'], True):
        return todo()
    help_msg += "`" + prefix + "inventory` - View your inventory.\n"

    '''sell'''
    if is_command(message, ['sell']):
        number = check.numbers(message)
        if not number:
            return [Mailbox().dm("No amount provided! Please provide me with a number!",True)]
        answer = [Mailbox().dm(shop.sell(user_id,number[0],message.author.name),user_id)]
    if is_command(message, ['sell'], True):
        msg = "**Usage:** Sell an item from the shop.\n\n`" + prefix + "sell <n>`\n\n"
        msg += "**Example:** `" + prefix + "sell 1`"
        return [Mailbox().respond(msg,True)]
    help_msg += "`" + prefix + "sell` - Buy item from the shop.\n"

    '''shop'''
    if is_command(message, ['shop']):
        answer = Mailbox()

        for msg in shop.get_market_message():
            answer.respond(msg,True)
        
        return answer
    if is_command(message, ['shop']):
        msg = "**Usage:** View the Devil Bot's shop.\n\n`" + prefix + "shop`"
        return [Mailbox().respond(msg,True)]
    help_msg += "`" + prefix + "shop` - View the Devil's shop."

    help_msg += "\n\n__Item specific commands:__"

    '''attack'''
    if is_command(message, ['attack', 'dagger', 'kill']):
        pass # TODO

    '''disguise'''
    if is_command(message,['disguise','dis']):
        return [use_item(103,message)]
    if is_command(message,['disguise','dis'],True):
        msg = "**Usage:** Disguise a participant.\n\n`" + prefix + "disguise @Randium#6521 Innocent`\n\n"
        msg += "This command can only be used by participants. You can disguise yourself."
        return [Mailbox().respond(msg,True)]
    help_msg += "`" + prefix + "disguise` - Disguise a participant.\n"

    '''hide'''
    if is_command(message,['hide']):
        return [use_item(100,message)]
    if is_command(message,['disguise','dis'],True):
        msg = "**Usage:** Disguise a participant.\n\n`" + prefix + "disguise @Randium#6521 Innocent`\n\n"
        msg += "This command can only be used by participants. You can disguise yourself."
        return [Mailbox().respond(msg,True)]
    help_msg += "`" + prefix + "hide` - Become invisible for the night.\n"

    # --------------------------------------------------------------
    #                          HELP
    # --------------------------------------------------------------
    help_msg += "\n\n*If you have any more questions, feel free to ask any of the Game Masters!*"

    '''help'''
    if is_command(message,['help']) and is_command(message,['help'],True) == False:
        return [Mailbox().respond(help_msg,True)]
    if is_command(message,['help'],True):
        answer = Mailbox().respond("Hey there! `" + prefix + "help` will give you a list of commands that you can use.")
        answer.respond_add("\nIf you have any questions, feel free to ask any of the Game Masters!")
        return [answer]

    if message.content.startswith(prefix):
        return [Mailbox().respond("Sorry bud, couldn't find what you were looking for.", True)]

    return []
Exemple #21
0
def process(message, isGameMaster=False, isAdmin=False, isPeasant=False):
    user_id = message.author.id
    message_channel = message.channel.id

    help_msg = "**List of commands:**\n"

    args = message.content.split(' ')

    # =============================================================
    #
    #                         BOT COMMANDS
    #
    # =============================================================
    if isPeasant == True:

        if is_command(message, ['success']):
            token = args[1]
            choice = args[2]

            if box.token_status(token) != 2:
                return []

            data = box.get_token_data(token)
            given_options = [int(data[3]), int(data[4]), int(data[5])]

            if choice not in given_options:
                return [
                    Mailbox().respond("Invalid choice!", True).spam(
                        "A webhook has given an invalid bug. This means one of the following two things;\n1. There's bug;\n2. Someone's trying to hack the bots through a webhook.\n\nBoth are not good."
                    )
                ]

            box.add_choice(token, choice)
            return [
                Mailbox().respond(
                    "Got it! Thanks.\n*(Well, not really, this still needs to be done, but...)*"
                )
            ]

    # =============================================================
    #
    #                         ADMINISTRATOR
    #
    # =============================================================
    if isAdmin == True:
        help_msg += "\n __Admin commands:__\n"

    elif is_command(message, ['delete_category', 'start']):
        return [
            Mailbox().respond(PERMISSION_MSG.format("Administrator"), True)
        ]

    # =============================================================
    #
    #                         GAME MASTERS
    #
    # =============================================================
    if isGameMaster == True:
        help_msg += "\n__Game Master commands:__\n"

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Game Master"), True)]

    # =============================================================
    #
    #                         PARTICIPANTS
    #
    # =============================================================

    if isParticipant(user_id):
        help_msg += "\n__Participant commands:__\n"

        user_undead = int(db_get(user_id, 'undead'))

    elif is_command(message, []):
        return [Mailbox().respond(PERMISSION_MSG.format("Participant"), True)]

    # =============================================================
    #
    #                         EVERYONE
    #
    # =============================================================

    help_msg += '\n\n'

    if is_command(message, ['lead']):
        number = check.numbers(message)
        if not number:
            return [Mailbox().respond(gen.gain_leaderboard(user_id))]
        return [
            Mailbox().respond(gen.gain_leaderboard(user_id, max(number)), True)
        ]
    if is_command(message, ['lead'], True):
        msg = "**Usage:** Gain a list of the most active users on the server.\n\n`" + prefix + "leaderboard <number>`\n\n"
        msg += "**Example:** `" + prefix + "lead 10`.\nThe number is optional, and doesn't have to be given."
    help_msg += "`" + prefix + "lead` - See an activity leaderboard.\n"

    # Profile commands
    profile_commands = process_profile(message=message,
                                       is_game_master=isGameMaster,
                                       is_admin=isAdmin,
                                       is_peasant=isPeasant)
    if profile_commands:
        return profile_commands

    help_msg += "`" + prefix + "age` - Set your age\n"
    help_msg += "`" + prefix + "bio` - Set your bio\n"
    help_msg += "`" + prefix + "gender` - Set your gender\n"
    help_msg += "`" + prefix + "profile` - View a player's profile\n"

    # --------------------------------------------------------------
    #                          HELP
    # --------------------------------------------------------------
    help_msg += "\n\n*If you have any more questions, feel free to ask any of the Game Masters!*"
    '''help'''
    if is_command(message, ['help']) and is_command(message, ['help'],
                                                    True) == False:
        return [Mailbox().respond(help_msg, True)]
    if is_command(message, ['help'], True):
        answer = Mailbox().respond(
            "Hey there! `" + prefix +
            "help` will give you a list of commands that you can use.")
        answer.respond_add(
            "\nIf you have any questions, feel free to ask any of the Game Masters!"
        )
        return [answer]

    if message.content.startswith(prefix):
        return [
            Mailbox().respond(
                "Sorry bud, couldn't find what you were looking for.", True)
        ]

    return []