我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用discord.InvalidArgument()。
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 _update_avatar(self, msg): if "bot_maintainers" not in self.config_manager.config: raise UserPermissionError("No bot maintainers are set!") elif msg.author.id not in self.config_manager.config.bot_maintainers: raise UserPermissionError url = " ".join(msg.content.split()[1:]) if url: try: img = urllib.request.urlopen(url).read() await self.client.user.edit(avatar=img) await respond(msg, "**AVATAR UPDATED.**") except (urllib.request.URLError, ValueError): await respond(msg, "**WARNING: Invalid URL provided.**") except InvalidArgument: await respond(msg, "**NEGATIVE. Image must be a PNG or JPG.**") else: raise CommandSyntaxError("No URL provided.")
def set_avatar(self, avatar_link : str): """Sets bot's avatar Parameters: avatar_link: The link of the the picture which will become the new bot's avatar Example: [p]set_avatar http://i.imgur.com/bjmbH1e.png""" r = requests.get(avatar_link) if r.status_code == 200: try: await self.bot.edit_profile(avatar=r.content) await self.bot.say("Done!") except discord.HTTPException: await self.bot.say("HTTP Exception") except discord.InvalidArgument: await self.bot.say("Wrong image format") except requests.exceptions.MissingSchema: await self.bot.say("Invalid URL") else: await self.bot.say("Error " + str(r.status_code) + ": The link must be incorrect, " \ + "make sure the link finishes with `.png`, `.jpg`, `.jpeg`, etc")
def set_game(self, *game): """Sets bot's game Parameters: *game: The game you want to set for the bot Leaving this blank will remove bot's game Example: [p]set_game with fire!""" try: if game: await self.bot.change_presence(game=discord.Game(\ name=" ".join(game), type=0)) else: await self.bot.change_presence(game=None) await self.bot.say("Done! :ok_hand:") except discord.InvalidArgument: await self.bot.say("Wrong game name format (too long?)")
def set_stream(self, stream_link: str = "", *game): """Sets bot's stream name Parameters: stream_link: the link to the stream you want to set for the bot *game: The game you want to set for the bot's stream Leaving this blank will remove bot's stream status Example: [p]set_stream https://www.twitch.tv/beafantles coding myself!""" try: if stream_link != "": if stream_link.startswith("https://www.twitch.tv/"): await self.bot.change_presence(game=discord.Game(\ name=" ".join(game), type=1, url = stream_link)) await self.bot.say("Done! :ok_hand:") else: await self.bot.say("Please provide a correct stream link") else: await self.bot.change_presence(game=None) await self.bot.say("Done! :ok_hand:") except discord.InvalidArgument: await self.bot.say("Wrong game name format (too long?)")
def send_log(self, server: discord.Server, log: Log): """Sends a embed corresponding to the log in the log channel of the server""" if server.id in self.servers_config["servers"]: if "log channel" in self.servers_config["servers"][server.id]: embed = log.get_embed(self.bot) channel = self.servers_config["servers"][server.id]["log channel"] try: await self.bot.send_message(destination=channel, embed=embed) except discord.Forbidden: await self.bot.send_message(destination=server.owner, content=\ "I'm not allowed to send embeds in the log channel (#" + \ channel.name + "). Please change my permissions.") except discord.NotFound: await self.bot.send_message(destination=server.owner, content=\ "I'm not allowed to send embeds in the log channel because " + \ "it doesn't exists anymore. Please set another log channel " + \ "using the `[p]set_log_channel` command.") except discord.HTTPException: pass except discord.InvalidArgument: pass
def say_victory_message(self, msg_winner, msg_no_winner): serverlist = list(self.bot.servers) for s in serverlist: if self.get_victory_messages(s): try: msg = msg_winner if self.get_show_result(s) else msg_no_winner matches_channel = self.bot.get_channel(self.get_matches_channel(s)) if matches_channel: try: await self.bot.send_message(matches_channel, msg) except (discord.Forbidden, discord.NotFound, discord.InvalidArgument): pass except discord.HTTPException: pass #except Exception as e: # print("Unable to announce end of match: %s" % e)
def contact(self, ctx, *, message): """Sends a message to the bot owner (60s cooldown). Is not affected by Octarine Core, Refresher Orb, Rearm, or cooldown reduction talents.""" try: owner = await self.bot.get_owner() except discord.NotFound: await self.bot.say("Alas, I know not who my owner is.") return author = ctx.message.author emb = discord.Embed(description = message) emb.set_author(name = "Message from %s" % author) try: await self.bot.send_message(owner, embed = emb) except discord.InvalidArgument: await self.bot.say("Alas, I know not where my owner is.") except discord.HTTPException: await self.bot.say("Alas, I could not deliver your message. Perhaps it is too long?") except: await self.bot.say("Alas, for reasons yet unknown to me, I could not deliver your message.") else: await self.bot.say("I have delivered your message with utmost haste! I pray it should arrive safely.")
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 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 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, *, 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 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 join(self, *, channel: discord.Channel): """Joins a voice channel.""" try: await self.create_voice_client(channel) # Check if the channel given was an actual voice channel except discord.InvalidArgument: await self.bot.say('This is not a voice channel...') except (asyncio.TimeoutError, discord.ConnectionClosed): await self.bot.say("I failed to connect! This usually happens if I don't have permission to join the" " channel, but can sometimes be caused by your server region being far away." " Otherwise this is an issue on Discord's end, causing the connect to timeout!") await self.remove_voice_client(channel.server) else: await self.bot.say('Ready to play audio in ' + channel.name)
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 set_name(self, *name): """Sets bot's name Parameters: *name: The name you want to set for the bot Example: [p]set_name Beaftek's bot""" try: await self.bot.edit_profile(username=" ".join(name)) await self.bot.say("Done!") except discord.HTTPException: await self.bot.say("HTTP Exception") except discord.InvalidArgument: await self.bot.say("Wrong name format (too long?)")
def say_match_start(self, msg): serverlist = list(self.bot.servers) for s in serverlist: try: # Catching potential HTTPExceptions here is actually important, because if we don't then the background task will stop matches_channel = self.bot.get_channel(self.get_matches_channel(s)) if matches_channel: try: await self.bot.send_message(matches_channel, msg) except (discord.Forbidden, discord.NotFound, discord.InvalidArgument): pass except discord.HTTPException: pass #except Exception as e: # print("Unable to announce draft: %s" % e)
def say_welcome_channel(self, server, msg): welcome_channel = self.bot.server_settings_list[server.id]["welcome_channel"] if welcome_channel: try: await self.bot.send_message(self.bot.get_channel(welcome_channel), msg) except (discord.Forbidden, discord.NotFound, discord.InvalidArgument): await self.bot.send_message(server.default_channel, WELCOME_CHANNEL_NOT_FOUND) else: await self.bot.send_message(server.default_channel, msg) # As auto_change_nick is now off by default, there is no need for an on_server_join() method
def avatar(self, ctx, *, user: str=None): """Display a user's avatar. * user - A text string that the bot will attempt to use to look up a user. You may also specify a size for the. The size must be a power of 2 from 16 to 1024. User searches are done with substring matching, so if you're looking for a user called boingtheboingboing, you can simply run for example <prefix> avatar boing, where <prefix> is the bot's prefix. You may also mention the user or supply a user ID. Detailed behavior of this command is as follows (assuming you are the one issuing the command). * If no arguments are given, the avatar displayed is yours. E.g: kit avatar * If one argument is given and it's a valid size, the avatar displayed is yours, at that size. E.g: <prefix> avatar 512 * If one argument is given and it's not a valid size, the bot will try to find a user whose ID or username matches it. E.g: <prefix> avatar b1nzy * If multiple arguments are given, and the final one is a valid size, the bot will try to find a user whose ID or username matches the rest of the arguments, and it will deliver it at the size specified. E.g: <prefix> avatar b1nzy the discord dev 512 * If multiple arguments are given, and the final one is not a valid size, the bot will try to find a user whose ID or username matches all of the arguments. If it fails, it will omit the last argument and try searching with the rest of the arguments. If this too fails, the command will fail completely. E.g: <prefix> avatar b1nzy the discord dev * If no valid size is provided and the avatar found is a .gif image, then the URL will have the size parameter removed entirely so that the avatar animates in chat. Otherwise, it defaults to size 1024. """ manual_size = None if not user: user = ctx.author elif user.isdecimal() and int(user) in VALID_SIZES: manual_size = int(user) user = ctx.author elif user.isdecimal(): user = await helpers.member_by_substring(ctx, user) else: user_minus_last_word, sep, new_size = user.rpartition(" ") if new_size.isdecimal() and int(new_size) in VALID_SIZES: user = await helpers.member_by_substring(ctx, user_minus_last_word) manual_size = int(new_size) else: try: user = await helpers.member_by_substring(ctx, user) except commands.BadArgument: user = await helpers.member_by_substring(ctx, user_minus_last_word) try: if manual_size: url = user.avatar_url_as(size=manual_size) else: url = user.avatar_url if not manual_size and ".gif" in url: url = url.rpartition("?size=")[0] embed = discord.Embed(description=f"Avatar for {user.mention}") embed.set_image(url=url) await ctx.send(embed=embed) except discord.InvalidArgument: await ctx.send(f"Invalid size. Valid sizes: {VALID_SIZES}")
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() """