A Python wrapper for the Discord API forked from discord.py
—
Comprehensive documentation for nextcord's message handling and communication capabilities.
The core message representation with content, embeds, and attachments.
import nextcord
from nextcord import Message, Embed, File
class Message:
"""Represents a message from Discord.
Attributes
----------
id: int
The message ID.
content: str
The actual contents of the message.
author: Union[Member, User]
The user or member who sent the message.
channel: Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable]
The channel the message was sent in.
guild: Optional[Guild]
The guild that the message belongs to, if applicable.
embeds: List[Embed]
A list of embeds the message has.
attachments: List[Attachment]
A list of attachments given to a message.
reactions: List[Reaction]
Reactions to a message.
reference: Optional[MessageReference]
The message that this message references (for replies).
mention_everyone: bool
Specifies if the message mentions everyone.
mentions: List[Union[User, Member]]
A list of users that were mentioned.
channel_mentions: List[GuildChannel]
A list of channels that were mentioned.
role_mentions: List[Role]
A list of roles that were mentioned.
pinned: bool
Specifies if the message is currently pinned.
tts: bool
Specifies if the message was done with text-to-speech.
type: MessageType
The type of message.
flags: MessageFlags
Extra features of the message.
created_at: datetime.datetime
The message's creation time in UTC.
edited_at: Optional[datetime.datetime]
The message's last edit time in UTC, if edited.
jump_url: str
Returns a URL that allows the client to jump to this message.
"""
# Message properties
@property
def clean_content(self) -> str:
"""str: A property that returns the content in a "cleaned up" manner.
This transforms mentions into the way the client shows it.
e.g. <#id> will transform into #name.
"""
...
@property
def system_content(self) -> str:
"""str: A property that returns the content that is rendered
regardless of the Message.type.
"""
...
@property
def raw_mentions(self) -> List[int]:
"""List[int]: A property that returns an array of user IDs matched
with the syntax of <@user_id> in the message content.
"""
...
@property
def raw_channel_mentions(self) -> List[int]:
"""List[int]: A property that returns an array of channel IDs matched
with the syntax of <#channel_id> in the message content.
"""
...
@property
def raw_role_mentions(self) -> List[int]:
"""List[int]: A property that returns an array of role IDs matched
with the syntax of <@&role_id> in the message content.
"""
...
def is_system(self) -> bool:
"""bool: Whether the message is a system message."""
...
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a MessageReference from the current message.
Parameters
----------
fail_if_not_exists: bool
Whether replying using the message reference should raise HTTPException
if the message no longer exists.
"""
...Sending messages with various content types through the Messageable interface.
from typing import Optional, List, Sequence, Union
from nextcord import (
Embed, File, AllowedMentions, MessageReference, MessageFlags,
GuildSticker, StickerItem, View
)
from nextcord.abc import Messageable
class Messageable:
"""An ABC that details the common operations on a model that can send messages."""
async def send(
self,
content: Optional[str] = None,
*,
tts: bool = False,
embed: Optional[Embed] = None,
embeds: Optional[List[Embed]] = None,
file: Optional[File] = None,
files: Optional[List[File]] = None,
stickers: Optional[Sequence[Union[GuildSticker, StickerItem]]] = None,
delete_after: Optional[float] = None,
nonce: Optional[Union[str, int]] = None,
allowed_mentions: Optional[AllowedMentions] = None,
reference: Optional[Union[Message, MessageReference, PartialMessage]] = None,
mention_author: Optional[bool] = None,
view: Optional[View] = None,
flags: Optional[MessageFlags] = None,
suppress_embeds: Optional[bool] = None,
) -> Message:
"""Sends a message to the destination.
Parameters
----------
content: Optional[str]
The content of the message to send.
tts: bool
Indicates if the message should be sent using text-to-speech.
embed: Optional[Embed]
The rich embed for the content.
embeds: Optional[List[Embed]]
A list of embeds to send with the content. Maximum of 10.
file: Optional[File]
The file to upload.
files: Optional[List[File]]
A list of files to upload. Must be a maximum of 10.
stickers: Optional[Sequence[Union[GuildSticker, StickerItem]]]
A list of stickers to send with the message. Maximum of 3.
delete_after: Optional[float]
If provided, the number of seconds to wait before deleting the message.
nonce: Optional[Union[str, int]]
The nonce to use for sending this message.
allowed_mentions: Optional[AllowedMentions]
Controls the mentions being processed in this message.
reference: Optional[Union[Message, MessageReference, PartialMessage]]
A reference to the Message to which you are replying.
mention_author: Optional[bool]
If set, overrides the mention_author setting of reference.
view: Optional[View]
A UI view to add to the message.
flags: Optional[MessageFlags]
The flags to set for this message.
suppress_embeds: Optional[bool]
Whether to suppress embeds for the message.
Returns
-------
Message
The message that was sent.
"""
...
def typing(self) -> Typing:
"""Returns a context manager that allows you to send a typing indicator.
Example
-------
async with channel.typing():
# do expensive stuff here
await channel.send('done!')
"""
...
# Usage Examples
async def send_basic_message(channel):
"""Send a simple text message."""
await channel.send("Hello, world!")
async def send_message_with_embed(channel):
"""Send a message with an embed."""
embed = nextcord.Embed(title="My Embed", description="This is an embed!")
await channel.send("Check out this embed:", embed=embed)
async def send_message_with_file(channel):
"""Send a message with a file attachment."""
with open('image.png', 'rb') as f:
await channel.send("Here's an image:", file=nextcord.File(f, 'image.png'))
async def send_reply(message):
"""Reply to a message."""
await message.reply("This is a reply!")Modifying existing messages after they've been sent.
class Message:
async def edit(
self,
*,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: Optional[List[Embed]] = MISSING,
attachments: Optional[List[Attachment]] = MISSING,
suppress: Optional[bool] = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""Edits the message.
Parameters
----------
content: Optional[str]
The new content to replace the message with. Could be None to remove content.
embed: Optional[Embed]
The new embed to replace the original with. Could be None to remove embed.
embeds: Optional[List[Embed]]
The new embeds to replace the original with. Maximum of 10.
attachments: Optional[List[Attachment]]
A list of attachments to keep in the message.
suppress: Optional[bool]
Whether to suppress embeds for the message.
delete_after: Optional[float]
If provided, the number of seconds to wait before deleting the message.
allowed_mentions: Optional[AllowedMentions]
Controls the mentions being processed in this message.
view: Optional[View]
The updated view to update this message with.
file: Optional[File]
If provided, a new file to add to the message.
files: Optional[List[File]]
If provided, a list of new files to add to the message.
Returns
-------
Message
The edited message.
"""
...
async def delete(self, *, delay: Optional[float] = None) -> None:
"""Deletes the message.
Parameters
----------
delay: Optional[float]
If provided, the number of seconds to wait before deleting the message.
"""
...
class PartialMessage:
async def edit(self, **fields) -> Optional[Message]:
"""Edits the partial message.
Same parameters as Message.edit().
"""
...
# Usage Examples
async def edit_message_content(message):
"""Edit a message's content."""
await message.edit(content="This message has been edited!")
async def edit_message_embed(message):
"""Edit a message's embed."""
new_embed = nextcord.Embed(title="Updated", description="This embed was updated!")
await message.edit(embed=new_embed)
async def suppress_message_embeds(message):
"""Suppress embeds in a message."""
await message.edit(suppress=True)Rich message formatting with fields, images, and styling.
from nextcord import Embed, Colour
from datetime import datetime
from typing import Optional, Any, List
class Embed:
"""Represents a Discord embed.
Attributes
----------
title: Optional[str]
The title of the embed.
type: str
The type of embed. Usually "rich".
description: Optional[str]
The description of the embed.
url: Optional[str]
The hyperlink of the embed title.
timestamp: Optional[datetime.datetime]
The timestamp of the embed content.
colour: Optional[Colour]
The colour code of the embed. Aliased to color.
"""
def __init__(
self,
*,
colour: Optional[Union[int, Colour]] = None,
color: Optional[Union[int, Colour]] = None,
title: Optional[Any] = None,
type: str = "rich",
url: Optional[Any] = None,
description: Optional[Any] = None,
timestamp: Optional[datetime.datetime] = None,
):
"""Creates an embed object.
Parameters
----------
colour: Optional[Union[int, Colour]]
The colour code of the embed.
color: Optional[Union[int, Colour]]
Alias for colour.
title: Optional[str]
The title of the embed.
type: str
The type of embed. Defaults to "rich".
url: Optional[str]
The hyperlink of the embed title.
description: Optional[str]
The description of the embed.
timestamp: Optional[datetime.datetime]
The timestamp of the embed content.
"""
...
# Author methods
def set_author(
self,
*,
name: str,
url: Optional[str] = None,
icon_url: Optional[str] = None,
) -> Self:
"""Sets the author for the embed content.
Parameters
----------
name: str
The name of the author.
url: Optional[str]
The URL for the author.
icon_url: Optional[str]
The URL of the author icon.
"""
...
def remove_author(self) -> Self:
"""Clears embed's author information."""
...
# Footer methods
def set_footer(
self,
*,
text: Optional[str] = None,
icon_url: Optional[str] = None
) -> Self:
"""Sets the footer for the embed content.
Parameters
----------
text: Optional[str]
The footer text.
icon_url: Optional[str]
The URL of the footer icon.
"""
...
def remove_footer(self) -> Self:
"""Clears embed's footer information."""
...
# Image methods
def set_image(self, url: Optional[str]) -> Self:
"""Sets the image for the embed content.
Parameters
----------
url: Optional[str]
The source URL for the image. Pass None to remove.
"""
...
def set_thumbnail(self, url: Optional[str]) -> Self:
"""Sets the thumbnail for the embed content.
Parameters
----------
url: Optional[str]
The source URL for the thumbnail. Pass None to remove.
"""
...
# Field methods
def add_field(
self,
*,
name: str,
value: str,
inline: bool = True
) -> Self:
"""Adds a field to the embed object.
Parameters
----------
name: str
The name of the field.
value: str
The value of the field.
inline: bool
Whether the field should be displayed inline.
"""
...
def insert_field_at(
self,
index: int,
*,
name: str,
value: str,
inline: bool = True
) -> Self:
"""Inserts a field at a specified index.
Parameters
----------
index: int
The index of where to insert the field.
name: str
The name of the field.
value: str
The value of the field.
inline: bool
Whether the field should be displayed inline.
"""
...
def set_field_at(
self,
index: int,
*,
name: str,
value: str,
inline: bool = True
) -> Self:
"""Modifies a field at the specified index.
Parameters
----------
index: int
The index of the field to modify.
name: str
The name of the field.
value: str
The value of the field.
inline: bool
Whether the field should be displayed inline.
"""
...
def remove_field(self, index: int) -> Self:
"""Removes a field at a specified index.
Parameters
----------
index: int
The index of the field to remove.
"""
...
def clear_fields(self) -> Self:
"""Removes all fields from this embed."""
...
# Properties
@property
def fields(self) -> List[EmbedFieldProxy]:
"""List[EmbedFieldProxy]: Returns a list of EmbedProxy denoting the field contents."""
...
@property
def footer(self) -> EmbedFooterProxy:
"""EmbedFooterProxy: Returns an EmbedProxy denoting the footer contents."""
...
@property
def image(self) -> EmbedMediaProxy:
"""EmbedMediaProxy: Returns an EmbedProxy denoting the image contents."""
...
@property
def thumbnail(self) -> EmbedMediaProxy:
"""EmbedMediaProxy: Returns an EmbedProxy denoting the thumbnail contents."""
...
@property
def author(self) -> EmbedAuthorProxy:
"""EmbedAuthorProxy: Returns an EmbedProxy denoting the author contents."""
...
# Utility methods
def copy(self) -> Self:
"""Returns a shallow copy of the embed."""
...
def to_dict(self) -> EmbedData:
"""Converts this embed object into a dict."""
...
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Self:
"""Converts a dict to an Embed."""
...
# Usage Examples
def create_basic_embed():
"""Create a basic embed."""
embed = nextcord.Embed(
title="My Embed Title",
description="This is the embed description.",
color=0x00ff00 # Green color
)
return embed
def create_rich_embed():
"""Create a rich embed with multiple elements."""
embed = nextcord.Embed(
title="Rich Embed",
description="A comprehensive embed example.",
color=nextcord.Colour.blue(),
timestamp=datetime.utcnow()
)
embed.set_author(
name="Author Name",
url="https://example.com",
icon_url="https://example.com/icon.png"
)
embed.set_thumbnail(url="https://example.com/thumbnail.png")
embed.set_image(url="https://example.com/image.png")
embed.add_field(name="Field 1", value="Value 1", inline=True)
embed.add_field(name="Field 2", value="Value 2", inline=True)
embed.add_field(name="Long Field", value="This field spans the full width", inline=False)
embed.set_footer(
text="Footer text",
icon_url="https://example.com/footer_icon.png"
)
return embedFile handling and attachment management.
from nextcord import Attachment, File
from typing import Optional, Union
import io
from os import PathLike
class Attachment:
"""Represents an attachment from Discord.
Attributes
----------
id: int
The attachment ID.
size: int
The attachment size in bytes.
height: Optional[int]
The attachment's height, in pixels (images/videos only).
width: Optional[int]
The attachment's width, in pixels (images/videos only).
filename: str
The attachment's filename.
url: str
The attachment URL.
proxy_url: str
The proxy URL (cached version).
content_type: Optional[str]
The attachment's media type.
description: Optional[str]
The attachment's description.
"""
def is_spoiler(self) -> bool:
"""bool: Whether this attachment contains a spoiler."""
...
async def save(
self,
fp: Union[io.BufferedIOBase, PathLike, str],
*,
seek_begin: bool = True,
use_cached: bool = False,
) -> int:
"""Saves this attachment into a file-like object.
Parameters
----------
fp: Union[io.BufferedIOBase, PathLike, str]
The file-like object to save to or filename.
seek_begin: bool
Whether to seek to the beginning after saving.
use_cached: bool
Whether to use proxy_url rather than url.
Returns
-------
int
The number of bytes written.
"""
...
async def read(self, *, use_cached: bool = False) -> bytes:
"""Retrieves the content of this attachment as bytes.
Parameters
----------
use_cached: bool
Whether to use proxy_url rather than url.
Returns
-------
bytes
The contents of the attachment.
"""
...
async def to_file(
self,
*,
filename: Optional[str] = None,
description: Optional[str] = None,
use_cached: bool = False,
spoiler: bool = False,
force_close: bool = True,
) -> File:
"""Converts the attachment into a File suitable for sending.
Parameters
----------
filename: Optional[str]
The filename to use. If not specified, uses attachment filename.
description: Optional[str]
The description to use. If not specified, uses attachment description.
use_cached: bool
Whether to use proxy_url rather than url.
spoiler: bool
Whether the file is a spoiler.
force_close: bool
Whether to forcibly close the bytes when .close() is called.
Returns
-------
File
The attachment as a file suitable for sending.
"""
...
class File:
"""A parameter object used for sending file objects.
Attributes
----------
fp: Union[io.BufferedReader, io.BufferedIOBase]
A file-like object opened in binary mode and read mode.
filename: Optional[str]
The filename to display when uploading to Discord.
description: Optional[str]
The description for the file.
spoiler: bool
Whether the attachment is a spoiler.
force_close: bool
Whether to forcibly close the bytes when .close() is called.
"""
def __init__(
self,
fp: Union[str, bytes, PathLike, io.BufferedIOBase],
filename: Optional[str] = None,
*,
description: Optional[str] = None,
spoiler: bool = False,
force_close: Optional[bool] = None,
):
"""Creates a File object.
Parameters
----------
fp: Union[str, bytes, PathLike, io.BufferedIOBase]
A file-like object opened in binary mode or a filename.
filename: Optional[str]
The filename to display when uploading to Discord.
description: Optional[str]
The description for the file.
spoiler: bool
Whether the attachment is a spoiler.
force_close: Optional[bool]
Whether to forcibly close the bytes when .close() is called.
"""
...
def reset(self, *, seek: Union[int, bool] = True) -> None:
"""Reset the file position."""
...
def close(self) -> None:
"""Close the file."""
...
# Usage Examples
async def download_attachment(attachment):
"""Download an attachment to local file."""
await attachment.save(f"./downloads/{attachment.filename}")
async def read_attachment_content(attachment):
"""Read attachment content into memory."""
content = await attachment.read()
return content
async def resend_attachment(attachment, channel):
"""Convert attachment to file and resend."""
file = await attachment.to_file()
await channel.send("Reposting this file:", file=file)
def create_file_from_path():
"""Create a File from a local path."""
return nextcord.File("./image.png", description="My image")
def create_file_from_bytes():
"""Create a File from bytes in memory."""
data = b"Hello, world!"
return nextcord.File(io.BytesIO(data), filename="hello.txt")Adding, removing, and managing message reactions.
from nextcord import Reaction, Emoji, PartialEmoji
from nextcord.abc import Snowflake
from typing import Union, Optional
EmojiInputType = Union[Emoji, PartialEmoji, str]
class Message:
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""Add a reaction to the message.
Parameters
----------
emoji: Union[Emoji, Reaction, PartialEmoji, str]
The emoji to react with.
"""
...
async def remove_reaction(
self,
emoji: Union[EmojiInputType, Reaction],
member: Snowflake
) -> None:
"""Remove a reaction by the member from the message.
Parameters
----------
emoji: Union[Emoji, Reaction, PartialEmoji, str]
The emoji to remove.
member: Snowflake
The member for which to remove the reaction.
"""
...
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""Clears a specific reaction from the message.
Parameters
----------
emoji: Union[Emoji, Reaction, PartialEmoji, str]
The emoji to clear.
"""
...
async def clear_reactions(self) -> None:
"""Removes all the reactions from the message."""
...
class Reaction:
"""Represents a reaction to a message.
Attributes
----------
emoji: Union[Emoji, PartialEmoji, str]
The reaction emoji. May be a custom emoji, or a unicode emoji.
count: int
Number of times this reaction was made.
me: bool
If the user sent this reaction.
message: Message
Message this reaction is for.
"""
def is_custom_emoji(self) -> bool:
"""bool: If this is a custom emoji."""
...
async def remove(self, user: Snowflake) -> None:
"""Remove the reaction by the provided User from the message.
Parameters
----------
user: Snowflake
The user from which to remove the reaction.
"""
...
async def clear(self) -> None:
"""Clears this reaction from the message."""
...
def users(
self,
*,
limit: Optional[int] = None,
after: Optional[Snowflake] = None
) -> ReactionIterator:
"""Returns an AsyncIterator representing the users that have reacted.
Parameters
----------
limit: Optional[int]
The maximum number of results to return.
after: Optional[Snowflake]
For pagination, reactions are sorted by member.
Yields
------
Union[User, Member]
The users that have reacted to this message.
"""
...
# Usage Examples
async def add_reactions(message):
"""Add multiple reactions to a message."""
await message.add_reaction("👍")
await message.add_reaction("👎")
await message.add_reaction("❤️")
async def remove_user_reaction(message, user):
"""Remove a specific user's reaction."""
await message.remove_reaction("👍", user)
async def clear_specific_reaction(message):
"""Clear all instances of a specific reaction."""
await message.clear_reaction("👍")
async def clear_all_reactions(message):
"""Remove all reactions from a message."""
await message.clear_reactions()
async def get_reaction_users(message):
"""Get users who reacted with thumbs up."""
for reaction in message.reactions:
if str(reaction.emoji) == "👍":
async for user in reaction.users():
print(f"{user.name} reacted with 👍")Replies, message references, and threading.
from nextcord import MessageReference, Message, PartialMessage
from typing import Optional, Union
class MessageReference:
"""Represents a reference to a Message.
Attributes
----------
message_id: Optional[int]
The id of the message referenced.
channel_id: int
The channel id of the message referenced.
guild_id: Optional[int]
The guild id of the message referenced.
fail_if_not_exists: bool
Whether replying should raise HTTPException if message no longer exists.
resolved: Optional[Union[Message, DeletedReferencedMessage]]
The message that this reference resolved to.
"""
def __init__(
self,
*,
message_id: int,
channel_id: int,
guild_id: Optional[int] = None,
fail_if_not_exists: bool = True,
):
"""Creates a MessageReference.
Parameters
----------
message_id: int
The id of the message to reference.
channel_id: int
The channel id of the message to reference.
guild_id: Optional[int]
The guild id of the message to reference.
fail_if_not_exists: bool
Whether to raise an exception if the message doesn't exist.
"""
...
@classmethod
def from_message(
cls,
message: Message,
*,
fail_if_not_exists: bool = True
) -> MessageReference:
"""Creates a MessageReference from an existing Message.
Parameters
----------
message: Message
The message to be converted into a reference.
fail_if_not_exists: bool
Whether replying should raise HTTPException if message no longer exists.
Returns
-------
MessageReference
A reference to the message.
"""
...
@property
def cached_message(self) -> Optional[Message]:
"""Optional[Message]: The cached message, if found in the internal message cache."""
...
@property
def jump_url(self) -> str:
"""str: Returns a URL that allows the client to jump to the referenced message."""
...
class Message:
async def reply(
self,
content: Optional[str] = None,
**kwargs
) -> Message:
"""A shortcut method to reply to the Message.
This is equivalent to:
await message.channel.send(content, reference=message, **kwargs)
Parameters
----------
content: Optional[str]
The content of the message to send.
**kwargs
Keyword arguments to pass to send().
Returns
-------
Message
The message that was sent.
"""
...
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a MessageReference from the current message.
Parameters
----------
fail_if_not_exists: bool
Whether replying using the message reference should raise HTTPException.
Returns
-------
MessageReference
The reference to this message.
"""
...
# Usage Examples
async def reply_to_message(message):
"""Reply to a message."""
await message.reply("This is a reply to your message!")
async def reply_without_mention(message):
"""Reply without mentioning the author."""
await message.reply("This won't mention you!", mention_author=False)
async def create_manual_reference(channel, message_id):
"""Create a manual message reference."""
reference = nextcord.MessageReference(
message_id=message_id,
channel_id=channel.id,
guild_id=channel.guild.id if channel.guild else None
)
await channel.send("Replying to an older message", reference=reference)
async def reply_with_embed(message):
"""Reply with an embed."""
embed = nextcord.Embed(title="Reply", description="This is a reply with an embed!")
await message.reply(embed=embed)Uploading files and images to Discord.
from nextcord import File
import io
from typing import Optional, List, Union
from os import PathLike
# File Creation Methods
def create_file_from_path(path: str, *, spoiler: bool = False) -> File:
"""Create a File from a local file path."""
return File(path, spoiler=spoiler)
def create_file_from_bytes(
data: bytes,
filename: str,
*,
spoiler: bool = False
) -> File:
"""Create a File from bytes in memory."""
return File(io.BytesIO(data), filename=filename, spoiler=spoiler)
def create_spoiler_file(path: str) -> File:
"""Create a spoiler file (prefixes filename with SPOILER_)."""
return File(path, spoiler=True)
# Sending Files
async def send_single_file(channel):
"""Send a single file."""
file = nextcord.File("./image.png", description="An example image")
await channel.send("Here's an image:", file=file)
async def send_multiple_files(channel):
"""Send multiple files at once."""
files = [
nextcord.File("./image1.png"),
nextcord.File("./image2.png"),
nextcord.File("./document.pdf")
]
await channel.send("Multiple files:", files=files)
async def send_file_with_embed(channel):
"""Send a file along with an embed."""
file = nextcord.File("./data.json")
embed = nextcord.Embed(title="Data File", description="JSON data export")
await channel.send(embed=embed, file=file)
# Dynamic File Creation
async def send_text_file(channel, content: str, filename: str):
"""Create and send a text file from string content."""
file_data = content.encode('utf-8')
file = nextcord.File(io.BytesIO(file_data), filename=filename)
await channel.send("Generated file:", file=file)
async def send_json_data(channel, data: dict):
"""Send JSON data as a file."""
import json
json_str = json.dumps(data, indent=2)
json_bytes = json_str.encode('utf-8')
file = nextcord.File(io.BytesIO(json_bytes), filename="data.json")
await channel.send("JSON data export:", file=file)
# File Context Manager Usage
async def send_with_context_manager(channel):
"""Use File as a context manager for automatic cleanup."""
with nextcord.File("./large_file.zip") as file:
await channel.send("Large file upload:", file=file)
# File is automatically closed after sendingButtons and select menus within messages.
from nextcord import ButtonStyle, ComponentType
from nextcord.ui import Button, Select, View
from typing import List, Optional
class Button:
"""Represents a button component.
Attributes
----------
style: ButtonStyle
The style of the button.
custom_id: Optional[str]
The ID of the button that gets received during an interaction.
url: Optional[str]
The URL this button sends you to.
disabled: bool
Whether the button is disabled or not.
label: Optional[str]
The label of the button, if any.
emoji: Optional[PartialEmoji]
The emoji of the button, if available.
"""
pass
class StringSelectMenu:
"""Represents a string select menu component.
Attributes
----------
custom_id: str
The ID of the select menu.
placeholder: Optional[str]
The placeholder text that is shown if nothing is selected.
min_values: int
The minimum number of items that must be chosen.
max_values: int
The maximum number of items that must be chosen.
options: List[SelectOption]
A list of options that can be selected.
disabled: bool
Whether the select is disabled or not.
"""
pass
class SelectOption:
"""Represents an option in a select menu.
Attributes
----------
label: str
The user-facing name of the option.
value: str
The dev-defined value of the option.
description: Optional[str]
An additional description of the option.
emoji: Optional[PartialEmoji]
An emoji that appears on the option.
default: bool
Whether this option is selected by default.
"""
pass
# Usage with Views
from nextcord.ui import View, Button, Select
class MyView(View):
def __init__(self):
super().__init__()
@nextcord.ui.button(label='Click me!', style=nextcord.ButtonStyle.primary)
async def button_callback(self, button: Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Button was clicked!', ephemeral=True)
@nextcord.ui.select(
placeholder='Choose an option...',
options=[
nextcord.SelectOption(label='Option 1', value='1'),
nextcord.SelectOption(label='Option 2', value='2'),
nextcord.SelectOption(label='Option 3', value='3'),
]
)
async def select_callback(self, select: Select, interaction: nextcord.Interaction):
await interaction.response.send_message(f'You chose {select.values[0]}!', ephemeral=True)
# Sending Messages with Components
async def send_message_with_components(channel):
"""Send a message with interactive components."""
view = MyView()
await channel.send("This message has components:", view=view)
async def send_button_message(channel):
"""Send a message with just buttons."""
class ButtonView(View):
@nextcord.ui.button(label='Primary', style=nextcord.ButtonStyle.primary)
async def primary_button(self, button: Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Primary button clicked!', ephemeral=True)
@nextcord.ui.button(label='Secondary', style=nextcord.ButtonStyle.secondary)
async def secondary_button(self, button: Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Secondary button clicked!', ephemeral=True)
@nextcord.ui.button(label='Danger', style=nextcord.ButtonStyle.danger)
async def danger_button(self, button: Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Danger button clicked!', ephemeral=True)
view = ButtonView()
await channel.send("Choose an action:", view=view)
async def send_select_message(channel):
"""Send a message with a select menu."""
class SelectView(View):
@nextcord.ui.select(
placeholder='Pick your favorite color...',
options=[
nextcord.SelectOption(label='Red', value='red', emoji='🔴'),
nextcord.SelectOption(label='Blue', value='blue', emoji='🔵'),
nextcord.SelectOption(label='Green', value='green', emoji='🟢'),
]
)
async def color_select(self, select: Select, interaction: nextcord.Interaction):
color = select.values[0]
await interaction.response.send_message(f'You picked {color}!', ephemeral=True)
view = SelectView()
await channel.send("What's your favorite color?", view=view)Message properties and metadata.
from nextcord.flags import MessageFlags
class MessageFlags:
"""Wraps up a Discord Message flag value.
Attributes
----------
value: int
The raw value. This is a bit array field representing available flags.
"""
@property
def crossposted(self) -> bool:
"""bool: Returns True if the message is the original crossposted message."""
...
@property
def is_crossposted(self) -> bool:
"""bool: Returns True if the message was crossposted from another channel."""
...
@property
def suppress_embeds(self) -> bool:
"""bool: Returns True if the message's embeds have been suppressed."""
...
@property
def source_message_deleted(self) -> bool:
"""bool: Returns True if the source message for this crosspost has been deleted."""
...
@property
def urgent(self) -> bool:
"""bool: Returns True if the message is an urgent message."""
...
@property
def has_thread(self) -> bool:
"""bool: Returns True if the message has an associated thread."""
...
@property
def ephemeral(self) -> bool:
"""bool: Returns True if the message is ephemeral."""
...
@property
def loading(self) -> bool:
"""bool: Returns True if the message is a loading state."""
...
@property
def failed_to_mention_some_roles_in_thread(self) -> bool:
"""bool: Returns True if the message failed to mention some roles in thread."""
...
# Usage Examples
def check_message_flags(message):
"""Check various message flags."""
if message.flags.crossposted:
print("This message was crossposted from another channel")
if message.flags.suppress_embeds:
print("This message has suppressed embeds")
if message.flags.has_thread:
print("This message has a thread")
if message.flags.ephemeral:
print("This message is ephemeral")
async def suppress_message_embeds(message):
"""Suppress embeds in a message by editing it."""
await message.edit(suppress=True)
async def send_message_with_flags(channel):
"""Send a message with specific flags."""
flags = nextcord.MessageFlags()
flags.suppress_embeds = True
await channel.send("This message will have suppressed embeds", flags=flags)
# Working with announcement channels
async def publish_announcement(message):
"""Publish a message in an announcement channel."""
if message.channel.type == nextcord.ChannelType.news:
await message.publish()
print("Message published to followers")Comprehensive examples combining multiple message features.
import nextcord
from nextcord.ext import commands
from datetime import datetime
import io
class MessageExamples:
"""Complete examples of message functionality."""
@staticmethod
async def comprehensive_message_example(channel):
"""Send a comprehensive message with multiple features."""
# Create a rich embed
embed = nextcord.Embed(
title="📋 Status Report",
description="Daily server statistics and information.",
color=nextcord.Colour.blue(),
timestamp=datetime.utcnow()
)
embed.set_author(
name="Server Bot",
icon_url="https://example.com/bot_avatar.png"
)
embed.add_field(name="👥 Members", value="1,234", inline=True)
embed.add_field(name="📱 Online", value="456", inline=True)
embed.add_field(name="🎯 Active", value="89", inline=True)
embed.add_field(
name="📊 Today's Activity",
value="• 50 messages sent\n• 12 new members\n• 5 events created",
inline=False
)
embed.set_thumbnail(url="https://example.com/server_icon.png")
embed.set_footer(text="Last updated", icon_url="https://example.com/clock.png")
# Create a file attachment
report_data = {
"date": datetime.utcnow().isoformat(),
"members": 1234,
"messages": 50,
"events": 5
}
import json
json_data = json.dumps(report_data, indent=2).encode('utf-8')
file = nextcord.File(io.BytesIO(json_data), filename="daily_report.json")
# Create interactive components
class ReportView(nextcord.ui.View):
@nextcord.ui.button(label="📈 Detailed Stats", style=nextcord.ButtonStyle.primary)
async def detailed_stats(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Fetching detailed statistics...", ephemeral=True)
@nextcord.ui.button(label="🔄 Refresh", style=nextcord.ButtonStyle.secondary)
async def refresh(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Report refreshed!", ephemeral=True)
@nextcord.ui.select(
placeholder="Choose a time period...",
options=[
nextcord.SelectOption(label="Last 24 hours", value="24h", emoji="🕐"),
nextcord.SelectOption(label="Last 7 days", value="7d", emoji="📅"),
nextcord.SelectOption(label="Last 30 days", value="30d", emoji="📊"),
]
)
async def time_period(self, select: nextcord.ui.Select, interaction: nextcord.Interaction):
period = select.values[0]
await interaction.response.send_message(f"Showing data for: {period}", ephemeral=True)
# Send the comprehensive message
view = ReportView()
message = await channel.send(
content="**📋 Daily Server Report**\nHere's your server's daily activity summary:",
embed=embed,
file=file,
view=view
)
# Add some reactions
await message.add_reaction("👍")
await message.add_reaction("📊")
await message.add_reaction("🔔")
return message
@staticmethod
async def conversation_flow_example(channel):
"""Example of a conversation flow with replies and references."""
# Initial message
initial_message = await channel.send(
"🎮 **Game Night Planning**\n"
"Who's interested in game night this Friday? React below!"
)
await initial_message.add_reaction("✅") # Yes
await initial_message.add_reaction("❌") # No
await initial_message.add_reaction("🤔") # Maybe
# Follow-up with embed
embed = nextcord.Embed(
title="🎯 Game Options",
description="Vote for which games you'd like to play!",
color=nextcord.Colour.green()
)
embed.add_field(name="🎲 Board Games", value="Monopoly, Risk, Settlers", inline=False)
embed.add_field(name="🎮 Video Games", value="Among Us, Jackbox, Fall Guys", inline=False)
embed.add_field(name="🃏 Card Games", value="Uno, Poker, Cards Against Humanity", inline=False)
games_message = await initial_message.reply(
embed=embed,
mention_author=False # Don't ping everyone
)
# Create a poll with reactions
game_emojis = ["🎲", "🎮", "🃏"]
for emoji in game_emojis:
await games_message.add_reaction(emoji)
return initial_message, games_message
@staticmethod
async def file_sharing_example(channel):
"""Example of various file sharing scenarios."""
# Text file from string
content = """
# Meeting Notes - 2024-01-15
## Attendees
- Alice
- Bob
- Charlie
## Topics Discussed
1. Project timeline
2. Budget allocation
3. Next steps
## Action Items
- [ ] Alice: Update project plan
- [ ] Bob: Review budget
- [ ] Charlie: Schedule follow-up
"""
notes_file = nextcord.File(
io.BytesIO(content.encode('utf-8')),
filename="meeting_notes.md",
description="Meeting notes from today's discussion"
)
# Image with spoiler
# Assuming we have an image file
spoiler_image = nextcord.File("./spoiler_image.png", spoiler=True)
# Multiple files
files = [notes_file, spoiler_image]
embed = nextcord.Embed(
title="📁 File Share",
description="Meeting notes and images from today's session",
color=nextcord.Colour.purple()
)
await channel.send(
"📋 **Files from today's meeting:**",
embed=embed,
files=files
)
@staticmethod
async def error_handling_example(channel):
"""Example with proper error handling for message operations."""
try:
# Attempt to send a message with potential issues
embed = nextcord.Embed(title="Test Embed")
message = await channel.send(embed=embed)
# Try to edit the message
await message.edit(content="Updated content")
# Try to add reactions
await message.add_reaction("✅")
# Try to reply
reply = await message.reply("Operation successful!")
# Schedule deletion
await reply.delete(delay=10.0)
except nextcord.Forbidden:
print("Missing permissions for this operation")
except nextcord.HTTPException as e:
print(f"HTTP error occurred: {e}")
except nextcord.NotFound:
print("Message or channel not found")
except Exception as e:
print(f"Unexpected error: {e}")
# Bot command examples using nextcord.ext.commands
class MessageCommands(commands.Cog):
"""Command examples for message functionality."""
@commands.command()
async def embed_info(self, ctx, *, title: str):
"""Create an embed with user input."""
embed = nextcord.Embed(
title=title,
description=f"Created by {ctx.author.mention}",
color=nextcord.Colour.random(),
timestamp=datetime.utcnow()
)
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)
@commands.command()
async def quote(self, ctx, message_id: int):
"""Quote a message by ID."""
try:
message = await ctx.fetch_message(message_id)
embed = nextcord.Embed(
description=message.content,
timestamp=message.created_at,
color=nextcord.Colour.blue()
)
embed.set_author(
name=message.author.display_name,
icon_url=message.author.avatar.url
)
embed.set_footer(text=f"Originally sent in #{message.channel.name}")
await ctx.send(f"💬 **Quote from {message.author.mention}:**", embed=embed)
except nextcord.NotFound:
await ctx.send("❌ Message not found!")
except nextcord.Forbidden:
await ctx.send("❌ I don't have permission to read that message!")
@commands.command()
async def poll(self, ctx, question: str, *options):
"""Create a poll with reactions."""
if len(options) < 2:
await ctx.send("❌ Please provide at least 2 options!")
return
if len(options) > 10:
await ctx.send("❌ Maximum 10 options allowed!")
return
embed = nextcord.Embed(
title="📊 Poll",
description=question,
color=nextcord.Colour.blue()
)
reactions = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
for i, option in enumerate(options):
embed.add_field(
name=f"{reactions[i]} Option {i+1}",
value=option,
inline=False
)
message = await ctx.send(embed=embed)
for i in range(len(options)):
await message.add_reaction(reactions[i])This comprehensive documentation covers all the major aspects of nextcord's message and communication capabilities, including practical examples and proper error handling. The documentation follows the Knowledge Tile format with API blocks and complete type definitions, making it a valuable reference for developers working with nextcord.
Install with Tessl CLI
npx tessl i tessl/pypi-nextcord