Python discord.NotFound() Examples

The following are 30 code examples of discord.NotFound(). 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: purge.py    From bot with MIT License 6 votes vote down vote up
def basic_purge(self, ctx, amount):
        self.bot.recentpurge[ctx.channel.id] = []
        async for message in ctx.channel.history(limit=amount):
            self.bot.recentpurge[ctx.channel.id].append({
                'author': str(message.author),
                'author_id': str(message.author.id),
                'content': message.system_content or '',
                'bot': message.author.bot,
                'embeds': [e.to_dict() for e in message.embeds]
            })
        try:
            await ctx.channel.purge(limit=amount)
        except discord.NotFound:
            return await ctx.error(f'I couldn\'t delete some messages, maybe you set the amount too high?')
        except Exception:
            return await ctx.error(f'Failed to purge')
        finally:
            if not ctx.silent:
                return await ctx.channel.send(
                    f'Successfully deleted **{len(self.bot.recentpurge[ctx.channel.id])}** messages!',
                    delete_after=5
                ) 
Example #2
Source File: reactrestrict.py    From Fox-V3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_message(
        self, ctx: commands.Context, message_id: int
    ) -> Union[discord.Message, None]:
        """
        Tries to find a message by ID in the current guild context.

        :param ctx:
        :param message_id:
        :return:
        """
        for channel in ctx.guild.channels:
            try:
                return await channel.get_message(message_id)
            except discord.NotFound:
                pass
            except AttributeError:  # VoiceChannel object has no attribute 'get_message'
                pass
            except discord.Forbidden:  # No access to channel, skip
                pass

        return None 
Example #3
Source File: help_channels.py    From bot with MIT License 6 votes vote down vote up
def _change_cooldown_role(self, member: discord.Member, coro_func: CoroutineFunc) -> None:
        """
        Change `member`'s cooldown role via awaiting `coro_func` and handle errors.

        `coro_func` is intended to be `discord.Member.add_roles` or `discord.Member.remove_roles`.
        """
        guild = self.bot.get_guild(constants.Guild.id)
        role = guild.get_role(constants.Roles.help_cooldown)
        if role is None:
            log.warning(f"Help cooldown role ({constants.Roles.help_cooldown}) could not be found!")
            return

        try:
            await coro_func(role)
        except discord.NotFound:
            log.debug(f"Failed to change role for {member} ({member.id}): member not found")
        except discord.Forbidden:
            log.debug(
                f"Forbidden to change role for {member} ({member.id}); "
                f"possibly due to role hierarchy"
            )
        except discord.HTTPException as e:
            log.error(f"Failed to change role for {member} ({member.id}): {e.status} {e.code}") 
Example #4
Source File: help.py    From bot with MIT License 6 votes vote down vote up
def help_cleanup(bot: Bot, author: Member, message: Message) -> None:
    """
    Runs the cleanup for the help command.

    Adds the :trashcan: reaction that, when clicked, will delete the help message.
    After a 300 second timeout, the reaction will be removed.
    """
    def check(reaction: Reaction, user: User) -> bool:
        """Checks the reaction is :trashcan:, the author is original author and messages are the same."""
        return str(reaction) == DELETE_EMOJI and user.id == author.id and reaction.message.id == message.id

    await message.add_reaction(DELETE_EMOJI)

    try:
        await bot.wait_for("reaction_add", check=check, timeout=300)
        await message.delete()
    except TimeoutError:
        await message.remove_reaction(DELETE_EMOJI, bot.user)
    except NotFound:
        pass 
Example #5
Source File: builder.py    From Fox-V3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def next_group(ctx: commands.Context, pages: list,
                     controls: dict, message: discord.Message, page: int,
                     timeout: float, emoji: str):
    perms = message.channel.permissions_for(ctx.guild.me)
    if perms.manage_messages:  # Can manage messages, so remove react
        try:
            await message.remove_reaction(emoji, ctx.author)
        except discord.NotFound:
            pass
    page = bisect.bisect_right(PAGE_GROUPS, page)

    if page == len(PAGE_GROUPS):
        page = PAGE_GROUPS[0]
    else:
        page = PAGE_GROUPS[page]

    return await menu(ctx, pages, controls, message=message,
                      page=page, timeout=timeout) 
