Python discord.DiscordException() Examples

The following are 11 code examples of discord.DiscordException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: clans.py    From SML-Cogs with MIT License 6 votes vote down vote up
def post_auto_clans(self, message=None):
        self.check_settings()
        for server_id, v in self.settings['auto_clan']['servers'].items():
            if v.get('auto'):
                channel_id = v.get('channel_id')
                channel = self.bot.get_channel(channel_id)
                if channel is not None:
                    message_id = v.get('message_id')
                    msg = None
                    if message_id is not None:
                        try:
                            msg = await self.bot.get_message(channel, message_id)
                        except DiscordException:
                            pass
                    try:
                        message = await self.post_clans(channel, msg=msg)
                    except DiscordException:
                        pass
                    else:
                        v['message_id'] = message.id

        dataIO.save_json(JSON, self.settings) 
Example #2
Source File: clans.py    From SML-Cogs with MIT License 6 votes vote down vote up
def clanwars_stop(self, ctx):
        """Stop auto display"""
        server = ctx.message.server
        channel = ctx.message.channel
        self.disable_clanwars(server, channel)

        await self.bot.say("Auto clan wars update stopped.")

    # async def post_clanwars_task(self):
    #     """Task: post embed to channel."""
    #     try:
    #         while True:
    #             if self == self.bot.get_cog("Clans"):
    #                 try:
    #                     await self.post_clanwars()
    #                 except DiscordException as e:
    #                     pass
    #                 await asyncio.sleep(TASK_INTERVAL)
    #     except asyncio.CancelledError:
    #         pass 
Example #3
Source File: conftest.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        error = error.original

    if isinstance(error, (AvraeException, DiscordException)):
        return
    pytest.fail(f"Command raised an error: {error}")
    raise error 
Example #4
Source File: command.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def respond_with_emote(message, icon):
        """
        Responds to a message with an emote reaction.
        :type message: discord.Message
        :type icon: discord.Emoji or str
        :param message: The message to respond to with an emote.
        :param icon: The emote to react with to the message.
        :return:
        """
        try:
            await message.add_reaction(icon)
        except discord.DiscordException:
            pass 
Example #5
Source File: bot.py    From seasonalbot with MIT License 5 votes vote down vote up
def on_command_error(self, context: commands.Context, exception: DiscordException) -> None:
        """Check command errors for UserInputError and reset the cooldown if thrown."""
        if isinstance(exception, commands.UserInputError):
            context.command.reset_cooldown(context)
        else:
            await super().on_command_error(context, exception) 
Example #6
Source File: tibia.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def time_add(self, ctx: NabCtx, *, _timezone):
        """Adds a new timezone to display.

        You can look by city, country or region.
        Once the timezone is found, you can set the name you want to show on the `time` command.

        Only Server Moderators can use this command."""
        _timezone = _timezone.lower().replace(" ", "_")
        matches = []
        for tz in pytz.all_timezones:
            if _timezone in tz.lower():
                matches.append(tz)
        if not matches:
            return await ctx.send(f"{ctx.tick(False)} No timezones found matching that name.")
        _timezone = await ctx.choose(matches)
        if _timezone is None:
            return
        timezone_time = dt.datetime.now().astimezone(pytz.timezone(_timezone))
        msg = await ctx.send(f"The time in `{_timezone}` is **{timezone_time.strftime('%H:%M')}**.\n"
                             f"What display name do you want to assign? You can `cancel` if you changed your mind.")
        display_name = await ctx.input(timeout=60, clean=True, delete_response=True)
        if display_name is None or display_name.lower() == "cancel":
            return await ctx.send("I guess you changed your mind.")
        try:
            await msg.delete()
        except discord.DiscordException:
            pass

        if len(display_name) > 40:
            return await ctx.send(f"{ctx.tick(False)} The display name can't be longer than 40 characters.")

        try:
            await ctx.pool.execute("INSERT INTO server_timezone(server_id, zone, name) VALUES($1, $2, $3)",
                                   ctx.guild.id, _timezone, display_name.strip())
        except asyncpg.UniqueViolationError:
            return await ctx.error("That timezone already exists.")
        await ctx.send(f"{ctx.tick()} Timezone `{_timezone}` saved successfully as `{display_name.strip()}`.") 
Example #7
Source File: clans.py    From SML-Cogs with MIT License 5 votes vote down vote up
def post_clanwars(self):
        """Post embbed to channel."""
        self.check_settings()
        for server_id, v in self.settings['clan_wars']['servers'].items():
            if v.get('auto'):
                channel_id = v.get('channel_id')
                channel = self.bot.get_channel(channel_id)
                if channel is not None:
                    # post clan wars status
                    try:
                        clans = await self.get_clanwars()
                    except:
                        pass
                    else:
                        em = self.clanwars_embed(clans)
                        message_id = v.get('message_id')
                        message = None
                        if message_id is not None:
                            try:
                                message = await self.bot.get_message(channel, message_id)
                            except DiscordException:
                                pass

                        if message is None:
                            await self.bot.purge_from(channel, limit=10)
                            message = await self.bot.send_message(channel, embed=em)
                            v["message_id"] = message.id
                            dataIO.save_json(JSON, self.settings)
                        else:
                            await self.bot.edit_message(message, embed=em) 
