我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用discord.VoiceChannel()。
def on_guild_channel_create(self, channel): self._log_ignored(f"Channel was created in guild {channel.guild.id}") if not await self._accept_channel(channel): return if isinstance(channel, discord.VoiceChannel): self.logger.info(f"Voice channel {channel.name} deleted in {channel.guild.name}") with self.sql.transaction() as trans: self.sql.add_voice_channel(trans, channel) return self.logger.info(f"Channel #{channel.name} created in {channel.guild.name}") with self.sql.transaction() as trans: self.sql.add_channel(trans, channel) # pylint: disable=not-callable hook = self.hooks['on_guild_channel_create'] if hook: self.logger.debug(f"Found hook {hook!r}, calling it") await hook(channel)
def on_guild_channel_delete(self, channel): self._log_ignored(f"Channel was deleted in guild {channel.guild.id}") if not await self._accept_channel(channel): return if isinstance(channel, discord.VoiceChannel): self.logger.info(f"Voice channel {channel.name} deleted in {channel.guild.name}") with self.sql.transaction() as trans: self.sql.remove_voice_channel(trans, channel) return self.logger.info(f"Channel #{channel.name} deleted in {channel.guild.name}") with self.sql.transaction() as trans: self.sql.remove_channel(trans, channel) # pylint: disable=not-callable hook = self.hooks['on_guild_channel_delete'] if hook: self.logger.debug(f"Found hook {hook!r}, calling it") await hook(channel)
def vchannelinfo(self, ctx, *, channel: discord.VoiceChannel): """Display information about a voice channel. * channel - A specific voice channel to get information about.""" embed = discord.Embed(title=f"{channel.name}") embed.add_field(name="Channel ID", value=channel.id) try: embed.add_field(name="Guild", value=channel.guild.name) except AttributeError: pass embed.add_field(name="Bitrate", value=f"{channel.bitrate}bps") if channel.user_limit > 0: user_limit = channel.user_limit else: user_limit = None embed.add_field(name="User limit", value=user_limit) embed.add_field(name="Created at", value=channel.created_at.ctime()) await ctx.send(embed=embed)
def summon(self, ctx, channel : discord.VoiceChannel = None): """Summons the bot to the voice channel you are currently in You can specify the specific voice channel that you would like to connect to. If no channel is specified, it will connect to whatever channel you are currently in. **Example:** `{cmdpfx}summon General`""" if not channel: if not ctx.message.author.voice: raise UserError("You are not currently in a voice channel") channel = ctx.message.author.voice.channel if channel.guild != ctx.message.guild: raise UserError("You are not currently in a voice channel on this server/guild") audio = self.bot.get_cog("Audio") if not audio: raise UserError("You must have the Audio cog enabled to do this") try: await audio.connect_voice(channel) botdata.guildinfo(channel.guild.id).voicechannel = channel.id except asyncio.TimeoutError: raise UserError("There was a timeout when attempting to do the `?summon`")
def on_guild_channel_update(self, before, after): self._log_ignored(f"Channel was updated in guild {after.guild.id}") if not await self._accept_channel(after): return if before.name != after.name: changed = f' (now {after.name})' else: changed = '' if isinstance(after, discord.TextChannel): self.logger.info(f"Channel #{before.name}{changed} was changed in {after.guild.name}") with self.sql.transaction() as trans: self.sql.update_channel(trans, after) # pylint: disable=not-callable hook = self.hooks['on_guild_channel_update'] if hook: self.logger.debug(f"Found hook {hook!r}, calling it") await hook(before, after) elif isinstance(after, discord.VoiceChannel): self.logger.info("Voice channel {before.name}{changed} was changed in {after.guild.name}") with self.sql.transaction() as trans: self.sql.update_voice_channel(trans, after) elif isinstance(after, discord.CategoryChannel): self.logger.info(f"Channel category {before.name}{changed} was changed in {after.guild.name}") with self.sql.transaction() as trans: self.sql.update_channel_category(trans, after)
def link(self, ctx, text: discord.TextChannel, *, voice: discord.VoiceChannel): """Links an existing text channel to a voice channel.""" with ctx.session: link = ctx.session.get(TextVoiceLink, text_id=text.id, voice_id=voice.id).one_or_none() if link is not None: return await ctx.send('BAKA! Those channels are already linked!') role = await self._create_role(ctx.guild, text, voice, 'Voice link requested by {}'.format(ctx.author)) link = ctx.session.add(TextVoiceLink(role_id=role.id, text_id=text.id, voice_id=voice.id)) await ctx.send(content='Linked {} to "{}"'.format(text.mention, voice.name))
def make(self, ctx, *, voice: discord.VoiceChannel): """Creates a text channel and links it to the given voice channel.""" msg = await ctx.send('Creating text channel for {}'.format(voice.name)) text = await ctx.guild.create_text_channel('voice-' + voice.name.lower().replace(' ', '-'), reason='Voice link requested by {}'.format(ctx.author)) with ctx.session: role = await self._create_role(ctx.guild, text, voice, 'Voice link requested by {}'.format(ctx.author)) link = ctx.session.add(TextVoiceLink(role_id=role.id, text_id=text.id, voice_id=voice.id)) await ctx.send(content='Created {} and linked it to "{}"'.format(text.mention, voice.name))
def unlink(self, ctx, text: discord.TextChannel, *, voice: discord.VoiceChannel): """Unlinks a voice channel and deletes the corresponding role.""" with ctx.session: link = ctx.session.get(TextVoiceLink, text_id=text.id, voice_id=voice.id).one_or_none() if link is None: return await ctx.send('BAKA! Those channels are not linked!') role_id, text_id, voice_id = link.role_id, link.text_id, link.voice_id ctx.session.delete(link) role = discord.utils.get(ctx.guild.roles, id=role_id) if role is None: await ctx.send(content='Unlinked {} from "{}" and deleted the "{}" role.'.format(text.mention, voice.name, role.name)) else: await self._delete_role(ctx.guild, role, text, voice, 'Voice unlink requested by {}'.format(ctx.author)) await ctx.send(content='Unlinked {} from "{}" and deleted the "{}" role.'.format(text.mention, voice.name, role.name))
def count_channels(channels): text = 0 voice = 0 categories = 0 for channel in channels: if isinstance(channel, discord.TextChannel): text += 1 elif isinstance(channel, discord.VoiceChannel): voice += 1 elif isinstance(channel, discord.CategoryChannel): categories += 1 return text, voice, categories
def _set_channel_cmd(self, msg): args = shlex.split(msg.content) if len(args) > 1: chantype = args[1].lower() else: raise CommandSyntaxError("No channel type provided.") if len(args) > 2: if chantype.startswith("voice"): channel = args[2].lower() channel = utils.find(lambda x: isinstance(x, VoiceChannel) and x.name.lower() == channel, msg.guild.channels) if not channel: raise CommandSyntaxError(f"Voice channel {args[2].lower()} not found.") else: if msg.channel_mentions: channel = msg.channel_mentions[0] else: raise CommandSyntaxError("No channel provided.") else: channel = None self.channel_manager.set_channel(msg.guild, chantype, channel) if channel: await respond(msg, f"**ANALYSIS: The {chantype} channel for this server has been set to " f"{channel.mention}.**") else: await respond(msg, f"ANALYSIS: The {chantype} channel for this server has been disabled.")
def __init__(self, ctx): permissions_in = ctx.author.permissions_in _channel_parsers = { discord.TextChannel: functools.partial(_parse_channel, prefix='#', predicate=lambda c: permissions_in(c).read_messages), discord.VoiceChannel: functools.partial(_parse_channel, prefix='', predicate=lambda c: permissions_in(c).connect), } entries = [ (category, [_channel_parsers[c.__class__](c) for c in entries]) for category, channels in ctx.guild.by_category() for entries in sliced(channels, 10) ] super().__init__(ctx, entries, lines_per_page=1)
def info_channel(self, ctx, channel: union(discord.TextChannel, discord.VoiceChannel)=None): """Shows info about a voice or text channel.""" if channel is None: channel = ctx.channel embed_type = 'text_channel_embed' if isinstance(channel, discord.TextChannel) else 'voice_channel_embed' channel_embed = getattr(self, embed_type)(channel) channel_embed.colour = self.bot.colour await ctx.send(embed=channel_embed)
def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
def connect(self, channel): if not isinstance(channel, discord.VoiceChannel): channel = self.bot.get_channel(channel) if self.voice is None: await channel.connect() else: await self.voice.move_to(channel)
def id_(self, ctx, *, argument: Union(Emoji, Role, TextChannel, VoiceChannel, Member, User)): await ctx.send(f"{argument.name}'s ID is {argument.id}")
def _init_sql(self, trans): self.logger.info(f"Processing {len(self.users)} users...") for user in self.users: self.sql.upsert_user(trans, user) self.logger.info(f"Processing {len(self.guilds)} guilds...") for guild in self.guilds: self.sql.upsert_guild(trans, guild) self.logger.info(f"Processing {len(guild.roles)} roles...") for role in guild.roles: self.sql.upsert_role(trans, role) self.logger.info(f"Processing {len(guild.emojis)} emojis...") for emoji in guild.emojis: self.sql.upsert_emoji(trans, emoji) self.logger.info(f"Processing {len(guild.members)} members...") for member in guild.members: self.sql.upsert_member(trans, member) # In case people left while the bot was down self.sql.remove_old_members(trans, guild) text_channels = [] voice_channels = [] categories = [] for channel in guild.channels: if isinstance(channel, discord.TextChannel): text_channels.append(channel) elif isinstance(channel, discord.VoiceChannel): voice_channels.append(channel) elif isinstance(channel, discord.CategoryChannel): categories.append(channel) self.logger.info(f"Processing {len(categories)} channel categories...") for category in categories: self.sql.upsert_channel_category(trans, category) self.logger.info(f"Processing {len(text_channels)} channels...") for channel in text_channels: self.sql.upsert_channel(trans, channel) self.logger.info(f"Processing {len(voice_channels)} voice channels...") for channel in voice_channels: self.sql.upsert_voice_channel(trans, channel)
def stats(self, ctx): """Shows participation info about the bot.""" # TODO: Make this function neater. It's currently trash. # member stats all_members = list(self.bot.get_all_members()) def filter_members_by_status(status): return len([m for m in all_members if m.status == status]) num_members = len(all_members) num_online = filter_members_by_status(discord.Status.online) num_idle = filter_members_by_status(discord.Status.idle) num_dnd = filter_members_by_status(discord.Status.dnd) num_offline = filter_members_by_status(discord.Status.offline) perc_online = f'{round(num_online / num_members * 100, 2)}% is online' # channel stats all_channels = list(self.bot.get_all_channels()) num_channels = len(all_channels) num_voice_channels = len([c for c in all_channels if isinstance(c, discord.VoiceChannel)]) num_text_channels = len([c for c in all_channels if isinstance(c, discord.TextChannel)]) # other stats num_emojis = len(self.bot.emojis) num_emojis_managed = len([e for e in self.bot.emojis if e.managed]) num_servers = len(self.bot.guilds) member_counts = [len(g.members) for g in self.bot.guilds] average_member_count = int(sum(member_counts) / len(member_counts)) uptime = str(datetime.datetime.utcnow() - self.bot.boot_time)[:-7] def cm(v): return utils.commas(v) embed = discord.Embed(title='Statistics') embed.set_footer(text=f'Booted at {utils.standard_datetime(self.bot.boot_time)} UTC') fields = { 'Members': f'{cm(num_members)} total, {cm(num_online)} online\n{cm(num_dnd)} DnD, ' f'{cm(num_idle)} idle\n{cm(num_offline)} offline\n\n{perc_online}', 'Channels': f'{cm(num_channels)} total\n' f'{cm(num_voice_channels)} voice channel(s)\n' f'{cm(num_text_channels)} text channel(s)\n', 'Emoji': f'{cm(num_emojis)} total\n{cm(num_emojis_managed)} managed', 'Servers': f'{cm(num_servers)} total\n{cm(average_member_count)} average members\n' f'{cm(max(member_counts))} max, {cm(min(member_counts))} min', 'Uptime': uptime } for name, value in fields.items(): embed.add_field(name=name, value=value) await ctx.send(embed=embed)
def channelinfo(self, ctx, *, channel: int = None): """Shows channel information""" if not channel: channel = ctx.message.channel else: channel = self.bot.get_channel(channel) data = discord.Embed() if hasattr(channel, 'mention'): data.description = "**Information about Channel:** " + channel.mention if hasattr(channel, 'changed_roles'): if len(channel.changed_roles) > 0: data.color = discord.Colour.green() if channel.changed_roles[0].permissions.read_messages else discord.Colour.red() if isinstance(channel, discord.TextChannel): _type = "Text" elif isinstance(channel, discord.VoiceChannel): _type = "Voice" else: _type = "Unknown" data.add_field(name="Type", value=_type) data.add_field(name="ID", value=channel.id, inline=False) if hasattr(channel, 'position'): data.add_field(name="Position", value=channel.position) if isinstance(channel, discord.VoiceChannel): if channel.user_limit != 0: data.add_field(name="User Number", value="{}/{}".format(len(channel.voice_members), channel.user_limit)) else: data.add_field(name="User Number", value="{}".format(len(channel.voice_members))) userlist = [r.display_name for r in channel.members] if not userlist: userlist = "None" else: userlist = "\n".join(userlist) data.add_field(name="Users", value=userlist) data.add_field(name="Bitrate", value=channel.bitrate) elif isinstance(channel, discord.TextChannel): try: pins = await channel.pins() data.add_field(name="Pins", value=len(pins), inline=True) except discord.Forbidden: pass data.add_field(name="Members", value="%s"%len(channel.members)) if channel.topic: data.add_field(name="Topic", value=channel.topic, inline=False) hidden = [] allowed = [] for role in channel.changed_roles: if role.permissions.read_messages is True: if role.name != "@everyone": allowed.append(role.mention) elif role.permissions.read_messages is False: if role.name != "@everyone": hidden.append(role.mention) if len(allowed) > 0: data.add_field(name='Allowed Roles ({})'.format(len(allowed)), value=', '.join(allowed), inline=False) if len(hidden) > 0: data.add_field(name='Restricted Roles ({})'.format(len(hidden)), value=', '.join(hidden), inline=False) if channel.created_at: data.set_footer(text=("Created on {} ({} days ago)".format(channel.created_at.strftime("%d %b %Y %H:%M"), (ctx.message.created_at - channel.created_at).days))) await ctx.send(embed=data)