Python discord.DMChannel() Examples

The following are 22 code examples of discord.DMChannel(). 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: bot.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def on_typing(self, channel, user, _):
        await self.wait_for_connected()

        if user.bot:
            return

        if isinstance(channel, discord.DMChannel):
            if not self.config.get("user_typing"):
                return

            thread = await self.threads.find(recipient=user)

            if thread:
                await thread.channel.trigger_typing()
        else:
            if not self.config.get("mod_typing"):
                return

            thread = await self.threads.find(channel=channel)
            if thread is not None and thread.recipient:
                if await self.is_blocked(thread.recipient):
                    return
                await thread.recipient.trigger_typing() 
Example #2
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(
        self,
        manager: "ThreadManager",
        recipient: typing.Union[discord.Member, discord.User, int],
        channel: typing.Union[discord.DMChannel, discord.TextChannel] = None,
    ):
        self.manager = manager
        self.bot = manager.bot
        if isinstance(recipient, int):
            self._id = recipient
            self._recipient = None
        else:
            if recipient.bot:
                raise CommandError("Recipient cannot be a bot.")
            self._id = recipient.id
            self._recipient = recipient
        self._channel = channel
        self.genesis_message = None
        self._ready_event = asyncio.Event()
        self.close_task = None
        self.auto_close_task = None 
Example #3
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def on_message_edit(self, before, after):
        if after.author.bot:
            return
        if before.content == after.content:
            return

        if isinstance(after.channel, discord.DMChannel):
            thread = await self.threads.find(recipient=before.author)
            if not thread:
                return

            try:
                await thread.edit_dm_message(after, after.content)
            except ValueError:
                _, blocked_emoji = await self.retrieve_emoji()
                await self.add_reaction(after, blocked_emoji)
            else:
                embed = discord.Embed(
                    description="Successfully Edited Message", color=self.main_color
                )
                embed.set_footer(text=f"Message ID: {after.id}")
                await after.channel.send(embed=embed) 
Example #4
Source File: main.py    From discord_bot with MIT License 5 votes vote down vote up
def on_command(ctx):
    bot.commands_used[ctx.command.name] += 1
    msg = ctx.message
    # if isinstance(msg.channel, discord.Channel):
    #     #dest = f'#{msg.channel.name} ({msg.guild.name})'
    #     dest = f'#{msg.channel.name}'
    # elif isinstance(msg.channel, discord.DMChannel):
    #     dest = 'Direct Message'
    # elif isinstance(msg.channel, discord.GroupChannel):
    #     dest = 'Group Message'
    # else:
    #     dest = 'Voice Channel'
    # logging.info(f'{msg.created_at}: {msg.author.name} in {dest}: {msg.content}') 
Example #5
Source File: filter.py    From nano-chan with MIT License 5 votes vote down vote up
def on_message(self, message):
        if message.author.id in self.bot.blglobal:
            return
        if isinstance(message.channel, discord.DMChannel):
            return
        if message.channel.id not in self.channels:
            return
        if message.author.bot:
            return
        cleaned_message = message.clean_content
        if cleaned_message in self.filter_allowed:
            return
        try:
            await message.delete()
            await self.bot.pg_controller.add_message_delete(
                message.author.id
            )
            user_deleted = await self.bot.pg_controller.get_message_deleted(
                message.author.id
            )
            if int(user_deleted) in [5,10,20,100]:
                time = self.bot.timestamp()
                mod_info = self.bot.get_channel(259728514914189312)
                await mod_info.send(
                    f'**{time} | SPAM:** {message.author} has had {user_deleted} '\
                    f'messages deleted in {message.channel.name}'
                )
            self.bot.logger.info(
                'Successfully deleted message from: '
                f'{message.author.display_name}')
        except Exception as e:
            self.bot.logger.warning(f'Error deleting message: {e}') 
Example #6
Source File: db.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def allowed_nsfw_types(cls, allow_nsfw: AllowNsfwType):
		"""return the allowed values for the nsfw column in an emote row based on the allow_nsfw argument.
		if it's a channel (any kind), return whether the channel is NSFW.
		else, return the argument.

		This is mostly useful for database functions which take in either a bool or channel and need to convert to
		something that can be passed into a SQL WHERE clause.
		"""
		if isinstance(allow_nsfw, (discord.DMChannel, discord.TextChannel)):
			allow_nsfw = utils.channel_is_nsfw(allow_nsfw)
		return ('SFW', 'SELF_NSFW', 'MOD_NSFW') if allow_nsfw else ('SFW',) 
Example #7
Source File: selfbot.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def before_invoke(ctx):
    bot.commands_triggered[ctx.command.qualified_name] += 1
    if isinstance(ctx.channel, discord.DMChannel):
        destination = f'PM with {ctx.channel.recipient}'
    elif isinstance(ctx.channel, discord.GroupChannel):
        destination = f'Group {ctx.channel}'
    else:
        destination = f'#{ctx.channel.name},({ctx.guild.name})'
    log.info('In {}: {}'.format(destination, ctx.message.content.strip(ctx.prefix))) 
