Пример #1
0
async def create_game(client, message):
    # Get the second player
    join_request = await client.send_message(
        message.channel, "One more player needed. "
        "Reply '>Join' in 30 seconds to join")
    reply = await client.wait_for_message(timeout=30,
                                          channel=message.channel,
                                          content=">Join")
    if reply.content is None:
        # Delete the call for players, & close the game
        await client.send_message(message.channel,
                                  "Game cancelled: Player timeout reached")
        await client.delete_message(join_request)
        return -1

    # Create a game channel
    default_permissions = PermissionOverwrite(read_messages=False)
    player_permissions = PermissionOverwrite(read_messages=True)
    channel = await client.create_channel(
        message.server,
        'checkers', (message.server.default_role, default_permissions),
        (message.server.me, player_permissions),
        (message.author, player_permissions),
        (reply.author, player_permissions),
        type=ChannelType.text)
    checkers = Checkers(client, channel, message.channel,
                        [message.author, message.author])
    await checkers.announcerules()

    return checkers, "checkers"
Пример #2
0
    async def start_voice(self, a, b, session_id):
        """ Begin voice chat session between two people """
        everyone_perms = PermissionOverwrite(read_messages=False)
        my_perms = PermissionOverwrite(read_messages=True)
        guild = self.bot.get_guild(self.guild_id)
        if guild is None:
            raise ConnectionError(f"Cannot connect to Guild({GUILD_ID})")
        ch = await guild.create_voice_channel(f"{SESSION_CHANNEL_PREFIX}{a.name}-{b.name}",
                                              overwrites={guild.default_role: everyone_perms, a: my_perms, b: my_perms},
                                              category=self.bot.get_channel(self.category_channel_id))
        self.active_channels.add(ch)

        # Move members into voice channel
        a_member = guild.get_member(a.id)
        b_member = guild.get_member(b.id)
        await a_member.edit(voice_channel=ch)
        await b_member.edit(voice_channel=ch)

        logging.info(f"Waiting for users {a} and {b} to join Voice Channel...")

        async def ch_filled():
            """ Ensure both members have joined the voice chat. """
            while not len(self.bot.get_channel(ch.id).members) == 2:
                await asyncio.sleep(.1)

        try:
            await asyncio.wait_for(ch_filled(), PREP_TIME)
        except asyncio.TimeoutError:
            logging.info(f"Members didn't connect. Closing session {session_id}...")
            await self.close_session(a, b, ch)
        else:
            logging.info(f"Beginning Session [{session_id}]({a}, {b})...")
            await asyncio.sleep(SESSION_TIME)
            await self.end_voice(a, b, ch, session_id)
Пример #3
0
 async def save_guild_config(self, guild: Guild, config: Dict[str, Any]):
     for channel in guild.text_channels:
         if channel.name == self.BOT_CONFIG_CHANNEL:
             config_channel = channel
             break
     else:
         config_channel = await guild.create_text_channel(
             self.BOT_CONFIG_CHANNEL,
             overwrites={
                 guild.default_role: PermissionOverwrite(
                     read_messages=False
                 ),
                 self.user: PermissionOverwrite(read_messages=True)
             }
         )
     json_config = json.dumps(config, separators=(',', ':'))
     i = 0
     # last_message = config_channel.last_message
     # async for message in config_channel.history(before=last_message):
     #     await message.delete()
     # if last_message:
     #     await last_message.delete()
     while True:
         json_chunk = json_config[i*1990:(i+1)*1990]
         if not json_chunk:
             break
         await config_channel.send(
             f'```\n{"^" if i != 0 else ""}{json_chunk}```'
         )
         i += 1
Пример #4
0
    async def on_guild_join(self, guild: Guild):
        if guild.id not in self.join_locks:
            self.join_locks[guild.id] = Event()

        debug(f"Setting up Configuration for guild {guild.name}")

        if not self.permission_check(guild):
            await guild.text_channels[0].send(
                "I don't have the correct permissions, make sure manage_channels and"
                " manage_messages are enabled.")
            await guild.leave()
            return

        overwrites = {
            guild.default_role: PermissionOverwrite(read_messages=False),
            guild.me: PermissionOverwrite(read_messages=True,
                                          manage_messages=True),
            **{
                role: PermissionOverwrite(read_messages=True)
                for role in guild.roles if role.permissions.manage_channels
            }
        }

        channel = await guild.create_text_channel(
            self.bot.channel_name,
            overwrites=overwrites,
            topic=
            "This is the configuration channel for f-lute, please do NOT delete this, or the bot will leave"
        )

        self.join_locks[guild.id].set()