Example #6
Source File: antispam.py    From bot with MIT License 6 votes vote down vote up
def maybe_delete_messages(self, channel: TextChannel, messages: List[Message]) -> None:
        """Cleans the messages if cleaning is configured."""
        if AntiSpamConfig.clean_offending:
            # If we have more than one message, we can use bulk delete.
            if len(messages) > 1:
                message_ids = [message.id for message in messages]
                self.mod_log.ignore(Event.message_delete, *message_ids)
                await channel.delete_messages(messages)

            # Otherwise, the bulk delete endpoint will throw up.
            # Delete the message directly instead.
            else:
                self.mod_log.ignore(Event.message_delete, messages[0].id)
                try:
                    await messages[0].delete()
                except NotFound:
                    log.info(f"Tried to delete message `{messages[0].id}`, but message could not be found.") 
Example #7
Source File: converter.py    From discord.py with MIT License 6 votes vote down vote up
def convert(self, ctx, argument):
        id_regex = re.compile(r'^(?:(?P<channel_id>[0-9]{15,21})-)?(?P<message_id>[0-9]{15,21})$')
        link_regex = re.compile(
            r'^https?://(?:(ptb|canary)\.)?discord(?:app)?\.com/channels/'
            r'(?:([0-9]{15,21})|(@me))'
            r'/(?P<channel_id>[0-9]{15,21})/(?P<message_id>[0-9]{15,21})/?$'
        )
        match = id_regex.match(argument) or link_regex.match(argument)
        if not match:
            raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
        message_id = int(match.group("message_id"))
        channel_id = match.group("channel_id")
        message = ctx.bot._connection._get_message(message_id)
        if message:
            return message
        channel = ctx.bot.get_channel(int(channel_id)) if channel_id else ctx.channel
        if not channel:
            raise BadArgument('Channel "{channel}" not found.'.format(channel=channel_id))
        try:
            return await channel.fetch_message(message_id)
        except discord.NotFound:
            raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
        except discord.Forbidden:
            raise BadArgument("Can't read messages in {channel}".format(channel=channel.mention)) 
Example #8
Source File: builder.py    From Fox-V3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def select_page(self, ctx: commands.Context, pages: list,
                          controls: dict, message: discord.Message, page: int,
                          timeout: float, emoji: str):
        perms = message.channel.permissions_for(ctx.guild.me)
        if perms.manage_messages:  # Can manage messages, so remove react
            try:
                await message.remove_reaction(emoji, ctx.author)
            except discord.NotFound:
                pass

        if page >= len(ROLE_LIST):
            self.rand_roles.append(CATEGORY_COUNT[page - len(ROLE_LIST)])
        else:
            self.code.append(page)

        return await menu(ctx, pages, controls, message=message,
                          page=page, timeout=timeout) 
Example #9
Source File: checks.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def check_role_on_support_guild(role_name):
    async def predicate(ctx):
        support_guild = ctx.bot.get_guild(ctx.config.support_guild)
        if support_guild is None:
            log.warning("Support Guild is unavailable")
            raise cmd.CommandError(
                "The support guild is currently unavailable. Please try again later."
            )

        try:
            member = await support_guild.fetch_member(ctx.author.id)
        except discord.NotFound:
            raise cmd.CommandError("You need to be on the support guild to use this command.")

        roles = filter(lambda r: r.name == role_name, member.roles)
        if len(list(roles)) == 0:
            raise cmd.CommandError(
                f"You are **missing** the `{role_name}` **role** on the support guild."
            )

        return True

    return predicate 
Example #10
Source File: backups.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def _overwrites_from_json(self, json):
        overwrites = {}
        for union_id, overwrite in json.items():
            try:
                union = await self.guild.fetch_member(int(union_id))
            except discord.NotFound:
                roles = list(
                    filter(lambda r: r.id == self.id_translator.get(union_id), self.guild.roles))
                if len(roles) == 0:
                    continue

                union = roles[0]

            overwrites[union] = discord.PermissionOverwrite(**overwrite)

        return overwrites 
Example #11
Source File: shop.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def item23(self, ctx):
        """Buy a mechanical duck (40 exp)
        !shop 23"""
        message = ctx.message
        _ = self.bot._;
        language = await self.bot.db.get_pref(ctx.channel, "language")

        try:
            await ctx.message.delete()
        except discord.Forbidden:
            await self.bot.hint(ctx=ctx, message=_("If you ask a server admin to give me the `manage_message` permission, I will be able to delete that kind of shop commands ;)", language))
        except discord.NotFound:
            pass

        await self.bot.db.add_to_stat(message.channel, message.author, "exp", -40)
        await self.bot.send_message(ctx=ctx, force_pm=True, message=_(":money_with_wings: You prepared a mechanical duck on the channel for 40 exp. It's wrong, but so funny!", language))

        async def spawn_mech_duck():
            await asyncio.sleep(90)
            duck = await ducks.MechanicalDuck.create(self.bot, ctx.channel, user=ctx.message.author)
            await spawning.spawn_duck(self.bot, ctx.channel, instance=duck, ignore_event=True)

        asyncio.ensure_future(spawn_mech_duck()) 