Example #8
Source File: cmds.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def log_command(self, ctx, command):
        self.bot.commands_triggered[command] += 1
        if isinstance(ctx.channel, discord.DMChannel):
            destination = f'PM with {ctx.channel.recipient}'
        elif isinstance(ctx.channel, discord.GroupChannel):
            destination = f'Group {ctx.channel}'
        else:
            destination = f'#{ctx.channel.name},({ctx.guild.name})'
        log.info(f'In {destination}: {command}')

    # Cumstom Commands with prefix 
Example #9
Source File: chat.py    From xiaomi_uranus_chatbot with GNU General Public License v3.0 5 votes vote down vote up
def get_chat_info(message) -> dict:
    """Returns a dictionary of user information"""
    if isinstance(message.channel, DMChannel):
        chat_type = "user"
        name = message.channel.recipient.name
        guild_id = None
        guild_name = None
    else:
        chat_type = "channel"
        name = message.channel.name
        guild_id = message.guild.id
        guild_name = message.guild.name
    return {'id': message.channel.id, 'name': name,'type': chat_type,
            'guild_id': guild_id, 'guild_name': guild_name} 
Example #10
Source File: subscriptions.py    From xiaomi_uranus_chatbot with GNU General Public License v3.0 5 votes vote down vote up
def subscription_allowed(message) -> bool:
    """Check if the subscription is allowed"""
    return bool(isinstance(message.channel, DMChannel)
                or message.author.guild_permissions.administrator
                or message.author.id in DISCORD_BOT_ADMINS) 
Example #11
Source File: clients.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def append_log(
        self,
        message: Message,
        *,
        message_id: str = "",
        channel_id: str = "",
        type_: str = "thread_message",
    ) -> dict:
        channel_id = str(channel_id) or str(message.channel.id)
        message_id = str(message_id) or str(message.id)

        data = {
            "timestamp": str(message.created_at),
            "message_id": message_id,
            "author": {
                "id": str(message.author.id),
                "name": message.author.name,
                "discriminator": message.author.discriminator,
                "avatar_url": str(message.author.avatar_url),
                "mod": not isinstance(message.channel, DMChannel),
            },
            "content": message.content,
            "type": type_,
            "attachments": [
                {
                    "id": a.id,
                    "filename": a.filename,
                    "is_image": a.width is not None,
                    "size": a.size,
                    "url": a.url,
                }
                for a in message.attachments
            ],
        }

        return await self.logs.find_one_and_update(
            {"channel_id": channel_id}, {"$push": {"messages": data}}, return_document=True
        ) 
Example #12
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_message_delete(self, message):
        """Support for deleting linked messages"""
        # TODO: use audit log to check if modmail deleted the message
        if isinstance(message.channel, discord.DMChannel):
            thread = await self.threads.find(recipient=message.author)
            if not thread:
                return
            try:
                message = await thread.find_linked_message_from_dm(message)
            except ValueError as e:
                if str(e) != "Thread channel message not found.":
                    logger.warning("Failed to find linked message to delete: %s", e)
                return
            embed = message.embeds[0]
            embed.set_footer(text=f"{embed.footer.text} (deleted)", icon_url=embed.footer.icon_url)
            await message.edit(embed=embed)
            return

        thread = await self.threads.find(channel=message.channel)
        if not thread:
            return
        try:
            await thread.delete_message(message, note=False)
        except ValueError as e:
            if str(e) not in {"DM message not found.", "Malformed thread message."}:
                logger.warning("Failed to find linked message to delete: %s", e)
            return
        except discord.NotFound:
            return 
Example #13
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_commands(self, message):
        if message.author.bot:
            return

        if isinstance(message.channel, discord.DMChannel):
            return await self.process_dm_modmail(message)

        if message.content.startswith(self.prefix):
            cmd = message.content[len(self.prefix) :].strip()

            # Process snippets
            if cmd in self.snippets:
                snippet = self.snippets[cmd]
                message.content = f"{self.prefix}freply {snippet}"

        ctxs = await self.get_contexts(message)
        for ctx in ctxs:
            if ctx.command:
                if not any(
                    1 for check in ctx.command.checks if hasattr(check, "permission_level")
                ):
                    logger.debug(
                        "Command %s has no permissions check, adding invalid level.",
                        ctx.command.qualified_name,
                    )
                    checks.has_permissions(PermissionLevel.INVALID)(ctx.command)

                await self.invoke(ctx)
                continue

            thread = await self.threads.find(channel=ctx.channel)
            if thread is not None:
                if self.config.get("anon_reply_without_command"):
                    await thread.reply(message, anonymous=True)
                elif self.config.get("reply_without_command"):
                    await thread.reply(message)
                else:
                    await self.api.append_log(message, type_="internal")
            elif ctx.invoked_with:
                exc = commands.CommandNotFound(
                    'Command "{}" is not found'.format(ctx.invoked_with)
                )
                self.dispatch("command_error", ctx, exc) 