Пример #5
0
async def hide(ctx):
    """Makes voice channel invisible // can only be used by channel owner."""
    await bot.wait_until_ready()
    channeldata = load_json(channeldata_file)
    if str(ctx.message.author.id) in [
            x for v in channeldata.values() for x in v
    ]:
        channel_id = get_key(str(ctx.message.author.id), channeldata)
        channel_obj = ctx.guild.get_channel(int(channel_id))
        # if channel_obj.name.startswith(emotes[2]): // prevented by 2 name edits per 10 min rate limit :(
        # await channel_obj.edit(name=emotes[2] + channel_obj.name)
        # // prevented by 2 name edits per 10 min rate limit :(
        overwrites = PermissionOverwrite(view_channel=False)
        await channel_obj.set_permissions(target=ctx.guild.default_role,
                                          overwrite=overwrites)
        for m in channel_obj.members:
            await channel_obj.set_permissions(
                target=m, overwrite=PermissionOverwrite(view_channel=True))
        channeldata[channel_id] = [str(ctx.message.author.id), "true"]
        json_file = open(channeldata_file, 'w+')
        json_file.write(json.dumps(channeldata, indent=4))
        json_file.close()
        await ctx.message.delete()
    else:
        embed = discord.Embed(
            title='',
            description='{} You do not own a channel!'.format(emotes[4]),
            color=embed_color)
        await ctx.channel.send(embed=embed)
Пример #6
0
async def lock(ctx):
    """Makes voice channel private // can only be used by channel owner."""
    await bot.wait_until_ready()
    channeldata = load_json(channeldata_file)
    if str(ctx.message.author.id) in [
            x for v in channeldata.values() for x in v
    ]:
        channel_obj = ctx.guild.get_channel(
            int(get_key(str(ctx.message.author.id), channeldata)))
        # if emotes[0] in channel_obj.name:
        # embed = discord.Embed(
        # title='',
        # description='{} is already locked!'.format(channel_obj.name),
        # color=embed_color
        # )
        # await ctx.send(embed=embed)

        # c_name = channel_obj.name.replace(emotes[1], emotes[0])  # Replace unlock with lock.
        # await channel_obj.edit(name=c_name)
        # // prevented by 2 name edits per 10 min rate limit :(
        overwrites = PermissionOverwrite(connect=False)
        await channel_obj.set_permissions(target=ctx.guild.default_role,
                                          overwrite=overwrites)
        for m in channel_obj.members:
            await channel_obj.set_permissions(
                target=m, overwrite=PermissionOverwrite(connect=True))
        await ctx.message.add_reaction(emotes[0])
    else:
        embed = discord.Embed(
            title='',
            description='{} You do not own a channel!'.format(emotes[4]),
            color=embed_color)
        await ctx.channel.send(embed=embed)
Пример #7
0
    def get_overwrites(members: t.List[Member], guild: Guild) -> t.Dict[t.Union[Member, Role], PermissionOverwrite]:
        """Get code jam team channels permission overwrites."""
        # First member is always the team leader
        team_channel_overwrites = {
            members[0]: PermissionOverwrite(
                manage_messages=True,
                read_messages=True,
                manage_webhooks=True,
                connect=True
            ),
            guild.default_role: PermissionOverwrite(read_messages=False, connect=False),
            guild.get_role(Roles.verified): PermissionOverwrite(
                read_messages=False,
                connect=False
            )
        }

        # Rest of members should just have read_messages
        for member in members[1:]:
            team_channel_overwrites[member] = PermissionOverwrite(
                read_messages=True,
                connect=True
            )

        return team_channel_overwrites
Пример #8
0
 async def on_voice_state_update(self, member, before, after):
     if after.channel != None:
         channelQ = get_private(after.channel.id)
     else:
         channelQ = get_private(before.channel.id)
     if channelQ != None:
         channels = session.query(Private).all()
         if after.channel == None:
             channelQ.count_members = 0
         else:
             channelQ.count_members = len(after.channel.members)
         for channel in channels:
             channeld = member.guild.get_channel(channel.channel_id)
             if channeld.members == []:
                 await channeld.delete()
                 session.delete(channel)
         session.commit()
     else:
         if after.channel.id == 649676227329654834:
             channel = await member.guild.create_voice_channel(
                 member.name, category=after.channel.category)
             add_private(Private(channel_id=channel.id, count_members=1))
             await member.move_to(channel)
             overwrite = PermissionOverwrite()
             overwrite.manage_channels = True
             await channel.set_permissions(member, overwrite=overwrite)