Example #12
Source File: mod.py    From Discord-Selfbot with GNU General Public License v3.0 6 votes vote down vote up
def hackban(self, ctx, user_id: int):
        """Bans a user outside of the server."""
        author = ctx.message.author
        guild = author.guild

        user = guild.get_member(user_id)
        if user is not None:
            return await ctx.invoke(self.ban, user=user)

        try:
            await self.bot.http.ban(user_id, guild.id, 0)
            await ctx.message.edit(content=self.bot.bot_prefix + 'Banned user: %s' % user_id)
        except discord.NotFound:
            await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user. '
                               'Invalid user ID was provided.')
        except discord.errors.Forbidden:
            await ctx.message.edit(content=self.bot.bot_prefix + 'Could not ban user. Not enough permissions.') 
Example #13
Source File: error.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def send_error_message(self, pld):
        """
        Sends an error embed with an explanation to the
        channel where the command broke.
        :param pld: The command's payload data.
        :type pld: sigma.core.mechanics.payload.CommandPayload
        :return:
        :rtype:
        """
        title, err_text = self.get_error_message(pld.settings)
        error_embed = discord.Embed(color=0xBE1931)
        error_embed.add_field(name=title, value=err_text)
        error_embed.set_footer(text=f'Token: {self.token}')
        try:
            await pld.msg.channel.send(embed=error_embed)
        except (discord.Forbidden, discord.NotFound):
            pass 
Example #14
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def report(self, guild, incident_embed):
        """
        Reports the incident's contents to the guild's incident channel.
        :param guild: The guild that the incident happened in.
        :type guild: discord.Guild
        :param incident_embed: The incident embed to send to the guild's incident channel.
        :type incident_embed: discord.Embed
        :return:
        :rtype:
        """
        incident_channel_id = await self.db.get_guild_settings(guild.id, 'log_incidents_channel')
        incident_channel = guild.get_channel(incident_channel_id)
        if incident_channel:
            try:
                await incident_channel.send(embed=incident_embed)
            except (discord.Forbidden, discord.NotFound):
                pass 
Example #15
Source File: autorole_control.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def autorole_control(_ev, pld):
    """
    :param _ev: The main event instance referenced.
    :type _ev: sigma.core.mechanics.event.SigmaEvent
    :param pld: The event payload data to process.
    :type pld: sigma.core.mechanics.payload.MemberPayload
    """
    curr_role_id = pld.settings.get('auto_role')
    if curr_role_id:
        curr_role = pld.member.guild.get_role(curr_role_id)
        if curr_role:
            timeout = pld.settings.get('auto_role_timeout')
            if timeout:
                await asyncio.sleep(timeout)
            try:
                await pld.member.add_roles(curr_role, reason='Appointed guild autorole.')
            except (discord.NotFound, discord.Forbidden):
                pass 
Example #16
Source File: karma.py    From rubbergod with GNU General Public License v3.0 6 votes vote down vote up
def emoji_get_value(self, message):
        content = message.content.split()
        if len(content) != 3:
            return await self.emoji_list_all_values(message.channel)

        emoji = content[2]
        if not is_unicode(emoji):
            try:
                emoji_id = int(emoji.split(':')[2][:-1])
                emoji = await message.channel.guild.fetch_emoji(emoji_id)
            except (ValueError, IndexError):
                await message.channel.send(msg.karma_get_format)
                return
            except discord.NotFound:
                await message.channel.send(msg.karma_emote_not_found)
                return

        val = self.repo.emoji_value_raw(emoji)

        if val is not None:
            await message.channel.send(utils.fill_message("karma_get", emote=str(emoji), value=str(val)))
        else:
            await message.channel.send(utils.fill_message("karma_get_emote_not_voted", emote=str(emoji))) 
