コード例 #1
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)]
コード例 #2
0
ファイル: check.py プロジェクト: werewolves-devs/Poll-Bot
def users(message, amount=-1, delete_duplicates=True):
    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(response)

    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)]
コード例 #3
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
コード例 #4
0
ファイル: ww_head.py プロジェクト: abdulrabiu/Werewolf_Bot
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 []
コード例 #5
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()
コード例 #6
0
def count_votes(voting_table, purpose='lynch', mayor=0):
    """Count votes based on reactions given to """
    user_table = []
    blacklist = []
    blacklist2 = []
    emoji_table = []

    for vote in voting_table:
        # Add new emoji
        if vote[1] not in emoji_table:
            emoji_table.append(vote[1])

        # Filter self-votes and double votes
        if vote[0] in blacklist or vote[0] in blacklist2:
            pass
        elif vote[0] == emoji_to_player(
                vote[1]) and purpose not in ['Mayor', 'Reporter']:
            blacklist2.append(vote[0])
            if vote[0] in user_table:
                user_table.remove(vote[0])
        elif vote[0] in user_table:
            blacklist.append(vote[0])
            user_table.remove(vote[0])
        else:
            user_table.append(vote[0])

    # Evaluate table, filter double votes and continue
    if purpose == 'lynch':
        voting_table = [
            Vote(vote[0], vote[1], int(db_get(vote[0], 'votes')))
            for vote in voting_table if vote[0] in user_table
        ]
    else:
        voting_table = [
            Vote(vote[0], vote[1]) for vote in voting_table
            if vote[0] in user_table
        ]
    blacklist = [Disqualified(user) for user in blacklist]
    blacklist2 = [Disqualified(user, 1) for user in blacklist2]
    blacklist.extend(blacklist2)

    # Add extra (secret) outside lynches, may some special events happen.
    if purpose == 'lynch':
        for user in player_list():
            if int(db_get(user, 'threatened')) > 0:
                voting_table.append(
                    Vote("RAVEN THREAT", db_get(user, 'emoji'),
                         int(db_get(user, 'threatened'))))

                # Add emoji to table
                if db_get(user, 'emoji') not in emoji_table:
                    emoji_table.append(db_get(user, 'emoji'))

    # print([[vote.user,vote.emoji,vote.votes] for vote in voting_table])

    # Create the evaluation messages
    answer = "**__Poll results "
    log = "**__Poll results "

    if purpose == 'wolf':
        answer += "from wolf attack:__**\n\n"
        log += "from wolf attack:__**\n\n"
    elif purpose == 'cult':
        answer += "from cult attack:__**\n\n"
        log += "from cult attack:__**\n\n"
    elif purpose == 'thing':
        answer += "from the swamp:__**\n\n"
        log += "from the swamp:__**\n\n"
    elif purpose == 'lynch':
        answer += "from public execution on day {}:__**\n\n".format(
            day_number())
        log += "from public execution on day {}:__**\n\n".format(day_number())
    elif purpose == 'Mayor':
        answer += "from Mayor election:__**\n\n"
        log += "from Mayor election:__**\n\n"
    elif purpose == 'Reporter':
        answer += "from Reporter election:__**\n\n"
        log += "from Reporter election:__**\n\n"

    max_i = 0
    chosen_emoji = ''

    for emoji in emoji_table:
        emoji_votes = [vote for vote in voting_table if vote.emoji == emoji]

        if emoji_votes != []:
            for vote in emoji_votes:
                if vote.type == 'user':
                    answer += "**{} - VOTES FOR <@{}>:**\n".format(
                        emoji, emoji_to_player(emoji))
                    break
            log += "**{} - VOTES FOR <@{}>:**\n".format(
                emoji, emoji_to_player(emoji))
        i = 0

        for vote in emoji_votes:
            # vote.user
            # vote.type
            # vote.emoji
            # vote.votes
            if vote.type == 'user':
                answer += "<@{}> ".format(vote.user)
                log += "<@{}> ".format(vote.user)
                if vote.user == mayor:
                    vote.votes += 1
                    answer += "- @Mayor "
                    log += "- @Mayor "
                if vote.votes != 1:
                    log += "*({}x)* ".format(vote.votes)
                i += vote.votes
                log += '\n'
                answer += '\n'
            elif vote.type == 'generic':
                log += "{} ".format(vote.user)
                if vote.votes > 1:
                    log += "*({}x)* ".format(vote.votes)
                i += vote.votes
                log += '\n'
            else:
                answer += "*Oops! An error occured on this line!*\n"
                log += "*Oops! An error occured on this line! Looks like we\'ve got an undefined voting type!*\n"

        if i > 0:
            log += "**TOTAL: {} votes**\n\n".format(i)
        else:
            log += '\n\n'

        if i == max_i:
            chosen_emoji = ''
        if i > max_i:
            chosen_emoji = emoji
            max_i = i

    answer += "\n"
    log += "\n"

    for cheater in blacklist:
        if cheater.reason == 0:
            answer += "<@{}>, you have been disqualified for double voting.\n".format(
                cheater.user)
            log += "<@{}> has been disqualified for double voting.\n".format(
                cheater.user)
        if cheater.reason == 1:
            answer += "<@{}>, your vote has been disqualified for you may not vote for yourself on this poll.\n".format(
                cheater.user)
            log += "<@{}> has been disqualified for voting on themselves.\n".format(
                cheater.user)

    if chosen_emoji != '':
        answer += "\nThe emoji {} has the most votes, making <@{}> the winner of this poll!".format(
            chosen_emoji, emoji_to_player(chosen_emoji))
        log += "\nThe emoji {} has the most votes, effectively making <@{}> the winner of this poll.".format(
            chosen_emoji, emoji_to_player(chosen_emoji))
    elif emoji_table != []:
        answer += "\nIt seems like we\'ve reached a tie! No-one will win this poll, I\'m sorry!"
        log += "\nThe poll has reached a tie and will not choose a winner."
    else:
        answer += "\nIt seems like no-one has voted! Well, in that case, there won\'t be a winner either."
        log += "\nNo votes have been registered."

    return log, answer, chosen_emoji