Пример #9
0
    async def test_sent_correct_message(self):
        """Appropriate failure/success message was sent by the command."""
        unsilenced_overwrite = PermissionOverwrite(send_messages=True, add_reactions=True)
        test_cases = (
            (True, silence.MSG_UNSILENCE_SUCCESS, unsilenced_overwrite),
            (False, silence.MSG_UNSILENCE_FAIL, unsilenced_overwrite),
            (False, silence.MSG_UNSILENCE_MANUAL, self.text_overwrite),
            (False, silence.MSG_UNSILENCE_MANUAL, PermissionOverwrite(send_messages=False)),
            (False, silence.MSG_UNSILENCE_MANUAL, PermissionOverwrite(add_reactions=False)),
        )

        targets = (None, MockTextChannel())

        for (was_unsilenced, message, overwrite), target in itertools.product(test_cases, targets):
            ctx = MockContext()
            ctx.channel.overwrites_for.return_value = overwrite
            if target:
                target.overwrites_for.return_value = overwrite

            with mock.patch.object(self.cog, "_unsilence", return_value=was_unsilenced):
                with mock.patch.object(self.cog, "send_message") as send_message:
                    with self.subTest(was_unsilenced=was_unsilenced, overwrite=overwrite, target=target):
                        await self.cog.unsilence.callback(self.cog, ctx, channel=target)

                        call_args = (message, ctx.channel, target or ctx.channel)
                        send_message.assert_awaited_once_with(*call_args, alert_target=was_unsilenced)
Пример #10
0
    async def update_board_for_turn(self, board: ConnectFourBoard) -> None:
        ow: dict = self.channel.overwrites

        if self.player_one:
            allow = not board.is_connect_four and self.is_player_ones_turn
            if board.play_count == 1 and self.last_move_by.id == self.player_one.id:
                allow = False

            ow[self.player_one.member] = PermissionOverwrite(
                read_messages=True, send_messages=allow)

        if self.player_two:
            allow = not board.is_connect_four and (
                not self.is_player_ones_turn)
            ow[self.player_two.member] = PermissionOverwrite(
                read_messages=True, send_messages=allow)

        if board.is_connect_four:
            ow[self.channel.guild.default_role] = PermissionOverwrite(
                read_messages=True, send_messages=False)

        await self.channel.edit(overwrites=ow)

        if board.is_connect_four:
            await self.channel.send("CONNECT FOUR {0} !!!!".format(
                self.last_move_by.mention))
            await self.channel.send("This game will close in 15 seconds")
Пример #11
0
async def rebuild_course_channels(ctx):
    if not roles["admin"] in ctx.author.roles:
        await handle_no_permissions(ctx)
        return
    await ctx.message.add_reaction('✅')
    for course in courses_by_degree:
        permissions = {
            guild.default_role: PermissionOverwrite(read_messages=False)
        }
        for degree in courses_by_degree[course]['degrees']:
            degree_obj = next(
                (item for item in degrees if item["name"] == degree), None)
            if degree_obj is not None:
                permissions[degree_obj["role"]] = PermissionOverwrite(
                    read_messages=True)

        course_channel = get(courses_category.text_channels,
                             name=course.lower())
        if course_channel is None:
            await courses_category.create_text_channel(
                course.lower(),
                overwrites=permissions,
                topic=courses_by_degree[course]['name'])
        else:
            await course_channel.edit(overwrites=permissions,
                                      topic=courses_by_degree[course]['name'])
Пример #12
0
    async def create_game_channel(self, name: str, user: BunkUser, all_users: bool = True) -> TextChannel:
        channel: TextChannel = None
        game_channel: str = self.config.custom_games_channel

        if game_channel is not None:
            gc_ref: TextChannel = await self.channels.get_by_name(game_channel)
            c_name: str = "{0}-{1}".format(name, user.name)

            ow: dict = { 
                self.server.default_role: PermissionOverwrite(read_messages=all_users, send_messages=all_users),
                self.server.get_member(user.id): PermissionOverwrite(read_messages=True, send_messages=True),
                self.server.get_member(self.bot.user.id): PermissionOverwrite(read_messages=True, send_messages=True)
            }

            if gc_ref is not None:
                is_cat: bool = isinstance(gc_ref, CategoryChannel)

                if not is_cat:
                    await self.channels.log_error("Cannot create game under a non-category channel.", "GameService")
                else:
                    c_name = self.get_game_name(gc_ref, c_name)
                    channel = await gc_ref.create_text_channel(c_name, overwrites=ow, slowmode_delay=1)
            else:
                c_name = self.get_game_name(None, c_name)
                channel = await self.bot.server.create_text_channel(c_name, overwrites=ow, slowmode_delay=1)
        else:
            await self.channels.log_error("Cannot create custom game - CUSTOM-GAMES channel cannot be found", "GameService")

        return channel
