How to use the discord.Forbidden function in discord

To help you get started, we’ve selected a few discord examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github FoglyOgly / Meowth / meowth / exts / raid / objects.py View on Github external
await msg.edit(content=content, embed=embed)
                try:
                    await msg.clear_reactions()
                except discord.Forbidden:
                    pass
                msg_list.append(msg)
            for msgid in self.train_msgs:
                chn, msg = await ChannelMessage.from_id_string(self.bot, msgid)
                if not msg:
                    continue
                if chn in channel_list:
                    continue
                await msg.edit(content=content, embed=embed)
                try:
                    await msg.clear_reactions()
                except discord.Forbidden:
                    raise commands.BotMissingPermissions(['Manage Messages'])
                msg_list.append(msg)
            for msg in msg_list:
                for react in react_list:
                    if isinstance(react, int):
                        react = self.bot.get_emoji(react)
                    await msg.add_reaction(react)
            response = await formatters.ask(self.bot, msg_list, timeout=(self.end-time.time()),
                react_list=react_list)
            if response:
                emoji = str(response.emoji)
                for m in msg_list:
                    idstring = f'{m.channel.id}/{m.id}'
                    if idstring not in self.message_ids:
                        chn, msg = await ChannelMessage.from_id_string(self.bot, idstring)
                        if msg:
github Kenny2github / kenny2automate / kenny2automate / wiki.py View on Github external
async def login(self, ctx, wiki, username, *, password):
		"""Login to a Wiki. MUST BE IN DMS."""
		if ctx.guild is not None:
			try:
				await ctx.message.delete()
			except d.Forbidden:
				await ctx.send(embed=_embed(ctx,
					title=('error',),
					description=('wiki/login-notdm-nodelete',),
					color=0xff0000
				))
			else:
				msg = await ctx.send(embed=_embed(ctx,
					title=('error',),
					description=('wiki/login-notdm',),
					color=0xff0000
				))
				await a.sleep(2)
				await msg.delete()
			finally:
				return
		async with ctx.channel.typing():
github gearbot / GearBot / GearBot / Util / GearbotLogging.py View on Github external
if channel is None:
                del LOG_QUEUE[target]
                Configuration.validate_config(guild_id)
                return
            # pull message from queue
            todo = LOG_QUEUE[target].get(block=False)
            if (len(to_send) + len(todo.message) if todo.message is not None else 0) < 2000:
                to_send = f'{to_send}\n{todo.message if todo.message is not None else ""}'
            else:
                # too large, send it out
                await channel.send(to_send)
                to_send = todo.message
            if todo.embed is not None or todo.file is not None or LOG_QUEUE[target].empty():
                await channel.send(to_send, embed=todo.embed, file=todo.file)
                to_send = ""
        except discord.Forbidden:
            # someone screwed up their permissions, not my problem, will show an error in the dashboard
            del LOG_QUEUE[target]
            return
        except CancelledError:
            return  # bot is terminating
        except Exception as e:
            del LOG_QUEUE[target]
            await TheRealGearBot.handle_exception("LOG PUMP", BOT, e,
                                                  cid=target, todo=todo, to_send=to_send)
            return
    del LOG_QUEUE[target]
github Cog-Creators / Red-DiscordBot / redbot / cogs / filter / filter.py View on Github external
async def _channel_list(self, ctx: commands.Context):
        """Send the list of the channel's filtered words."""
        channel = ctx.channel
        author = ctx.author
        word_list = await self.config.channel(channel).filter()
        if not word_list:
            await ctx.send(_("There is no current words setup to be filtered in this channel."))
            return
        words = humanize_list(word_list)
        words = _("Filtered in this channel:") + "\n\n" + words
        try:
            for page in pagify(words, delims=[" ", "\n"], shorten_by=8):
                await author.send(page)
        except discord.Forbidden:
            await ctx.send(_("I can't send direct messages to you."))