Example #17
Source File: mute_checker.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def mute_checker(ev, pld):
    """
    :param ev: The event object referenced in the event.
    :type ev: sigma.core.mechanics.event.SigmaEvent
    :param pld: The event payload data to process.
    :type pld: sigma.core.mechanics.payload.MessagePayload
    """
    if pld.msg.guild:
        if isinstance(pld.msg.author, discord.Member):
            if pld.msg.author.id not in ev.bot.cfg.dsc.owners:
                if not pld.msg.author.permissions_in(pld.msg.channel).administrator:
                    mute_list = pld.settings.get('muted_users') or []
                    if pld.msg.author.id in mute_list:
                        try:
                            await pld.msg.delete()
                        except discord.Forbidden:
                            pass
                        except discord.NotFound:
                            pass 
Example #18
Source File: dm_detection.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def has_invite(ev, arguments):
    """
    :param ev: The event object referenced in the event.
    :type ev: sigma.core.mechanics.event.SigmaEvent
    :param arguments:
    :type arguments:
    :return:
    :rtype:
    """
    invite_found = False
    for arg in arguments:
        triggers = ['discord.gg', 'discordapp.com']
        for trigger in triggers:
            if trigger in arg:
                try:
                    await ev.bot.fetch_invite(arg)
                    invite_found = True
                    break
                except discord.NotFound:
                    pass
    return invite_found 
Example #19
Source File: connectfour.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def send_board_msg(message, board_msg, board_resp):
    """
    :param message:
    :type message: discord.Message
    :param board_msg:
    :type board_msg: discord.Message
    :param board_resp:
    :type board_resp: discord.Embed
    :return:
    :rtype: discord.Message
    """
    replaced = False
    if board_msg:
        try:
            await board_msg.edit(embed=board_resp)
        except discord.NotFound:
            board_msg = await message.channel.send(embed=board_resp)
            replaced = True
    else:
        board_msg = await message.channel.send(embed=board_resp)
        replaced = True
    if replaced:
        [await board_msg.add_reaction(num) for num in nums]
    return board_msg 
Example #20
Source File: hangman.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def send_hangman_msg(message, hangman_msg, hangman_resp):
    """
    :param message:
    :type message: discord.Message
    :param hangman_msg:
    :type hangman_msg: discord.Message
    :param hangman_resp:
    :type hangman_resp: discord.Embed
    :return:
    :rtype: discord.Message
    """
    if hangman_msg:
        try:
            await hangman_msg.edit(embed=hangman_resp)
        except discord.NotFound:
            hangman_msg = await message.channel.send(embed=hangman_resp)
    else:
        hangman_msg = await message.channel.send(embed=hangman_resp)
    return hangman_msg 
Example #21
Source File: quote.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def message_search(lookup: int, message: discord.Message):
    """

    :param lookup:
    :type lookup:
    :param message:
    :type message:
    :return:
    :rtype:
    """
    try:
        msg = await message.channel.fetch_message(lookup)
    except discord.NotFound:
        msg = None
    if not msg:
        for channel in message.guild.channels:
            if isinstance(channel, discord.TextChannel):
                try:
                    msg = await channel.fetch_message(lookup)
                    break
                except (discord.Forbidden, discord.NotFound):
                    msg = None
    return msg 
Example #22
Source File: bot.py    From rhinobot_heroku with MIT License 5 votes vote down vote up
def cmd_perms(self, author, user_mentions, channel, guild, message, permissions, target=None):
        """
        Usage:
            {command_prefix}perms [@user]
        Sends the user a list of their permissions, or the permissions of the user specified.
        """

        if user_mentions:
            user = user_mentions[0]
            
        if not user_mentions and not target:
            user = author
            
        if not user_mentions and target:
            user = guild.get_member_named(target)
            if user == None:
                try:
                    user = await self.fetch_user(target)
                except discord.NotFound:
                    return Response("Invalid user ID or server nickname, please double check all typing and try again.", reply=False, delete_after=30)

        permissions = self.permissions.for_user(user)    
                    
        if user == author:
            lines = ['Command permissions in %s\n' % guild.name, '```', '```']
        else:
            lines = ['Command permissions for {} in {}\n'.format(user.name, guild.name), '```', '```']

        for perm in permissions.__dict__:
            if perm in ['user_list'] or permissions.__dict__[perm] == set():
                continue
            lines.insert(len(lines) - 1, "%s: %s" % (perm, permissions.__dict__[perm]))

        await self.safe_send_message(author, '\n'.join(lines))
        return Response("\N{OPEN MAILBOX WITH RAISED FLAG}", delete_after=20) 