Пример #13
0
    async def create_gamemode(self, ctx: Context, gamemode: str):
        gamemode_identifier = gamemode.lower()
        api: Api = self.bot.get_cog("Api")
        guild_config: dict = api.get_server_settings(ctx.guild)

        if guild_config is None:
            return await ctx.send(
                "Please set up the config first."
                f" This can be done by running the {ctx.prefix}setup command")
        if gamemode_identifier in guild_config["matchmaking_channels"].keys():
            return await ctx.send("A gamemode with this name already exists?")

        matchmaking_category = self.bot.get_channel(
            guild_config["categories"]["matchmaking"])
        if matchmaking_category is None:
            return await ctx.send(
                "What the hell did you do? Contact support right now to get this resolved."
            )
        configured_user_role = ctx.guild.get_role(
            guild_config["roles"]["configured"])
        matchmaking_category_permissions = {
            configured_user_role:
            PermissionOverwrite(read_messages=True),
            ctx.guild.default_role:
            PermissionOverwrite(read_messages=False, speak=False)
        }
        vc = await matchmaking_category.create_voice_channel(
            name=gamemode,
            overwrites=matchmaking_category_permissions,
            reason="[Que-Management] Adding new gamemode")
        guild_config["matchmaking_channels"][gamemode_identifier] = vc.id
        api.update_server_settings(ctx.guild, guild_config)
        await ctx.send("Updated!")
Пример #14
0
async def mute(cmd, message, args):
    channel = message.channel
    server = message.server
    if not message.mentions:
        await cmd.bot.send_message(message.channel, cmd.help())
        return
    user_q = message.mentions[0]
    overwrite = PermissionOverwrite()
    overwrite.send_messages = False
    if message.author is not user_q:
        if check_man_msg(message.author, channel) and check_man_roles(
                message.author, channel):
            try:
                for chan in server.channels:
                    if str(chan.type).lower() == 'text':
                        if check_write(user_q, chan):
                            await cmd.bot.edit_channel_permissions(
                                chan, user_q, overwrite)
                await cmd.bot.send_message(
                    message.channel, 'Execution Successful.\nUser **' +
                    user_q.name + '** was muted')
            except Exception as e:
                cmd.log.error(e)
                await cmd.bot.send_message(message.channel, str(e))
        else:
            response = await cmd.bot.send_message(
                message.channel,
                'Only a user with the **Manage Messages and Manage Roles** privilege can use this command. :x:'
            )
            await asyncio.sleep(10)
            await cmd.bot.delete_message(response)
Пример #15
0
    async def create_team(bot: Bot, team: str, author: Member) -> Role:
        """creates a new team"""
        team_role: Optional[Role] = get(bot.guilds[0].roles, name=team)
        if team_role is not None:
            return team_role

        team_role: Role = await bot.guilds[0].create_role(name=team,
                                                          color=get_color())

        await bot.guilds[0].get_member(author.id).add_roles(team_role)

        t_cat_overwrites = {
            bot.guilds[0].default_role:
            PermissionOverwrite(**{"view_channel": False}),
            team_role:
            PermissionOverwrite(**{"view_channel": True})
        }
        team_category: CategoryChannel = await bot.guilds[0].create_category(
            name=team, overwrites=t_cat_overwrites)

        t_cha_overwrites = {
            bot.guilds[0].default_role:
            PermissionOverwrite(**{"view_channel": False}),
            team_role:
            PermissionOverwrite(**{"view_channel": True})
        }
        await bot.guilds[0].create_text_channel(name="Team Chat",
                                                overwrites=t_cha_overwrites,
                                                category=team_category)

        await bot.guilds[0].create_voice_channel(name="Team Talk",
                                                 overwrites=t_cha_overwrites,
                                                 category=team_category)

        return team_role