Example #14
Source File: bot.py    From modmailbotkenng with MIT License 5 votes vote down vote up
def on_message(self, message):
        if message.author.bot:
            return
        await self.process_commands(message)
        if isinstance(message.channel, discord.DMChannel):
            await self.process_modmail(message) 
Example #15
Source File: general.py    From MangoByte with MIT License 5 votes vote down vote up
def wiki(self, ctx, *, thing : str):
		"""Looks up a thing on wikipedia
		
		Uses my own implementation of the [Wikipedia API](https://www.mediawiki.org/wiki/API:Tutorial)

		You can also try `{cmdpfx} wiki random` to get a random wiki page
		
		Note that I've had to remove the images from these (unless you're in a NSFW channel) because I have no way of checking if it is an NSFW image, and posting an NSFW image in non-NSFW channels would be against discord's ToS. Sorry about that!

		**Example:**
		`{cmdpfx}wiki potato`
		"""
		await ctx.channel.trigger_typing()

		page = await wikipedia.get_wikipedia_page(thing)

		embed = discord.Embed(description=page.markdown)
		embed.title = f"**{page.title}**"
		embed.url = page.url

		footer_text = "Retrieved from Wikipedia"

		if page.image:
			if (not isinstance(ctx.channel, discord.DMChannel)) and ctx.channel.is_nsfw():
				embed.set_image(url=page.image)
			else:
				footer_text += ". (Image omitted because I can't check if it is NSFW) D:"

		embed.set_footer(text=footer_text, icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Wikipedia's_W.svg/2000px-Wikipedia's_W.svg.png")
		
		await ctx.send(embed=embed) 
Example #16
Source File: help.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def send(self):
        """A helper utility to send the page output from :attr:`paginator` to the destination."""
        destination = self.get_destination()
        for embed in self.embed_paginator.embeds:
            await destination.send(embed=embed)

        if not isinstance(self.context.channel, discord.DMChannel) and self.in_dms:
            await self.context.channel.send("I have sent help to your PMs.") 
Example #17
Source File: command.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def guild_or_channel_id(channel: Union[TextChannel, DMChannel, GroupChannel]) -> int:
    return getattr(channel, 'guild', channel).id 
Example #18
Source File: watchchannel.py    From bot with MIT License 5 votes vote down vote up
def send_header(self, msg: Message) -> None:
        """Sends a header embed with information about the relayed messages to the watch channel."""
        user_id = msg.author.id

        guild = self.bot.get_guild(GuildConfig.id)
        actor = guild.get_member(self.watched_users[user_id]['actor'])
        actor = actor.display_name if actor else self.watched_users[user_id]['actor']

        inserted_at = self.watched_users[user_id]['inserted_at']
        time_delta = self._get_time_delta(inserted_at)

        reason = self.watched_users[user_id]['reason']

        if isinstance(msg.channel, DMChannel):
            # If a watched user DMs the bot there won't be a channel name or jump URL
            # This could technically include a GroupChannel but bot's can't be in those
            message_jump = "via DM"
        else:
            message_jump = f"in [#{msg.channel.name}]({msg.jump_url})"

        footer = f"Added {time_delta} by {actor} | Reason: {reason}"
        embed = Embed(description=f"{msg.author.mention} {message_jump}")
        embed.set_footer(text=textwrap.shorten(footer, width=128, placeholder="..."))

        await self.webhook_send(embed=embed, username=msg.author.display_name, avatar_url=msg.author.avatar_url) 
Example #19
Source File: general.py    From MangoByte with MIT License 4 votes vote down vote up
def reddit(self, ctx, url_or_id):
		"""Displays a formatted reddit post

		Note that this will only get nsfw posts if you call this in an nsfw channel"""
		if settings.reddit is None:
			raise UserError("This MangoByte has not been configured to get reddit submissions. Gotta add your info to `settings.json`")

		await ctx.channel.trigger_typing()

		reddit = praw.Reddit(client_id=settings.reddit["client_id"],
			client_secret=settings.reddit["client_secret"],
			user_agent=settings.reddit["user_agent"])

		try:
			if re.search(r"(redd\.it|reddit.com)", url_or_id):
				if not re.search(r"https?://", url_or_id):
					url_or_id = "http://" + url_or_id
				submission = reddit.submission(url=url_or_id)
			else:
				submission = reddit.submission(id=url_or_id)
			description = submission.selftext
		except:
			raise UserError("Couldn't properly find that reddit submission")

		
		if submission.over_18:
			if (isinstance(ctx.channel, discord.DMChannel)) or (not ctx.channel.is_nsfw()):
				raise UserError("That is an NSFW post, so I can't link it in this non-nsfw channel.")


		character_limit = 600
		# convert between markdown types
		description = re.sub(r"\n(?:\*|-) (.*)", r"\n• \1", description)
		description = re.sub(r"(?:^|\n)#+([^#\n]+)\n", r"\n__**\1**__ \n", description)
		description = re.sub(r"\n+---\n+", r"\n\n", description)
		description = re.sub(r" ", r" ", description)

		description = html.unescape(description)

		if len(description) > character_limit:
			description = f"{description[0:character_limit]}...\n[Read More]({submission.shortlink})"

		embed = discord.Embed(description=description, color=discord.Color(int("ff4500", 16)))
		embed.set_footer(text=f"/r/{submission.subreddit}", icon_url="https://images-na.ssl-images-amazon.com/images/I/418PuxYS63L.png")

		embed.title = submission.title
		embed.url = submission.shortlink

		url_ext = submission.url.split(".")[-1]

		if url_ext in ["gifv", "gif", "png", "jpg", "jpeg"]:
			image_url = submission.url
			if url_ext == "gifv":
				image_url = image_url.replace(".gifv", ".gif")
			embed.set_image(url=image_url)

		await ctx.send(embed=embed) 
Example #20
Source File: emote_role_toggle.py    From apex-sigma-core with GNU General Public License v3.0 4 votes vote down vote up
def emote_role_toggle(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.RawReactionPayload
    """
    payload = pld.raw
    uid = payload.user_id
    cid = payload.channel_id
    mid = payload.message_id
    emoji = payload.emoji
    channel = await ev.bot.get_channel(cid)
    if isinstance(channel, discord.DMChannel):
        return
    if hasattr(channel, 'guild'):
        guild = channel.guild
        if guild:
            guild_togglers = await ev.db.get_guild_settings(guild.id, 'emote_role_togglers') or {}
            if guild_togglers:
                user = guild.get_member(uid)
                if user:
                    if not user.bot:
                        try:
                            message = await channel.fetch_message(mid)
                        except (discord.NotFound, discord.Forbidden):
                            message = None
                        if message:
                            smid = str(mid)
                            if smid in guild_togglers:
                                if ev.event_type == 'raw_reaction_add':
                                    try:
                                        await check_emotes(ev.bot, message, guild_togglers.get(smid))
                                    except (discord.NotFound, discord.Forbidden):
                                        pass
                                role_id = guild_togglers.get(smid).get(emoji.name)
                                if role_id:
                                    role_item = guild.get_role(role_id)
                                    if role_item:
                                        if user_has_role(role_item, user.roles):
                                            await user.remove_roles(role_item, reason='Emote toggled.')
                                        else:
                                            await user.add_roles(role_item, reason='Emote toggled.') 
Example #21
Source File: starboard_watcher.py    From apex-sigma-core with GNU General Public License v3.0 4 votes vote down vote up
def starboard_watcher(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.RawReactionPayload
    """
    global star_cache
    if not star_cache:
        star_cache = MemoryCacher(CacheConfig({}))
    payload = pld.raw
    uid = payload.user_id
    cid = payload.channel_id
    mid = payload.message_id
    emoji = payload.emoji
    channel = await ev.bot.get_channel(cid)
    if isinstance(channel, discord.DMChannel):
        return
    if hasattr(channel, 'guild'):
        guild = channel.guild
        if guild:
            starboard_doc = await ev.db.get_guild_settings(guild.id, 'starboard') or {}
            if starboard_doc.get('state'):
                sbc = starboard_doc.get('channel_id')
                sbe = starboard_doc.get('emote')
                sbl = starboard_doc.get('limit')
                if sbc and sbe and sbl:
                    if channel.id != sbc:
                        if emoji.name == sbe:
                            user = guild.get_member(uid)
                            if user:
                                if not user.bot:
                                    try:
                                        enough = await check_emotes(mid, uid, sbl)
                                        if enough:
                                            message = await channel.fetch_message(mid)
                                            if not message.author.bot:
                                                response = await generate_embed(message)
                                                if response:
                                                    await post_starboard(message, response, sbc)
                                    except (discord.NotFound, discord.Forbidden):
                                        pass 
Example #22
Source File: helpers.py    From bot with MIT License 4 votes vote down vote up
def __init__(self, **kwargs) -> None:
        default_kwargs = {'id': next(self.discord_id), 'name': 'channel', 'guild': MockGuild()}
        super().__init__(**collections.ChainMap(kwargs, default_kwargs))

        if 'mention' not in kwargs:
            self.mention = f"#{self.name}"


# Create data for the DMChannel instance