Example #23
Source File: bot.py    From rhinobot_heroku with MIT License 5 votes vote down vote up
def safe_edit_message(self, message, new, *, send_if_fail=False, quiet=False):
        lfunc = log.debug if quiet else log.warning

        try:
            return await message.edit(content=new)

        except discord.NotFound:
            lfunc("Cannot edit message \"{}\", message not found".format(message.clean_content))
            if send_if_fail:
                lfunc("Sending message instead")
                return await self.safe_send_message(message.channel, new) 
Example #24
Source File: paginators.py    From jishaku with MIT License 5 votes vote down vote up
def update(self):
        """
        Updates this interface's messages with the latest data.
        """

        if self.update_lock.locked():
            return

        await self.send_lock.wait()

        async with self.update_lock:
            if self.update_lock.locked():
                # if this engagement has caused the semaphore to exhaust,
                # we are overloaded and need to calm down.
                await asyncio.sleep(1)

            if not self.message:
                # too fast, stagger so this update gets through
                await asyncio.sleep(0.5)

            if not self.sent_page_reactions and self.page_count > 1:
                self.bot.loop.create_task(self.send_all_reactions())
                self.sent_page_reactions = True  # don't spawn any more tasks

            try:
                await self.message.edit(**self.send_kwargs)
            except discord.NotFound:
                # something terrible has happened
                if self.task:
                    self.task.cancel() 
Example #25
Source File: reactrestrict.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_message_from_channel(
        self, channel_id: int, message_id: int
    ) -> Union[discord.Message, None]:
        """
        Tries to find a message by ID in the current guild context.
        """
        channel = self.bot.get_channel(channel_id)
        try:
            return await channel.get_message(message_id)
        except discord.NotFound:
            pass
        except AttributeError:  # VoiceChannel object has no attribute 'get_message'
            pass

        return None 
Example #26
Source File: announcedaily.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def addimg(self, ctx: commands.Context, filename=None):
        """
        Add an image to the pool of announcement images

        You must attach an image while executing this command
        """
        if ctx.message.attachments:
            att_ = ctx.message.attachments[0]
            try:
                att_.height
            except AttributeError:
                await ctx.send("You must attach an image, no other file will be accepted")
                return

            if filename is None:
                filename = att_.filename

            try:
                # with open(self.image_path + filename, 'w') as f:
                #     await att_.save(f)
                await att_.save(self.image_path + filename)
            except discord.NotFound:
                await ctx.send(
                    "Did you delete the message? Cause I couldn't download the attachment"
                )
            except discord.HTTPException:
                await ctx.send("Failed to download the attachment, please try again")
            else:
                async with self.config.images() as images:
                    if filename in images:
                        await ctx.send("Image {} has been overwritten!".format(filename))
                    else:
                        images.append(filename)
                        await ctx.send("Image {} has been added!".format(filename))
        else:
            await ctx.send("You must attach an image when sending this command") 
Example #27
Source File: builder.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def prev_group(ctx: commands.Context, pages: list,
                     controls: dict, message: discord.Message, page: int,
                     timeout: float, emoji: str):
    perms = message.channel.permissions_for(ctx.guild.me)
    if perms.manage_messages:  # Can manage messages, so remove react
        try:
            await message.remove_reaction(emoji, ctx.author)
        except discord.NotFound:
            pass
    page = PAGE_GROUPS[bisect.bisect_left(PAGE_GROUPS, page) - 1]

    return await menu(ctx, pages, controls, message=message,
                      page=page, timeout=timeout) 