Пример #16
0
 def update_overwrite(ctx: commands.Context,
                      overwrite: discord.PermissionOverwrite,
                      permissions: dict):
     base_perms = dict(iter(discord.PermissionOverwrite()))
     old_perms = copy(permissions)
     user_perms = ctx.channel.permissions_for(ctx.author)
     invalid_perms = []
     valid_perms = []
     not_allowed: List[str] = []
     for perm in old_perms.keys():
         if perm not in base_perms.keys():
             invalid_perms.append(f"`{perm}`")
             del permissions[perm]
         else:
             valid_perms.append(f"`{perm}`")
     overwrite.update(**permissions)
     if invalid_perms:
         invalid = (
             f"\nThe following permissions were invalid:\n{humanize_list(invalid_perms)}\n"
         )
         possible = humanize_list(
             [f"`{perm}`" for perm in base_perms.keys()])
         invalid += f"Possible permissions are:\n{possible}"
     else:
         invalid = ""
     return overwrite, valid_perms, invalid, not_allowed
Пример #17
0
    async def _create_anonc_chat_channel(self, guild, member) -> AnoncChannel:
        overwrites = {
            guild.default_role:
            PermissionOverwrite.from_pair(
                Permissions.none(),  # allow
                Permissions.all()  # deny
            ),
            member:
            PermissionOverwrite(send_messages=True,
                                read_messages=True,
                                manage_messages=True,
                                attach_files=True,
                                read_message_history=True)
        }

        anonc_id = random_string(4)
        while self.get_anonc_chat_channel_from_anonc_id(anonc_id):
            anonc_id = random_string(4)

        anonc_id_role = None
        if self.use_role:
            anonc_id_role = await guild.create_role(name=anonc_id,
                                                    mentionable=True)

        channel = await guild.create_text_channel('anon chat',
                                                  overwrites=overwrites,
                                                  topic=anonc_id,
                                                  nsfw=self.nsfw)
        webhook = await channel.create_webhook(name=str(member.id))

        return AnoncChannel(channel, webhook, member, anonc_id_role)
Пример #18
0
 async def close(self, ctx):
     if ctx.channel.name != 'submission-discussion':
         return
     if not ctx.channel.permissions_for(ctx.author).administrator:
         return
     overwrites = ctx.channel.overwrites
     for key, value in overwrites.items():
         if isinstance(key, Member):
             author = key
             break
     overwrites = {
         ctx.guild.default_role:
         PermissionOverwrite(read_messages=False),
         author:
         PermissionOverwrite(read_messages=True,
                             send_messages=False,
                             add_reactions=False),
         self.admin_role:
         PermissionOverwrite(read_messages=True,
                             send_messages=True,
                             add_reactions=True)
     }
     embed = Embed(title="This discussion has been closed.", color=0x4F71C6)
     await ctx.channel.send(embed=embed)
     await ctx.channel.edit(name=ctx.channel.name + '-' + str(author.id),
                            category=self.archived_submissions_category,
                            overwrites=overwrites,
                            sync_permissions=True)
Пример #19
0
async def on_voice_state_update(user, vc_before, vc_after):
    global guild
    #remove permissions from previous channel first
    if vc_before.channel != None:
        #Skip non join/leave/switch vc channel events
        if vc_before.channel == vc_after.channel:
            return

        vc_txt_before = get_channel_name(vc_before.channel.name)

        channel = get(vc_before.channel.category.text_channels,
                      name=vc_txt_before)
        #Txt Channel might not exist the first few times
        if channel != None:
            if len(vc_before.channel.members) == 0:
                await channel.delete()
            else:
                await channel.set_permissions(user, read_messages=False)

    if vc_after.channel != None:
        vc_txt_after = get_channel_name(vc_after.channel.name)
        channel = get(vc_after.channel.category.text_channels,
                      name=vc_txt_after)
        if channel == None:
            overwrites = {
                guild.default_role: PermissionOverwrite(read_messages=False),
                user: PermissionOverwrite(read_messages=True)
            }
            channel = await vc_after.channel.category.create_text_channel(
                name=vc_txt_after, overwrites=overwrites)
        else:
            await channel.set_permissions(user, read_messages=True)
Пример #20
0
    async def _create_text_channel(self):
        """
                        Creates the user-related text-channel
        """

        channels = handler.load_json(JSON_CHANNEL_IDS_FILE)

        author = self.ctx.author

        self.users_using[str(author.id)] = 0

        channel: TextChannel = await self.ctx.guild.create_text_channel(f'{self.manga["name"]}-{author.name}')
        ow = PermissionOverwrite()
        ow.send_messages = False
        ow.read_messages = True
        await channel.set_permissions(author, overwrite=ow)

        default_role = utils.get(self.ctx.guild.roles, name='@everyone')

        ow.read_messages = False
        await channel.set_permissions(default_role, overwrite=ow)

        channels[str(self.ctx.guild.id)][str(author.id)] = str(channel.id)

        handler.dump_json(JSON_CHANNEL_IDS_FILE, channels)

        return channel