Example #8
Source File: crprofile.py    From SML-Cogs with MIT License 5 votes vote down vote up
def display_profile(self, ctx, tag, **kwargs):
        """Display profile."""
        sctag = SCTag(tag)
        if not sctag.valid:
            await self.bot.say(sctag.invalid_error_msg)
            return

        try:
            player_data = await self.model.player_data(sctag.tag)
        except json.decoder.JSONDecodeError:
            player_data = self.model.cached_player_data(tag)
        except asyncio.TimeoutError:
            player_data = self.model.cached_player_data(tag)

        if player_data is None:
            await self.bot.send_message(ctx.message.channel, "Unable to load from API.")
            return
        if player_data.is_cache:
            await self.bot.send_message(
                ctx.message.channel,
                (
                    "Unable to load from API. "
                    "Showing cached data from: {}.".format(
                        self.model.cached_player_data_timestamp(tag))
                )
            )

        server = ctx.message.server
        for em in self.embeds_profile(player_data, server=server, **kwargs):
            try:
                await self.bot.say(embed=em)
            except discord.DiscordException as e:
                await self.bot.say("Discord error: {e}".format(e=e)) 
Example #9
Source File: playlist.py    From Wavelink with MIT License 5 votes vote down vote up
def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
        """Connect to a valid voice channel."""
        if not channel:
            try:
                channel = ctx.author.voice.channel
            except AttributeError:
                raise discord.DiscordException('No channel to join. Please either specify a valid channel or join one.')

        player = self.bot.wavelink.get_player(ctx.guild.id)
        await ctx.send(f'Connecting to **`{channel.name}`**', delete_after=15)
        await player.connect(channel.id)

        controller = self.get_controller(ctx)
        controller.channel = ctx.channel 
Example #10
Source File: basic.py    From Wavelink with MIT License 5 votes vote down vote up
def connect_(self, ctx, *, channel: discord.VoiceChannel = None):
        if not channel:
            try:
                channel = ctx.author.voice.channel
            except AttributeError:
                raise discord.DiscordException('No channel to join. Please either specify a valid channel or join one.')

        player = self.bot.wavelink.get_player(ctx.guild.id)
        await ctx.send(f'Connecting to **`{channel.name}`**')
        await player.connect(channel.id) 
Example #11
Source File: racf_decks.py    From SML-Cogs with MIT License 4 votes vote down vote up
def update_decks(self):
        try:
            if self == self.bot.get_cog("RACFDecks"):
                while True:
                    debug("RACF DECKS: update decks")

                    server = None
                    server_id = self.settings.get("server_id")

                    debug("RACF DECKS: update decks server_id:", server_id)

                    if server_id:
                        server = self.bot.get_server(server_id)

                    debug("RACF DECKS: update decks server:", server)
                    if server:
                        try:
                            tasks = []
                            family_auto = self.settings.get('family_auto')
                            family_channel_id = self.settings.get('family_channel_id')
                            if family_auto and family_channel_id:
                                channel = discord.utils.get(server.channels, id=family_channel_id)
                                if channel:
                                    # self.loop.create_task(
                                    #     self.post_decks(channel, fam=True, show_empty=False)
                                    # )
                                    # await self.post_decks(channel, fam=True, show_empty=False)
                                    tasks.append(
                                        self.post_decks(channel, fam=True, show_empty=False)
                                    )

                            gc_auto = self.settings.get('gc_auto')
                            gc_channel_id = self.settings.get('gc_channel_id')
                            if gc_auto and gc_channel_id:
                                channel = discord.utils.get(server.channels, id=gc_channel_id)
                                if channel:
                                    # self.loop.create_task(
                                    #     self.post_decks(channel, fam=False, show_empty=False)
                                    # )
                                    # await self.post_decks(channel, fam=False, show_empty=False)
                                    tasks.append(
                                        self.post_decks(channel, fam=False, show_empty=False)
                                    )

                        except discord.DiscordException as e:
                            print(e)
                        else:
                            debug("RACF DECKS: Task Length: {}".format(len(tasks)))
                            await asyncio.gather(*tasks, return_exceptions=True)
                            debug("RACF DECKS: Gather done")


                    # await asyncio.sleep(3)
                    debug("RACF DECKS: sleep: ", DELAY)
                    await asyncio.sleep(DELAY)
        except asyncio.CancelledError:
            pass