github Cog-Creators / Red-DiscordBot / redbot / core / utils / menus.py View on Github external
except discord.NotFound:
            return

    try:
        react, user = await ctx.bot.wait_for(
            "reaction_add",
            check=ReactionPredicate.with_emojis(tuple(controls.keys()), message, ctx.author),
            timeout=timeout,
        )
    except asyncio.TimeoutError:
        try:
            if message.channel.permissions_for(ctx.me).manage_messages:
                await message.clear_reactions()
            else:
                raise RuntimeError
        except (discord.Forbidden, RuntimeError):  # cannot remove all reactions
            for key in controls.keys():
                try:
                    await message.remove_reaction(key, ctx.bot.user)
                except discord.Forbidden:
                    return
                except discord.HTTPException:
                    pass
        except discord.NotFound:
            return
    else:
        return await controls[react.emoji](
            ctx, pages, controls, message, page, timeout, react.emoji
        )
github henry232323 / RPGBot / RPGBot.py View on Github external
async def on_command_error(self, ctx, exception):
        self.stats.increment("RPGBot.errors", tags=["RPGBot:errors"], host="scw-8112e8")
        logging.info(f"Exception in {ctx.command} {ctx.guild}:{ctx.channel} {exception}")
        exception = getattr(exception, "original", exception)
        traceback.print_tb(exception.__traceback__)
        print(exception)
        try:
            if isinstance(exception, commands.MissingRequiredArgument):
                await ctx.send(f"```{exception}```")
            elif isinstance(exception, TimeoutError):
                await ctx.send(await _(ctx, "This operation ran out of time! Please try again"))
            elif isinstance(exception, discord.Forbidden):
                await ctx.send(await _(ctx, "Error: This command requires the bot to have permission to send links."))
            else:
                await ctx.send(f"`{exception} If this is unexpected, please report this to the bot creator`")
        except discord.Forbidden:
            pass
github lu-ci / apex-sigma-core / sigma / modules / development / suggestions / approvesuggestion.py View on Github external
:param delete:
    :type delete:
    """
    sugg_cmd = bot.modules.commands.get('botsuggest')
    if sugg_cmd:
        if sugg_cmd.cfg.channel:
            sugg_chn = await bot.get_channel(sugg_cmd.cfg.channel, True)
            if sugg_chn:
                try:
                    smsg = await sugg_chn.fetch_message(suggestion.get('message'))
                    if smsg:
                        if delete:
                            await smsg.delete()
                        else:
                            await smsg.add_reaction(reaction)
                except (discord.Forbidden, discord.NotFound):
                    pass
github Magic-Bots / xenon / cogs / utils / backups.py View on Github external
"nsfw": channel.is_nsfw(),
                        "type": "text",

                        "overwrites": {str(overwrite[0].id): overwrite[1]._values for overwrite in channel.overwrites if
                                       type(overwrite[0]) == discord.Role},

                        "webhooks": [],
                        "messages": []
                    }

                    try:
                        channel_data["webhooks"] = [{
                            "name": webhook.name,
                            "avatar": webhook.avatar_url
                        } for webhook in await channel.webhooks()]
                    except discord.Forbidden:
                        pass

                    try:
                        async for message in channel.history(limit=chatlog):
                            if message.clean_content.replace(" ", "") != "" or len(message.embeds) != 0:
                                channel_data["messages"].append(
                                    {
                                        "content": message.system_content,
                                        "embeds": [embed.to_dict() for embed in message.embeds],
                                        "attachments": [attachment.url for attachment in message.attachments],
                                        "timestamp": message.created_at.strftime('%Y/%b/%d, %H:%M'),
                                        "pinned": message.pinned,

                                        "reactions": [str(reaction.emoji) for reaction in message.reactions if
                                                      type(reaction.emoji) == str],
github python-discord / seasonalbot / bot / seasons / valentines / be_my_valentine.py View on Github external
valentine, title = self.valentine_check(valentine_type)

        if user is None:
            author = ctx.author
            user = self.random_user(author, lovefest_role.members)
            if user is None:
                return await ctx.send("There are no users avilable to whome your valentine can be sent.")

        embed = discord.Embed(
            title=f'{emoji_1}{title} {user.display_name}{emoji_2}',
            description=f'{valentine} \n **{emoji_2}From anonymous{emoji_1}**',
            color=Colours.pink
        )
        try:
            await user.send(embed=embed)
        except discord.Forbidden:
            await ctx.author.send(f"{user} has DMs disabled, so I couldn't send the message. Sorry!")
        else:
            await ctx.author.send(f"Your message has been sent to {user}")