Пример #21
0
    async def groups_create(self, ctx: Context, name: str, *,
                            description: str):
        """Create a group for you and your friends!
        Name must NOT include spaces and is CaSe SeNsItIvE!
        """
        if len(name) > 48:
            await ctx.send(
                ":anger: Please use a name shorter than 48 characters.")
            return

        sid = str(ctx.guild.id)

        if sid not in self.db:
            self.db[sid] = {}

        # Try to make a role, text, and voice channel for the group
        try:
            role = await ctx.guild.create_role(name=name,
                                               reason="Groups plugin")
            ow = {
                ctx.guild.default_role:
                PermissionOverwrite(read_messages=False),
                role: PermissionOverwrite(read_messages=True),
            }
            category = await ctx.guild.create_category(name=name,
                                                       reason="Groups plugin",
                                                       overwrites=ow)
            text = await ctx.guild.create_text_channel(
                name=name.lower(),
                reason="Groups plugin",
                category=category,
                topic=description,
            )
            voice = await ctx.guild.create_voice_channel(
                name=name, reason="Groups plugin", category=category)

            self.db[sid][name] = {
                "info": {
                    "leader": str(ctx.author.id),
                    "description": description,
                    "category": str(category.id),
                    "text_channel": str(text.id),
                    "voice_channel": str(voice.id),
                    "role": str(role.id),
                }
            }

            update_db(self.sql_db, self.db, "servers")

            await ctx.author.add_roles(role, reason="Group created.")

        except Exception as e:
            await ctx.send(f":anger: Something went wrong: `{e}`")
            return

        await ctx.send(":white_check_mark: Group created!")
        await text.send(
            f"Welcome to your group {ctx.author.mention}! Try the `group invite` command!"
        )
Пример #22
0
    async def on_voice_state_update(self, member, before, after):
        """invoked when a member changes their VoiceState"""
        if member.bot:
            return

        if before.channel and before.channel != after.channel:
            if not before.channel.members:
                if str(before.channel.id) in self.VCs['party_tchannels']:
                    await member.guild.get_channel(
                        self.VCs['party_tchannels'][str(before.channel.id)]
                    ).delete()
                    del self.VCs['party_tchannels'][str(before.channel.id)]
                    self.save()
                if before.channel.id in self.VCs['party_vchannels']:
                    await before.channel.delete()
                    self.VCs['party_vchannels'].remove(before.channel.id)
                    self.save()
            if str(before.channel.id) in self.VCs['party_tchannels']:
                tc = member.guild.get_channel(self.VCs['party_tchannels'][str(
                    before.channel.id)])
                await tc.set_permissions(member, overwrite=None)
        if not after.channel:
            return
        if member.nick:
            member_name = member.nick
        else:
            member_name = member.name
        if str(after.channel.id) in self.VCs['party_tchannels']:
            tc = member.guild.get_channel(self.VCs['party_tchannels'][str(
                after.channel.id)])
            await tc.set_permissions(member, read_messages=True)
            return
        if after.channel.id in self.VCs['text_enabled_channels'] or (
                member.guild.id in self.VCs['allow_text']
                and after.channel.id in self.VCs['party_vchannels']):
            overwrites = {
                member.guild.default_role:
                PermissionOverwrite(read_messages=False,
                                    read_message_history=False),
                member:
                PermissionOverwrite(read_messages=True)
            }
            tc = await member.guild.create_text_channel(
                f'party of {member_name}',
                overwrites=overwrites,
                category=after.channel.category)
            self.VCs['party_tchannels'][str(after.channel.id)] = tc.id
            self.save()
            return
        if after.channel.id not in self.VCs['vc_enabled_channels']:
            return
        vc = await member.guild.create_voice_channel(
            f'{member_name}\'s Party', category=after.channel.category)
        if vc.id not in self.VCs['party_vchannels']:
            self.VCs['party_vchannels'].append(vc.id)
            self.save()
        await member.move_to(vc)
Пример #23
0
 async def create_channel(self, ctx, name, role: Role = None):
     overwrites = {}
     if role:
         overwrites = {
             ctx.guild.default_role: PermissionOverwrite(read_messages=False),
             role: PermissionOverwrite(read_messages=True)
         }
     new_channel = await ctx.guild.create_text_channel(name, overwrites=overwrites)
     await ctx.send(f'Created new channel - {new_channel.name}')
