我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用discord.ClientException()。
def join(self, *, channel: discord.Channel): """Joins a voice channel.""" try: await self.bot.create_voice_client(channel) except discord.InvalidArgument: out = await self.bot.say('This is not a voice channel...') await asyncio.sleep(5) try: await self.bot.delete_messages([ctx.message, out]) except: pass except discord.ClientException: out = await self.bot.say('Already in a voice channel...') await asyncio.sleep(5) try: await self.bot.delete_messages([ctx.message, out]) except: pass else: out = await self.bot.say('Ready to play audio in ' + channel.name) await asyncio.sleep(5) try: await self.bot.delete_messages([ctx.message, out]) except: pass
def load_cogs(self, cogs: List): for cog, kwargs in cogs: try: # This is taken from self.load_extensions but allows kwargs to be passed if cog in self.extensions: return lib = importlib.import_module("src." + cog) if not hasattr(lib, 'setup'): del lib del sys.modules[cog] raise discord.ClientException("extension does not have a setup function") lib.setup(self, kwargs) self.extensions[cog] = lib except Exception as e: print('Failed to load extension {}\n{}: {}'.format(cog, type(e).__name__, e))
def run(self): # We load plugins in run rather than on_ready due to on_ready being able to be called multiple times for plugin in plugins: # We try to load the extension, and we account for if it fails try: self.load_extension(plugin) self.logger.info("{0} has been loaded".format(plugin)) # Except discord.ClientException so it doesn't fail to load all cogs when a cog doesn't have a setup function except discord.ClientException: self.logger.critical("{0} does not have a setup function!".format(plugin)) # Except import error (importlib raises this) so bot doesn't crash when it's raised except ImportError as IE: self.logger.critical(IE) # We check if discord.opus is loaded, despite it not having a reason to be if not discord.opus.is_loaded(): # Load discord.opus so we can use voice discord.opus.load_opus() self.logger.info("Opus has been loaded") super().run(setup_file["discord"]["token"])
def join(self, ctx, *, channel : discord.Channel): """Joins a voice channel.""" try: await self.create_voice_client(channel) except discord.ClientException: await self.bot.say('Already in a voice channel...') except discord.InvalidArgument: await self.bot.say('This is not a voice channel...') else: await self.bot.say('Ready to play audio in ' + channel.name)
def join(self, ctx, *, channel: discord.Channel): """Joins a voice channel.""" try: await self.create_voice_client(channel) except discord.ClientException: await self.bot.say('Already in a voice channel...') except discord.InvalidArgument: await self.bot.say('This is not a voice channel...') else: await self.bot.say('Ready to play audio in ' + channel.name)
def joinVC(self, toJoin, channel=None): ''' Joins a given voice channel. Will join the VC of a member if a member is passed. ''' if channel == None: channel = self.lastChannel # Join a channel if specified if type(toJoin) == Channel: loadedVC = self.sparcli.join_voice_channel(toJoin) self.voiceClient = loadedVC return loadedVC # No channel specified, join the user's VC memberVC = toJoin.voice.voice_channel if memberVC == None: await self.sparcli.send_message(channel, 'You aren\'t currently in a voice channel.') return False # Join the member's VC try: # Try to join loadedVC = await self.sparcli.join_voice_channel(memberVC) self.voiceClient = loadedVC return loadedVC except ClientException: # You're already in it loadedVC = self.sparcli.voice_client_in(toJoin.server) self.voiceClient = loadedVC return loadedVC else: # You can't join it await self.sparcli.send_message(channel, 'I am unable to join that voice channel.') return False
def join_voice(self, ctx, *, channel: discord.Channel): """Joins a voice channel.""" try: await self.create_voice_client(channel) except discord.ClientException: await self.bot.say('Already in a voice channel...') except discord.InvalidArgument: await self.bot.say('This is not a voice channel...') else: await self.bot.say('Ready to play audio in ' + channel.name)
def join(self, ctx, *, channel : discord.Channel): """Rejoindre un channel vocal""" try: await self.create_voice_client(channel) except discord.ClientException: await self.bot.say('Already in a voice channel...') except discord.InvalidArgument: await self.bot.say('This is not a voice channel...') else: await self.bot.say('Ready to play audio in ' + channel.name)
def send_to_channels(ev, embed, marker, triggers=None): channels = await get_channels(ev, marker) for channel in channels: try: if triggers: mentions = await get_triggers(ev.db, triggers, channel.guild) if mentions: mentions = ' '.join(mentions) await channel.send(mentions, embed=embed) else: await channel.send(embed=embed) else: await channel.send(embed=embed) except discord.ClientException: pass
def afk_comeback_check(ev, message): if message.guild: pfx = await ev.bot.get_prefix(message) if not message.content.startswith(pfx): if not sigma_mention_check(message.content, ev.bot.user.id): afk_data = await ev.db[ev.db.db_cfg.database]['AwayUsers'].find_one({'UserID': message.author.id}) if afk_data: await ev.db[ev.db.db_cfg.database]['AwayUsers'].delete_one({'UserID': message.author.id}) response = discord.Embed(color=0x3B88C3, title='? I have removed your AFK status.') removal = await message.channel.send(embed=response) await asyncio.sleep(5) try: await removal.delete() except discord.ClientException: pass
def clockwork_function_reminder_clockwork(ev): while True: reminders = await ev.db[ev.db.db_cfg.database]['Reminders'].find({}).to_list(None) for reminder in reminders: current_stamp = arrow.utcnow().timestamp execution_stamp = reminder['ExecutionStamp'] if current_stamp > execution_stamp: await ev.db[ev.db.db_cfg.database]['Reminders'].delete_one({'ReminderID': reminder['ReminderID']}) channel = discord.utils.find(lambda x: x.id == reminder['ChannelID'], ev.bot.get_all_channels()) author = discord.utils.find(lambda x: x.id == reminder['UserID'], ev.bot.get_all_members()) if channel: target = channel elif author: target = author else: target = None if target: dt_stamp = arrow.get(reminder['CreationStamp']).datetime title = f'? Your Reminder' response = discord.Embed(color=0xff3333, title=title, timestamp=dt_stamp) response.description = reminder.get('TextMessage') if author: response.set_author(name=author.name, icon_url=user_avatar(author)) response.set_footer(text=f'Reminder: {reminder.get("ReminderID")}') try: if author: await target.send(f'{author.mention}, your reminder executed.', embed=response) else: await target.send(embed=response) except discord.ClientException: pass await asyncio.sleep(1)
def connect(self, data): """ Connect to a channel in the specific server, or move if already in vc :param: false or default channel id :param data: message data to get author out of :return: True if connected, False if something went wrong """ try: m_channel = self.parent.channel_manager.get_channel(self.guild, "voice_music") except ChannelNotFoundError: m_channel = None except AttributeError: self.parent.logger.error("Failed to get channel.") m_channel = None if not m_channel and data.author.voice and data.author.voice.channel: m_channel = data.author.voice.channel elif not m_channel: raise UserPermissionError("Must be in voice chat.") self.vc = data.guild.voice_client if self.vc: await self.vc.move_to(m_channel) return m_channel perms = m_channel.permissions_for(self.guild.me) if perms.connect and perms.speak and perms.use_voice_activation: try: self.vc = await m_channel.connect() if self.queue: await self.skip_song(data) return m_channel except(InvalidArgument, ClientException): self.parent.logger.exception("Error connecting to voice chat. ", exc_info=True) return False else: return False
def join(self, ctx): """Summons the bot to your voice channel.""" msg = await ctx.send('\N{RUNNER} Connecting to voice...') state = self.state_for(ctx.guild) # already connected? if state.connected: return await msg.edit(content='I\'m already playing music in `{}`.'.format(state.channel)) # can't join if we aren't in a voice channel. if ctx.author.voice is None: return await msg.edit(content='I can\'t join you if you aren\'t in a voice channel.') # the channel that the command invoker is in ch = ctx.author.voice.channel # check if we can join that channel. if not ctx.guild.me.permissions_in(ch).connect: return await msg.edit(content='\N{LOCK} I can\'t connect to that channel.') try: log.debug('Connecting to %s.', ch) await ch.connect() except TimeoutError: await msg.edit(content='\N{ALARM CLOCK} Couldn\'t connect, I took too long to reach Discord\'s servers.') log.warning('Timed out while connecting to Discord\'s voice servers.') except ClientException: await msg.edit(content='\N{CONFUSED FACE} I\'m already connected.') log.warning('I couldn\'t detect being connected.') else: await msg.edit(content='\N{OK HAND SIGN} Connected!')
def join(self, ctx, *, channel : discord.Channel): """Joins a voice channel.""" if str(ctx.message.author.voice_channel) is not null or str(ctx.message.author.voice_channel.id) != self.bot.music_channel: await self.embed_for_me('I can only play in Music voicechannel. This is '+str(ctx.message.author.voice_channel),ctx) return False try: await self.create_voice_client(channel) except discord.ClientException: await self.embed_for_me('Already in a voice channel...',ctx) except discord.InvalidArgument: await self.embed_for_me('This is not a voice channel...',ctx) else: await self.embed_for_me('Ready to play audio in '+channel.name,ctx)
def add_cog(self, cog): if not isinstance(cog, Cog): raise discord.ClientException(f'cog must be an instance of {Cog.__qualname__}') # cog aliases for alias in cog.__aliases__: if alias in self.cog_aliases: raise discord.ClientException(f'"{alias}" already has a cog registered') self.cog_aliases[alias.lower()] = cog super().add_cog(cog) cog_name = cog.__class__.__name__ self.cog_aliases[cog.__class__.name.lower()] = self.cogs[cog_name.lower()] = self.cogs.pop(cog_name)
def join(self, ctx, *, channel: discord.Channel): """Joins a voice channel.""" try: await self.create_voice_client(channel) except discord.InvalidArgument: await self.bot.say("This is not a voice channel...") except discord.ClientException: await self.bot.say("Already in a voice channel...") else: await self.bot.say("Ready to play audio in " + channel.name)
def create_voice_client(self, channel): """Creates a voice client and saves it""" # First join the channel and get the VoiceClient that we'll use to save per server await self.remove_voice_client(channel.server) server = channel.server state = self.get_voice_state(server) voice = self.bot.voice_client_in(server) # Attempt 3 times for i in range(3): try: if voice is None: state.voice = await self.bot.join_voice_channel(channel) if state.voice: return True elif voice.channel == channel: state.voice = voice return True else: # This shouldn't theoretically ever happen yet it does. Thanks Discord await voice.disconnect() state.voice = await self.bot.join_voice_channel(channel) if state.voice: return True except (discord.ClientException, socket.gaierror, ConnectionResetError): continue return False
def load_cog(cog): try: bot.load_extension(cog) print('Loaded {0}'.format(cog)) except (ImportError, discord.ClientException) as e: print('Failed to load cog {0}\n{1}: {2}'.format( cog, type(e).__name__, e))
def join(self, ctx, *, channel : discord.Channel): try: await self.create_client(channel) except discord.ClientException: await self.bot.say("\N{CROSS MARK} already in a voice channel") except discord.InvalidArgument: await self.bot.say("\N{CROSS MARK} no a valid voice channel") else: await self.bot.say("Joined **{}** in **{}**".format(channel.name, channel.server.name))
def load_extension(self, extension_name): for shard in self.shards.values(): if extension_name in shard.extensions: continue else: ext_lib = import_module(extension_name) if not hasattr(ext_lib, "setup"): del ext_lib del sys.modules[extension_name] raise discord.ClientException("extension does not have a setup function") ext_lib.setup(shard) shard.extensions[extension_name] = ext_lib self.extensions[extension_name] = ext_lib
def add_cog(self, cog): lower_name = type(cog).__name__.lower() if lower_name in self.lower_cogs: raise ClientException( "The cog {} is already registered.".format(lower_name)) self.lower_cogs[lower_name] = cog super().add_cog(cog)
def afk_comeback_check(ev, message): if message.guild: if not message.content.startswith(ev.bot.get_prefix(message)): afk_data = ev.db[ev.db.db_cfg.database]['AwayUsers'].find_one({'UserID': message.author.id}) if afk_data: ev.db[ev.db.db_cfg.database]['AwayUsers'].delete_one({'UserID': message.author.id}) response = discord.Embed(color=0x3B88C3, title='? I have removed your AFK status.') removal = await message.channel.send(embed=response) await asyncio.sleep(5) try: await removal.delete() except discord.ClientException: pass
def clockwork_function_reminder_clockwork(ev): while True: reminders = ev.db[ev.db.db_cfg.database]['Reminders'].find({}) for reminder in reminders: current_stamp = arrow.utcnow().timestamp execution_stamp = reminder['ExecutionStamp'] if current_stamp > execution_stamp: ev.db[ev.db.db_cfg.database]['Reminders'].delete_one({'ReminderID': reminder['ReminderID']}) channel = discord.utils.find(lambda x: x.id == reminder['ChannelID'], ev.bot.get_all_channels()) author = discord.utils.find(lambda x: x.id == reminder['UserID'], ev.bot.get_all_members()) if channel: target = channel elif author: target = author else: target = None if target: response = discord.Embed(color=0x1ABC9C, timestamp=arrow.get(reminder['CreationStamp']).datetime) if author: response.set_author(name=author.name, icon_url=user_avatar(author)) response.add_field(name='? Reminder Message', value=f"```\n{reminder['TextMessage']}\n```") try: if author: await target.send(author.mention, embed=response) else: await target.send(embed=response) except discord.ClientException: pass await asyncio.sleep(1)
def join_vc_and_play_stream(self, ctx, *, channel: discord.Channel = None): """Has the bot join a voice channel and also starts the stream from listen.moe""" try: # Because the bot needs a channel to join, if it's None we'll just return the function assuming they're not in a voice channel if channel is None: # Set it to the voice channel for the member who triggers the command channel = ctx.message.author.voice.voice_channel # Check if again None (If the command user isn't in a voice channel) if channel is None: # Tell the user they actually need to tell us what channel they want Pixie to join await self.bot.say("```xl\nSorry, I'm not too sure what channel you want me to join unless you tell me!```") # Exit out of the function so we don't try joining None return # Get the VoiceClient object voice_client = await self.bot.join_voice_channel(channel) # Set it to stereo and set sample rate to 48000 voice_client.encoder_options(sample_rate=48000, channels=2) # Set the user agent and create the player player = voice_client.create_ffmpeg_player("http://listen.moe:9999/stream", headers={"User-Agent": user_agent}) # Set default player volume player.volume = self.default_vol / 100 # Start the player player.start() # Be a tsun while telling the user that you joined the channel await self.bot.say("```xl\nI-I didn't join {0.channel} because you told me to... you b-b-baka! *hmph*```".format(voice_client)) # Add to the dict of server ids linked to objects self.players.update({ctx.message.server.id: player}) # Here we account for our bot not having enough perms or for the bot region being a bit dodgy except asyncio.TimeoutError: await self.bot.say("```xl\nSorry, I timed out trying to join!```") # This here pms the owner of the bot by the owner id in the setup file telling them if Opus isn't loaded except OpusNotLoaded: # Get the member object (here we assume the owner is in a server that the bot can see) member = discord.utils.get(self.bot.get_all_members(), id=setup_file["discord"]["owner_id"]) # Send a message to tell the owner that the Opus isn't loaded await self.bot.send_message(member, "```xl\nOpus library not loaded.```") # Account for if the bot is in a channel on the server already except discord.ClientException: await self.bot.say("```xl\nSorry, I'm already in a voice channel on this server!```")
def vsetup(self, author): """Creates the voice client Args: author (discord.Member): The user that the voice ui will seek """ if self.vready: logger.warning("Attempt to init voice when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debug("Setting up voice") # Create voice client self.vchannel = author.voice.voice_channel if self.vchannel: self.statuslog.info("Connecting to voice") try: self.vclient = await client.join_voice_channel(self.vchannel) except discord.ClientException as e: logger.exception(e) self.statuslog.warning("I'm already connected to a voice channel.") return except discord.opus.OpusNotLoaded as e: logger.exception(e) logger.error("Could not load Opus. This is an error with your FFmpeg setup.") self.statuslog.error("Could not load Opus.") return except discord.DiscordException as e: logger.exception(e) self.statuslog.error("I couldn't connect to the voice channel. Check my permissions.") return except Exception as e: self.statuslog.error("Internal error connecting to voice, disconnecting.") logger.error("Error connecting to voice {}".format(e)) return else: self.statuslog.error("You're not connected to a voice channel.") return self.vready = True
def joinchannel(self, message): if message.author.voice.voice_channel is None: await self.bot.say("Sorry, I couldn't do that. You're not in a voice channel.") await self.bot.say("I can join a voice channel in this server if you append the `joinchannel` command with" "a voice channel ID.") else: try: self.bot.join_voice_channel(message.author.voice.voice_channel) except discord.InvalidArgument: # await self.bot.say("Sorry, looks like that ID isn't a voice channel ID.") return except asyncio.TimeoutError: await self.bot.say("Couldn't connect to the voice channel in time.") return except discord.ClientException: await self.bot.say("Sorry, it looks like I'm already connected to a voice channel.") return finally: await self.bot.say("Joined the voice channel! Hello, **" + discord.VoiceClient.channel.name + "**!") if not discord.opus.is_loaded(): discord.opus.load_opus() import config if config.DEBUG: if discord.opus.is_loaded(): await self.bot.say("Opus loaded") else: return else: return """ # This is commented out because I don't know if it'll work. elif id: await self.bot.say("Please wait, I'm trying to find that channel...") try: self.bot.join_voice_channel(id) except discord.InvalidArgument: await self.bot.say("Sorry, looks like that ID isn't a voice channel ID.") except asyncio.TimeoutError: await self.bot.say("Couldn't connect to the voice channel in time.") except discord.ClientException: await self.bot.say("Sorry, it looks like I'm already connected to a voice channel.") except discord.opus.OpusNotLoaded: await self.bot.say("Whoops, `libopus` isn't loaded.") finally: await self.bot.say("Successfully resolved the ID.") await self.bot.say("Joined the voice channel! Hello, **" + discord.VoiceClient.channel.name + "**!") # Load opus in the background discord.opus.load_opus() """