Example #28
Source File: afk_mention_check.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def afk_mention_check(ev, pld):
    """
    :param ev: The event object referenced in the event.
    :type ev: sigma.core.mechanics.event.SigmaEvent
    :param pld: The event payload data to process.
    :type pld: sigma.core.mechanics.payload.MessagePayload
    """
    if pld.msg.guild:
        pfx = ev.db.get_prefix(pld.settings)
        if not pld.msg.content.startswith(pfx):
            if pld.msg.mentions:
                target = pld.msg.mentions[0]
                afk_data = await ev.db.cache.get_cache(f'afk_{pld.msg.author.id}')
                if not afk_data:
                    afk_data = await ev.db[ev.db.db_nam].AwayUsers.find_one({'user_id': target.id})
                if afk_data:
                    time_then = arrow.get(afk_data.get('timestamp', 0))
                    afk_time = arrow.get(time_then).humanize(arrow.utcnow()).title()
                    afk_reason = afk_data.get('reason')
                    url = None
                    for piece in afk_reason.split():
                        if piece.startswith('http'):
                            suffix = piece.split('.')[-1]
                            if suffix in ['gif', 'jpg', 'jpeg', 'png']:
                                afk_reason = afk_reason.replace(piece, '') if afk_reason is not None else afk_reason
                                url = piece
                                break
                    response = discord.Embed(color=0x3B88C3, timestamp=time_then.datetime)
                    reason = f'Reason: {afk_reason}\nWent AFK: {afk_time}'
                    response.add_field(name=f'ℹ {target.name} is AFK.', value=reason)
                    if url:
                        response.set_image(url=url)
                    afk_notify = await pld.msg.channel.send(embed=response)
                    await asyncio.sleep(5)
                    try:
                        await afk_notify.delete()
                    except discord.NotFound:
                        pass 
Example #29
Source File: approvesuggestion.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def approvesuggestion(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if len(pld.args) >= 3:
        token, title, description = parse_approval(pld.args)
        suggestion = await cmd.db[cmd.db.db_nam].Suggestions.find_one({'suggestion.id': token})
        if suggestion:
            await react_to_suggestion(cmd.bot, suggestion, '✅', False)
            make_issue = False if title.lower().startswith('noissue') else True
            title = title if make_issue else title.partition(' ')[2]
            gl_desc = make_gl_suggestion(token, description, suggestion)
            gl_issue_url = None
            if cmd.cfg.token and cmd.cfg.project and make_issue:
                gl_issue_url = await submit_gl_issue(cmd.cfg.token, cmd.cfg.project, title, gl_desc)
            athr = await cmd.bot.get_user(suggestion.get('user', {}).get('id'))
            if athr:
                to_user = ok(f'Suggestion {token} approved by {pld.msg.author.display_name}.')
                if gl_issue_url:
                    to_user_desc = 'Your suggestion was approved, you can view its status and details [here]'
                    to_user_desc += f'({gl_issue_url}). If you need info, the support server is in the help command.'
                else:
                    to_user_desc = f'```md\n{gl_desc}\n```'
                to_user.description = to_user_desc
                try:
                    await athr.send(embed=to_user)
                    response = ok(f'Suggestion {token} approved.')
                except (discord.Forbidden, discord.NotFound):
                    response = ok(f'Suggestion {token} approved, but delivery to author failed.')
            else:
                response = ok(f'Suggestion {token} approved, but the author was not found.')
        else:
            response = error('No suggestion entry with that ID was found.')
    else:
        response = error('Not enough arguments.')
    await pld.msg.channel.send(embed=response) 
Example #30
Source File: error.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def get_error_message(self, settings):
        """
        Generates a message to show to the users
        that were affected by the command breaking.
        :param settings: The guild's settings.
        :type settings: dict
        :return:
        :rtype: (str, str)
        """
        prefix = self.cmd.db.get_prefix(settings)
        # escapes markdown formatting
        name = self.cmd.name
        for escapable in '*_~`':
            prefix = prefix.replace(escapable, f'\\{escapable}')
        if isinstance(self.exception, discord.Forbidden):
            title = '❗ Error: Forbidden!'
            err_text = f'It seems that you tried running something that {name} isn\'t allowed to'
            err_text += f' do. This is something when {name} is missing permissions for stuff'
            err_text += ' like sending messages, adding reactions, uploading files, etc. The'
            err_text += ' error has been relayed to the developers. If you feel like dropping by'
            err_text += f' and asking about it, the invite link is in the **{prefix}help** command.'
        elif isinstance(self.exception, discord.NotFound):
            title = '❗ Error: Not Found!'
            err_text = 'It might have been a target that got removed while the command was'
            err_text += f' executing, whatever it was, {name} couldn\'t find it and encountered an'
            err_text += ' error. The error has been relayed to the developers. If you feel like'
            err_text += f' dropping by and asking about it, the invite link is in the **{prefix}help** command.'
        else:
            title = '❗ An Unhandled Error Occurred!'
            err_text = 'Something seems to have gone wrong.'
            err_text += ' Please be patient while we work on fixing the issue.'
            err_text += ' The error has been relayed to the developers.'
            err_text += ' If you feel like dropping by and asking about it,'
            err_text += f' the invite link is in the **{prefix}help** command.'
        return title, err_text