Пример #24
0
 def set(
     self,
     target: Union[discord.Role, discord.Member],
     permission_overwrite: discord.PermissionOverwrite,
 ):
     """Set the permissions for a target."""
     if not permission_overwrite.is_empty():
         self.__overwrites[target] = discord.PermissionOverwrite(
         ).from_pair(*permission_overwrite.pair())
Пример #25
0
    async def member_join(
        self,
        member: Member,
        channel: VoiceChannel,
        group: Optional[DynamicVoiceGroup],
        dyn_channel: Optional[DynamicVoiceChannel],
    ):
        await member.add_roles(*await gather_roles(member.guild, channel.id))

        if dyn_channel is not None:
            if group is not None:
                await member.add_roles(
                    *await gather_roles(member.guild, group.channel_id))

            text_chat: Optional[TextChannel] = self.bot.get_channel(
                dyn_channel.text_chat_id)
            if text_chat is not None:
                if not group.public:
                    await channel.set_permissions(member,
                                                  read_messages=True,
                                                  connect=True)
                await text_chat.set_permissions(member, read_messages=True)
                await self.send_voice_msg(
                    text_chat, group.public, translations.voice_channel,
                    translations.f_dyn_voice_joined(member.mention))
            return

        if group is None:
            return

        if member.bot:
            await member.move_to(None)
            return
        if channel.category is not None and len(
                channel.category.channels) >= 49 or len(
                    channel.guild.channels) >= 499:
            await member.move_to(None)
            return

        guild: Guild = channel.guild
        number = len(await db_thread(
            db.all, DynamicVoiceChannel, group_id=group.id)) + 1
        chan: VoiceChannel = await channel.clone(name=group.name + " " +
                                                 str(number))
        category: Union[CategoryChannel, Guild] = channel.category or guild
        overwrites = {
            guild.default_role:
            PermissionOverwrite(read_messages=False, connect=False),
            guild.me:
            PermissionOverwrite(read_messages=True, connect=True),
        }
        if (team_role :=
                guild.get_role(await Settings.get(int,
                                                  "team_role"))) is not None:
            overwrites[team_role] = PermissionOverwrite(read_messages=True,
                                                        connect=True)
Пример #26
0
    async def on_new_draft(self, drafts):
        """Create channels for drafts and add correct users

        if need to keep track of discord channel id -> draft id use 
        send_update_drafts when know the channel ids. 
        """
        logger.info("FantasyBot: on new draft")
        # for guild in self.guilds: # TODO
        guild = self.get_guild(GUILD_ID)
        if guild is None:
            logger.error(
                f'FantasyBot:on_new_draft: cant find guild with id {GUILD_ID}')
            return
        for draft in drafts:
            logger.info(
                f'FantasyBot:on_new_draft: handling draft {draft["draft_id"]}')
            if draft['league_id'] != FANTASY_LEAGUE_ID:
                logger.error(
                    f'FantasyBot:on_new_draft: unexpected league id {draft["league_id"]}'
                )
                return
            overwrites = {
                guild.default_role: PermissionOverwrite(read_messages=False)
            }
            for team_draft in draft["team_drafts"]:
                member = guild.get_member(team_draft["meta"]["discord_id"])
                if member is None:
                    logger.error(
                        f'FantasyBot:on_new_draft: failed to find member')
                    # return
                    continue
                overwrites[member] = PermissionOverwrite(read_messages=True)
            category = dget(guild.categories, name=CATEGORY_NAME)
            if category is None:
                logger.error(
                    "FantasyBot:on_new_draft: failed to find catgeory")
                return
            logger.info(
                f'FantasyBot:on_new_draft: creating new channel for draft {draft["draft_id"]}'
            )
            # TODO CT should go into the fantasydota category (or a drafts subcategory)
            new_channel = await guild.create_text_channel(
                f'draft {draft["draft_id"]}',
                overwrites=overwrites,
                category=category)
            self.fantasy_handler.draft_ids_to_channel_ids[
                draft["draft_id"]] = new_channel.id
            self.fantasy_handler.channel_ids_to_draft_ids[
                new_channel.id] = draft["draft_id"]
            await self.fantasy_handler.client.send_update_drafts([
                DraftUpdate(draft["draft_id"],
                            meta={'channel_id': new_channel.id})
            ])
            await new_channel.send(f'Welcome drafters!')
            await new_channel.send(
                self.fantasy_handler.future_draft_choices(draft["draft_id"]))
