Python discord.Message() Examples
The following are 30
code examples of discord.Message().
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: antispam.py From bot with MIT License | 6 votes |
def punish(self, msg: Message, member: Member, reason: str) -> None: """Punishes the given member for triggering an antispam rule.""" if not any(role.id == self.muted_role.id for role in member.roles): remove_role_after = AntiSpamConfig.punishment['remove_after'] # Get context and make sure the bot becomes the actor of infraction by patching the `author` attributes context = await self.bot.get_context(msg) context.author = self.bot.user context.message.author = self.bot.user # Since we're going to invoke the tempmute command directly, we need to manually call the converter. dt_remove_role_after = await self.expiration_date_converter.convert(context, f"{remove_role_after}S") await context.invoke( self.bot.get_command('tempmute'), member, dt_remove_role_after, reason=reason )
Example #2
Source File: snekbox.py From bot with MIT License | 6 votes |
def get_code(self, message: Message) -> Optional[str]: """ Return the code from `message` to be evaluated. If the message is an invocation of the eval command, return the first argument or None if it doesn't exist. Otherwise, return the full content of the message. """ log.trace(f"Getting context for message {message.id}.") new_ctx = await self.bot.get_context(message) if new_ctx.command is self.eval_command: log.trace(f"Message {message.id} invokes eval command.") split = message.content.split(maxsplit=1) code = split[1] if len(split) > 1 else None else: log.trace(f"Message {message.id} does not invoke eval command.") code = message.content return code
Example #3
Source File: help_channels.py From bot with MIT License | 6 votes |
def on_message_delete(self, msg: discord.Message) -> None: """ Reschedule an in-use channel to become dormant sooner if the channel is empty. The new time for the dormant task is configured with `HelpChannels.deleted_idle_minutes`. """ if not self.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await self.is_empty(msg.channel): return log.info(f"Claimant of #{msg.channel} ({msg.author}) deleted message, channel is empty now. Rescheduling task.") # Cancel existing dormant task before scheduling new. self.cancel_task(msg.channel.id) task = TaskData(constants.HelpChannels.deleted_idle_minutes * 60, self.move_idle_channel(msg.channel)) self.schedule_task(msg.channel.id, task)
Example #4
Source File: help.py From bot with MIT License | 6 votes |
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: help_channels.py From bot with MIT License | 6 votes |
def check_for_answer(self, message: discord.Message) -> None: """Checks for whether new content in a help channel comes from non-claimants.""" channel = message.channel # Confirm the channel is an in use help channel if self.is_in_category(channel, constants.Categories.help_in_use): log.trace(f"Checking if #{channel} ({channel.id}) has been answered.") # Check if there is an entry in unanswered if await self.unanswered.contains(channel.id): claimant_id = await self.help_channel_claimants.get(channel.id) if not claimant_id: # The mapping for this channel doesn't exist, we can't do anything. return # Check the message did not come from the claimant if claimant_id != message.author.id: # Mark the channel as answered await self.unanswered.set(channel.id, False)
Example #6
Source File: attachments.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total attachments exceeding the limit sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if ( msg.author == last_message.author and len(msg.attachments) > 0 ) ) total_recent_attachments = sum(len(msg.attachments) for msg in relevant_messages) if total_recent_attachments > config['max']: return ( f"sent {total_recent_attachments} attachments in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #7
Source File: burst.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects repeated messages sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if msg.author == last_message.author ) total_relevant = len(relevant_messages) if total_relevant > config['max']: return ( f"sent {total_relevant} messages in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #8
Source File: paginator.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def start(self, ctx, page=None): """Start the session with the given page. Parameters ----------- page: Optional[str, discord.Embed, discord.Message] If no page is given, the message used to invoke the command will be used. Otherwise if an embed or str is passed, a new message will be created. """ if not page: page = ctx.message if isinstance(page, discord.Embed): self.page = await ctx.send(embed=page) elif isinstance(page, discord.Message): self.page = page else: self.page = await ctx.send(page) self._session_task = ctx.bot.loop.create_task(self._session(ctx))
Example #9
Source File: converter.py From discord.py with MIT License | 6 votes |
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 #10
Source File: antispam.py From bot with MIT License | 6 votes |
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 #11
Source File: filtering.py From bot with MIT License | 6 votes |
def _has_rich_embed(msg: Message) -> bool: """Determines if `msg` contains any rich embeds not auto-generated from a URL.""" if msg.embeds: for embed in msg.embeds: if embed.type == "rich": urls = URL_RE.findall(msg.content) if not embed.url or embed.url not in urls: # If `embed.url` does not exist or if `embed.url` is not part of the content # of the message, it's unlikely to be an auto-generated embed by Discord. return True else: log.trace( "Found a rich embed sent by a regular user account, " "but it was likely just an automatic URL embed." ) return False return False
Example #12
Source File: mentions.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total mentions exceeding the limit sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if msg.author == last_message.author ) total_recent_mentions = sum(len(msg.mentions) for msg in relevant_messages) if total_recent_mentions > config['max']: return ( f"sent {total_recent_mentions} mentions in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #13
Source File: role_mentions.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total role mentions exceeding the limit sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if msg.author == last_message.author ) total_recent_mentions = sum(len(msg.role_mentions) for msg in relevant_messages) if total_recent_mentions > config['max']: return ( f"sent {total_recent_mentions} role mentions in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #14
Source File: scheduler.py From calebj-cogs with GNU General Public License v3.0 | 6 votes |
def dispatch_fake(self, channel, author_id, name, command): prefix = self.bot.settings.get_prefixes(channel.server)[0] data = {} timestamp = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime()) data['timestamp'] = timestamp data['id'] = randint(10**(17), (10**18) - 1) data['content'] = prefix + command data['channel'] = channel data['author'] = {'id': author_id} data['nonce'] = randint(-2**32, (2**32) - 1) data['channel_id'] = channel.id data['reactions'] = [] fake_message = discord.Message(**data) log.info("Running '{0}' in {1.server}/#{1}".format(name, channel)) self.bot.dispatch('message', fake_message)
Example #15
Source File: scheduler.py From Squid-Plugins with MIT License | 6 votes |
def run_coro(self, event): channel = self.bot.get_channel(event.channel) try: server = channel.server prefix = self.bot.settings.get_prefixes(server)[0] except AttributeError: log.debug("Channel no longer found, not running scheduled event.") return data = {} data['timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime()) data['id'] = randint(10**(17), (10**18) - 1) data['content'] = prefix + event.command data['channel'] = self.bot.get_channel(event.channel) data['author'] = {'id': event.author} data['nonce'] = randint(-2**32, (2**32) - 1) data['channel_id'] = event.channel data['reactions'] = [] fake_message = discord.Message(**data) # coro = self.bot.process_commands(fake_message) log.info("Running '{}' in {}".format(event.name, event.server)) # self.bot.loop.create_task(coro) self.bot.dispatch('message', fake_message)
Example #16
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def check_account_age(self, author: discord.Member) -> bool: account_age = self.config.get("account_age") now = datetime.utcnow() try: min_account_age = author.created_at + account_age except ValueError: logger.warning("Error with 'account_age'.", exc_info=True) min_account_age = author.created_at + self.config.remove("account_age") if min_account_age > now: # User account has not reached the required time delta = human_timedelta(min_account_age) logger.debug("Blocked due to account age, user %s.", author.name) if str(author.id) not in self.blocked_users: new_reason = f"System Message: New Account. Required to wait for {delta}." self.blocked_users[str(author.id)] = new_reason return False return True
Example #17
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def check_guild_age(self, author: discord.Member) -> bool: guild_age = self.config.get("guild_age") now = datetime.utcnow() if not hasattr(author, "joined_at"): logger.warning("Not in guild, cannot verify guild_age, %s.", author.name) return True try: min_guild_age = author.joined_at + guild_age except ValueError: logger.warning("Error with 'guild_age'.", exc_info=True) min_guild_age = author.joined_at + self.config.remove("guild_age") if min_guild_age > now: # User has not stayed in the guild for long enough delta = human_timedelta(min_guild_age) logger.debug("Blocked due to guild age, user %s.", author.name) if str(author.id) not in self.blocked_users: new_reason = f"System Message: Recently Joined. Required to wait for {delta}." self.blocked_users[str(author.id)] = new_reason return False return True
Example #18
Source File: chars.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total message char count exceeding the limit sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if msg.author == last_message.author ) total_recent_chars = sum(len(msg.content) for msg in relevant_messages) if total_recent_chars > config['max']: return ( f"sent {total_recent_chars} characters in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #19
Source File: discord_emojis.py From bot with MIT License | 6 votes |
def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total Discord emojis (excluding Unicode emojis) exceeding the limit sent by a single user.""" relevant_messages = tuple( msg for msg in recent_messages if msg.author == last_message.author ) total_emojis = sum( len(DISCORD_EMOJI_RE.findall(msg.content)) for msg in relevant_messages ) if total_emojis > config['max']: return ( f"sent {total_emojis} emojis in {config['interval']}s", (last_message.author,), relevant_messages ) return None
Example #20
Source File: captcha.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def attempt(self, message: discord.Message): data = self.pending.get(message.author.id, {}) now_ts = datetime.now().timestamp() cooldown_left = data.get('sent_at', 0) - (now_ts - self.retry_cooldown) challenge = data.get('challenge') if not data: return elif message.content.lower() == 'retry': if cooldown_left > 0: time_left = _generate_timespec(cooldown_left) await self.cog.bot.send_message(message.channel, warning("%s, wait %s to retry." % (message.author.mention, time_left))) else: data['challenge'] = self.generate_code() await self.send_challenge(message.author, data) self.cog.save() elif message.content == challenge: if message.channel.is_private: await self.cog.bot.send_message(message.channel, okay("Correct!")) else: await self.cog.bot.send_message(message.channel, okay("%s, correct!") % message.author.mention) await self.approve(message.author, delay=2) elif message.content.replace(ZWSP, '') == challenge: if message.channel.is_private: msg = "Enter the code manually instead of copying and pasting, kthx." else: msg = '%s, enter the code manually instead of copying and pasting, kthx.' % message.author.mention await self.cog.bot.send_message(message.channel, warning(msg))
Example #21
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def check_manual_blocked(self, author: discord.Member) -> bool: if str(author.id) not in self.blocked_users: return True blocked_reason = self.blocked_users.get(str(author.id)) or "" now = datetime.utcnow() if blocked_reason.startswith("System Message:"): # Met the limits already, otherwise it would've been caught by the previous checks logger.debug("No longer internally blocked, user %s.", author.name) self.blocked_users.pop(str(author.id)) return True # etc "blah blah blah... until 2019-10-14T21:12:45.559948." end_time = re.search(r"until ([^`]+?)\.$", blocked_reason) if end_time is None: # backwards compat end_time = re.search(r"%([^%]+?)%", blocked_reason) if end_time is not None: logger.warning( r"Deprecated time message for user %s, block and unblock again to update.", author.name, ) if end_time is not None: after = (datetime.fromisoformat(end_time.group(1)) - now).total_seconds() if after <= 0: # No longer blocked self.blocked_users.pop(str(author.id)) logger.debug("No longer blocked, user %s.", author.name) return True logger.debug("User blocked, user %s.", author.name) return False
Example #22
Source File: recensor.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def is_mod_or_superior(self, obj): # Copied from red core mod.py if not isinstance(obj, (Message, discord.Member, discord.Role)): raise TypeError('Only messages, members or roles may be passed') server = obj.server admin_role = self.bot.settings.get_server_admin(server) mod_role = self.bot.settings.get_server_mod(server) if isinstance(obj, discord.Role): return obj.name in [admin_role, mod_role] elif isinstance(obj, Message): user = obj.author elif isinstance(obj, discord.User): user = obj else: return False if user.id == self.bot.settings.owner: return True elif user.id in self.bot.settings.co_owners: return True if hasattr(user, 'roles'): if discord.utils.get(user.roles, name=admin_role): return True elif discord.utils.get(user.roles, name=mod_role): return True return False
Example #23
Source File: serverquotes.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def is_mod_or_superior(self, obj, admin_only=False): if not isinstance(obj, (discord.Message, discord.Member, discord.Role)): raise TypeError('Only messages, members or roles may be passed') server = obj.server admin_role = self.bot.settings.get_server_admin(server).lower() mod_role = self.bot.settings.get_server_mod(server).lower() if isinstance(obj, discord.Role): if admin_only: return obj.name.lower() == admin_role else: return obj.name.lower() in [admin_role, mod_role] elif isinstance(obj, discord.Message): user = obj.author elif isinstance(obj, discord.Member): user = obj else: return False check_roles = {r.name.lower() for r in user.roles} if user.id == self.bot.settings.owner: return True elif user == server.owner: return True elif admin_role in check_roles: return True elif (not admin_only) and mod_role in check_roles: return True return False # Event listeners
Example #24
Source File: listeners.py From predacogs with MIT License | 5 votes |
def on_message(self, message: discord.Message): if message.author.id == self.bot.user.id: self.upsert(rgetattr(message, "guild.id", -1), "msg_sent") if message.guild is None: self.upsert(rgetattr(message, "channel.id", -1), "dms_received") self.upsert( rgetattr(message, "guild.id", rgetattr(message, "channel.id", -1)), "messages_read" )
Example #25
Source File: syncers.py From bot with MIT License | 5 votes |
def _get_confirmation_result( self, diff_size: int, author: Member, message: t.Optional[Message] = None ) -> t.Tuple[bool, t.Optional[Message]]: """ Prompt for confirmation and return a tuple of the result and the prompt message. `diff_size` is the size of the diff of the sync. If it is greater than `bot.constants.Sync.max_diff`, the prompt will be sent. The `author` is the invoked of the sync and the `message` is an extant message to edit to display the prompt. If confirmed or no confirmation was needed, the result is True. The returned message will either be the given `message` or a new one which was created when sending the prompt. """ log.trace(f"Determining if confirmation prompt should be sent for {self.name} syncer.") if diff_size > constants.Sync.max_diff: message = await self._send_prompt(message) if not message: return False, None # Couldn't get channel. confirmed = await self._wait_for_confirmation(author, message) if not confirmed: return False, message # Sync aborted. return True, message
Example #26
Source File: modlog.py From bot with MIT License | 5 votes |
def on_raw_message_delete(self, event: discord.RawMessageDeleteEvent) -> None: """Log raw message delete event to message change log.""" if event.guild_id != GuildConstant.id or event.channel_id in GuildConstant.modlog_blacklist: return await asyncio.sleep(1) # Wait here in case the normal event was fired if event.message_id in self._cached_deletes: # It was in the cache and the normal event was fired, so we can just ignore it self._cached_deletes.remove(event.message_id) return if event.message_id in self._ignored[Event.message_delete]: self._ignored[Event.message_delete].remove(event.message_id) return channel = self.bot.get_channel(event.channel_id) if channel.category: response = ( f"**Channel:** {channel.category}/#{channel.name} (`{channel.id}`)\n" f"**Message ID:** `{event.message_id}`\n" "\n" "This message was not cached, so the message content cannot be displayed." ) else: response = ( f"**Channel:** #{channel.name} (`{channel.id}`)\n" f"**Message ID:** `{event.message_id}`\n" "\n" "This message was not cached, so the message content cannot be displayed." ) await self.send_log_message( Icons.message_delete, Colours.soft_red, "Message deleted", response, channel_id=Channels.message_log )
Example #27
Source File: filtering.py From bot with MIT License | 5 votes |
def on_message_edit(self, before: Message, after: Message) -> None: """ Invoke message filter for message edits. If there have been multiple edits, calculate the time delta from the previous edit. """ if not before.edited_at: delta = relativedelta(after.edited_at, before.created_at).microseconds else: delta = relativedelta(after.edited_at, before.edited_at).microseconds await self._filter_message(after, delta)
Example #28
Source File: filtering.py From bot with MIT License | 5 votes |
def on_message(self, msg: Message) -> None: """Invoke message filter for new messages.""" await self._filter_message(msg) await self.check_bad_words_in_name(msg.author)
Example #29
Source File: watchchannel.py From bot with MIT License | 5 votes |
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 #30
Source File: discord.py From armchair-expert with MIT License | 5 votes |
def filter_content(message: discord.Message): # Replace mentions with names filtered_content = message.content for mention in message.mentions: try: if mention.nick is not None: replace_name = mention.nick else: replace_name = mention.name except AttributeError: replace_name = mention.name replace_id = mention.id replace_tag = "<@%s>" % replace_id filtered_content = filtered_content.replace(replace_tag, replace_name) return filtered_content