Пример #27
0
    async def webhook_project_repository(self, message: Message) -> None:
        """Generate a channel and webhook for a repository."""
        assert message.content.startswith("webhook!")

        url = message.content[len("webhook!"):]

        async with self.session.get(url) as resp:
            if not resp.status in range(200, 300):
                await message.channel.send(
                    f"{message.author.mention} - I couldn't verify that link, I got a HTTP/{resp.status} back.",
                    delete_after=3.0)
                await sleep(2)
                await message.delete()
                return

        kwargs = {"topic": url, "reason": f"Invoked by {message.author!s}"}

        match = await self.client.loop.run_in_executor(
            None, partial(search, r"([^/][\w-]+)(?:/)([^/].+)$", url))

        if match is not None:
            name = "-".join(match.groups())
        else:
            self.logger.error("Failed to match against %s", repr(url))
            name = url

        if len(name) > 80:
            name = name[:80]

        assert len(name) <= 80

        kwargs["name"] = name

        category = self.client.get_channel(self._category_id)
        assert category is not None

        member_role = message.guild.get_role(self._member_role_id)
        assert member_role is not None

        kwargs["overwrites"] = {
            **category.overwrites,
            member_role:
            PermissionOverwrite(read_messages=False,
                                read_message_history=False),
            message.author:
            PermissionOverwrite(read_messages=True,
                                read_message_history=True,
                                send_messages=True),
        }

        channel = await category.create_text_channel(**kwargs)
        webhook = await channel.create_webhook(name=name)

        await channel.send(
            ALLOCATED_MESSAGE.format(message=message, webhook=webhook))
        self.client.schedule_task(self._activate_webhook_channel(channel))
 async def getUserChannelCategory(guild):
     category = utils.get(guild.categories, name="Benutzerkanäle")
     if not category:
         categoryoverwrites = { guild.default_role: PermissionOverwrite(read_messages=False, send_messages=False, connect=False, speak=False, move_members=False, use_voice_activation=True) }
         textchanneloverwrites = { guild.default_role: PermissionOverwrite(read_messages=True, send_messages=True) }
         voicechanneloverwrites = { guild.default_role: PermissionOverwrite(read_messages=True, connect=True, speak=False, move_members=False) }
         category = await guild.create_category_channel(name="Benutzerkanäle", overwrites=categoryoverwrites, reason="Bereite Benutzerkanäle vor...")
         await category.create_text_channel(name="benutzerkanäle", overwrites=textchanneloverwrites, reason="Bereite Benutzerkanäle vor...", topic="Befehle: /textchannelcreate - /textchanneldelete")
         await category.create_voice_channel(name="Sprachkanal erstellen", overwrites=voicechanneloverwrites, reason="Bereite Benutzerkanäle vor...")
     return category
Пример #29
0
    async def groups_create(self, ctx: Context, name: str, *,
                            description: str):
        """Create a group for you and your friends!
        Name must NOT include spaces!
        """
        sid = str(ctx.guild.id)

        if sid not in db:
            db[sid] = {}

        # Try to make a role, text, and voice channel for the group
        try:
            role = await ctx.guild.create_role(name=name, reason=GP)
            # Set overwrites for the category
            ow = {
                ctx.guild.default_role:
                PermissionOverwrite(read_messages=False),
                role: PermissionOverwrite(read_messages=True)
            }
            category = await ctx.guild.create_category(name=name,
                                                       reason=GP,
                                                       overwrites=ow)
            text = await ctx.guild.create_text_channel(name=name.lower(),
                                                       reason=GP,
                                                       category=category,
                                                       topic=description)
            voice = await ctx.guild.create_voice_channel(name=name,
                                                         reason=GP,
                                                         category=category)

            db[sid] = {
                name: {
                    "info": {
                        "description": description,
                        "category": str(category.id),
                        "text_channel": str(text.id),
                        "voice_channel": str(voice.id),
                        "role": str(role.id)
                    }
                }
            }
            update_db(sql_db, db, "servers")

            await ctx.author.add_roles(role, reason="Group created.")

        except Exception as e:
            await ctx.send(f":anger: Something went wrong: `{e}`")
            return

        await ctx.send(":white_check_mark: Group created!")
        await text.send(
            f"Welcome to your group {ctx.author.mention}! Try the `group invite` command!"
        )
Пример #30
0
 async def get_default_vc(self):
     try:
         self.selected_channel = self.channel.guild.voice_channels[0]
     except IndexError:
         self.selected_channel = await self.channel.guild.create_voice_channel(
             "Flute Music",
             overwrites={
                 self.channel.guild.default_role:
                 PermissionOverwrite(speak=False),
                 self.channel.guild.me:
                 PermissionOverwrite(speak=True),
             })