HTTP client
This file handles the interaction with discords http endpoints.
class
GlobalLock
¶
Manages the global ratelimit
Source code in naff/api/http/http_client.py
class GlobalLock:
"""Manages the global ratelimit"""
def __init__(self) -> None:
self.cooldown_system: CooldownSystem = CooldownSystem(
45, 1
) # global rate-limit is 50 per second, conservatively we use 45
self._lock: asyncio.Lock = asyncio.Lock()
async def rate_limit(self) -> None:
async with self._lock:
while not self.cooldown_system.acquire_token():
await asyncio.sleep(self.cooldown_system.get_cooldown_time())
async def lock(self, delta: float) -> None:
"""
Lock the global lock for a given duration.
Args:
delta: The time to keep the lock acquired
"""
await self._lock.acquire()
await asyncio.sleep(delta)
self._lock.release()
async
method
lock(self, delta)
¶
Lock the global lock for a given duration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
delta |
float |
The time to keep the lock acquired |
required |
Source code in naff/api/http/http_client.py
async def lock(self, delta: float) -> None:
"""
Lock the global lock for a given duration.
Args:
delta: The time to keep the lock acquired
"""
await self._lock.acquire()
await asyncio.sleep(delta)
self._lock.release()
class
BucketLock
¶
Manages the ratelimit for each bucket
Source code in naff/api/http/http_client.py
class BucketLock:
"""Manages the ratelimit for each bucket"""
def __init__(self) -> None:
self._lock: asyncio.Lock = asyncio.Lock()
self.unlock_on_exit: bool = True
self.bucket_hash: Optional[str] = None
self.limit: int = -1
self.remaining: int = -1
self.delta: float = 0.0
def __repr__(self) -> str:
return f"<BucketLock: {self.bucket_hash or 'Generic'}>"
@property
def locked(self) -> bool:
"""Return True if lock is acquired."""
return self._lock.locked()
def unlock(self) -> None:
"""Unlock this bucket."""
self._lock.release()
def ingest_ratelimit_header(self, header: CIMultiDictProxy) -> None:
"""
Ingests a discord rate limit header to configure this bucket lock.
Args:
header: A header from a http response
"""
self.bucket_hash = header.get("x-ratelimit-bucket")
self.limit = int(header.get("x-ratelimit-limit") or -1)
self.remaining = int(header.get("x-ratelimit-remaining") or -1)
self.delta = float(header.get("x-ratelimit-reset-after", 0.0))
async def blind_defer_unlock(self) -> None:
"""Unlocks the BucketLock but doesn't wait for completion."""
self.unlock_on_exit = False
loop = asyncio.get_running_loop()
loop.call_later(self.delta, self.unlock)
async def defer_unlock(self, reset_after: float | None = None) -> None:
"""Unlocks the BucketLock after a specified delay."""
self.unlock_on_exit = False
await asyncio.sleep(reset_after or self.delta)
self.unlock()
async def __aenter__(self) -> None:
await self._lock.acquire()
async def __aexit__(self, *args) -> None:
if self.unlock_on_exit and self._lock.locked():
self.unlock()
self.unlock_on_exit = True
property
readonly
locked: bool
¶
Return True if lock is acquired.
method
unlock(self)
¶
Unlock this bucket.
Source code in naff/api/http/http_client.py
def unlock(self) -> None:
"""Unlock this bucket."""
self._lock.release()
method
ingest_ratelimit_header(self, header)
¶
Ingests a discord rate limit header to configure this bucket lock.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
header |
CIMultiDictProxy |
A header from a http response |
required |
Source code in naff/api/http/http_client.py
def ingest_ratelimit_header(self, header: CIMultiDictProxy) -> None:
"""
Ingests a discord rate limit header to configure this bucket lock.
Args:
header: A header from a http response
"""
self.bucket_hash = header.get("x-ratelimit-bucket")
self.limit = int(header.get("x-ratelimit-limit") or -1)
self.remaining = int(header.get("x-ratelimit-remaining") or -1)
self.delta = float(header.get("x-ratelimit-reset-after", 0.0))
async
method
blind_defer_unlock(self)
¶
Unlocks the BucketLock but doesn't wait for completion.
Source code in naff/api/http/http_client.py
async def blind_defer_unlock(self) -> None:
"""Unlocks the BucketLock but doesn't wait for completion."""
self.unlock_on_exit = False
loop = asyncio.get_running_loop()
loop.call_later(self.delta, self.unlock)
async
method
defer_unlock(self, reset_after)
¶
Unlocks the BucketLock after a specified delay.
Source code in naff/api/http/http_client.py
async def defer_unlock(self, reset_after: float | None = None) -> None:
"""Unlocks the BucketLock after a specified delay."""
self.unlock_on_exit = False
await asyncio.sleep(reset_after or self.delta)
self.unlock()
class
HTTPClient (BotRequests, ChannelRequests, EmojiRequests, GuildRequests, InteractionRequests, MemberRequests, MessageRequests, ReactionRequests, StickerRequests, ThreadRequests, UserRequests, WebhookRequests, ScheduledEventsRequests)
¶
A http client for sending requests to the Discord API.
Source code in naff/api/http/http_client.py
class HTTPClient(
BotRequests,
ChannelRequests,
EmojiRequests,
GuildRequests,
InteractionRequests,
MemberRequests,
MessageRequests,
ReactionRequests,
StickerRequests,
ThreadRequests,
UserRequests,
WebhookRequests,
ScheduledEventsRequests,
):
"""A http client for sending requests to the Discord API."""
def __init__(self, connector: Optional[BaseConnector] = None) -> None:
self.connector: Optional[BaseConnector] = connector
self.__session: Absent[Optional[ClientSession]] = MISSING
self.token: Optional[str] = None
self.global_lock: GlobalLock = GlobalLock()
self._max_attempts: int = 3
self.ratelimit_locks: WeakValueDictionary[str, BucketLock] = WeakValueDictionary()
self._endpoints = {}
self.user_agent: str = (
f"DiscordBot ({__repo_url__} {__version__} Python/{__py_version__}) aiohttp/{aiohttp.__version__}"
)
def get_ratelimit(self, route: Route) -> BucketLock:
"""
Get a route's rate limit bucket.
Args:
route: The route to fetch the ratelimit bucket for
Returns:
The BucketLock object for this route
"""
if bucket_hash := self._endpoints.get(route.rl_bucket):
# we have seen this route before, we know which bucket it is associated with
lock = self.ratelimit_locks.get(bucket_hash)
if lock:
# if we have an active lock on this route, it'll still be in the cache
# return that lock
return lock
# if no cached lock exists, return a new lock
return BucketLock()
def ingest_ratelimit(self, route: Route, header: CIMultiDictProxy, bucket_lock: BucketLock) -> None:
"""
Ingests a ratelimit header from discord to determine ratelimit.
Args:
route: The route we're ingesting ratelimit for
header: The rate limit header in question
bucket_lock: The rate limit bucket for this route
"""
bucket_lock.ingest_ratelimit_header(header)
if bucket_lock.bucket_hash:
# We only ever try and cache the bucket if the bucket hash has been set (ignores unlimited endpoints)
logger.debug(f"Caching ingested rate limit data for: {bucket_lock.bucket_hash}")
self._endpoints[route.rl_bucket] = bucket_lock.bucket_hash
self.ratelimit_locks[bucket_lock.bucket_hash] = bucket_lock
@staticmethod
def _process_payload(payload: dict | list[dict], files: Absent[list[UPLOADABLE_TYPE]]) -> dict | FormData | None:
"""
Processes a payload into a format safe for discord. Converts the payload into FormData where required
Args:
payload: The payload of the request
files: A list of any files to send
Returns:
Either a dictionary or multipart data form
"""
if payload in (None, MISSING):
return None
if isinstance(payload, dict):
payload = dict_filter(payload)
else:
payload = [dict_filter(x) if isinstance(x, dict) else x for x in payload]
if not files:
return payload
if not isinstance(files, list):
files = [files]
form_data = FormData()
form_data.add_field("payload_json", OverriddenJson.dumps(payload))
for index, file in enumerate(files):
file_buffer = models.open_file(file)
if isinstance(file, models.File):
form_data.add_field(f"files[{index}]", file_buffer, filename=file.file_name)
else:
form_data.add_field(f"files[{index}]", file_buffer)
return form_data
async def request(
self,
route: Route,
payload: Absent[dict] = MISSING,
files: Absent[list[UPLOADABLE_TYPE]] = MISSING,
reason: Absent[str] = MISSING,
params: Absent[dict] = MISSING,
**kwargs: dict,
) -> Any:
"""
Make a request to discord.
Args:
route: The route to take
payload: The payload for this request
files: The files to send with this request
reason: Attach a reason to this request, used for audit logs
"""
# Assemble headers
kwargs["headers"] = {"User-Agent": self.user_agent}
if self.token:
kwargs["headers"]["Authorization"] = f"Bot {self.token}"
if reason not in (None, MISSING):
kwargs["headers"]["X-Audit-Log-Reason"] = _uriquote(reason, safe="/ ")
if isinstance(payload, (list, dict)) and not files:
kwargs["headers"]["Content-Type"] = "application/json"
if isinstance(params, dict):
kwargs["params"] = dict_filter(params)
lock = self.get_ratelimit(route)
# this gets a BucketLock for this route.
# If this endpoint has been used before, it will get an existing ratelimit for the respective buckethash
# otherwise a brand-new bucket lock will be returned
for attempt in range(self._max_attempts):
async with lock:
try:
await self.global_lock.rate_limit()
# prevent us exceeding the global rate limit by throttling http requests
if self.__session.closed:
await self.login(self.token)
processed_data = self._process_payload(payload, files)
if isinstance(processed_data, FormData):
kwargs["data"] = processed_data
else:
kwargs["json"] = processed_data
async with self.__session.request(route.method, route.url, **kwargs) as response:
result = await response_decode(response)
self.ingest_ratelimit(route, response.headers, lock)
if response.status == 429:
# ratelimit exceeded
if result.get("global", False):
# global ratelimit is reached
# if we get a global, that's pretty bad, this would usually happen if the user is hitting the api from 2 clients sharing a token
logger.error(
f"Bot has exceeded global ratelimit, locking REST API for {result.get('retry_after')} seconds"
)
await self.global_lock.lock(float(result.get("retry_after")))
continue
elif result.get("message") == "The resource is being rate limited.":
# resource ratelimit is reached
logger.warning(
f"{route.endpoint} The resource is being rate limited! "
f"Reset in {result.get('retry_after')} seconds"
)
# lock this resource and wait for unlock
await lock.defer_unlock(float(result.get("retry_after")))
continue
else:
# endpoint ratelimit is reached
# 429's are unfortunately unavoidable, but we can attempt to avoid them
# so long as these are infrequent we're doing well
logger.warning(
f"{route.endpoint} Has exceeded it's ratelimit ({lock.limit})! Reset in {lock.delta} seconds"
)
await lock.defer_unlock() # lock this route and wait for unlock
continue
elif lock.remaining == 0:
# Last call available in the bucket, lock until reset
logger.debug(
f"{route.endpoint} Has exhausted its ratelimit ({lock.limit})! Locking route for {lock.delta} seconds"
)
await lock.blind_defer_unlock() # lock this route, but continue processing the current response
elif response.status in {500, 502, 504}:
# Server issues, retry
logger.warning(
f"{route.endpoint} Received {response.status}... retrying in {1 + attempt * 2} seconds"
)
await asyncio.sleep(1 + attempt * 2)
continue
if not 300 > response.status >= 200:
await self._raise_exception(response, route, result)
logger.debug(
f"{route.endpoint} Received {response.status} :: [{lock.remaining}/{lock.limit} calls remaining]"
)
return result
except OSError as e:
if attempt < self._max_attempts - 1 and e.errno in (54, 10054):
await asyncio.sleep(1 + attempt * 2)
continue
raise
async def _raise_exception(self, response, route, result) -> None:
logger.error(f"{route.method}::{route.url}: {response.status}")
if response.status == 403:
raise Forbidden(response, response_data=result, route=route)
elif response.status == 404:
raise NotFound(response, response_data=result, route=route)
elif response.status >= 500:
raise DiscordError(response, response_data=result, route=route)
else:
raise HTTPException(response, response_data=result, route=route)
async def request_cdn(self, url, asset) -> bytes:
logger.debug(f"{asset} requests {url} from CDN")
async with self.__session.get(url) as response:
if response.status == 200:
return await response.read()
await self._raise_exception(response, asset, await response_decode(response))
async def login(self, token: str) -> dict:
"""
"Login" to the gateway, basically validates the token and grabs user data.
Args:
token: the token to use
Returns:
The currently logged in bot's data
"""
self.__session = ClientSession(connector=self.connector)
self.token = token
try:
return await self.request(Route("GET", "/users/@me"))
except HTTPException as e:
if e.status == 401:
raise LoginError("An improper token was passed") from e
raise
async def close(self) -> None:
"""Close the session."""
if self.__session and not self.__session.closed:
await self.__session.close()
async def get_gateway(self) -> str:
"""
Gets the gateway url.
Returns:
The gateway url
"""
try:
data: dict = await self.request(Route("GET", "/gateway"))
except HTTPException as exc:
raise GatewayNotFound from exc
return "{0}?encoding={1}&v={2}&compress=zlib-stream".format(data["url"], "json", __api_version__)
async def get_gateway_bot(self) -> discord_typings.GetGatewayBotData:
try:
data: dict = await self.request(Route("GET", "/gateway/bot"))
except HTTPException as exc:
raise GatewayNotFound from exc
return data
async def websocket_connect(self, url: str) -> ClientWebSocketResponse:
"""
Connect to the websocket.
Args:
url: the url to connect to
"""
return await self.__session.ws_connect(
url, timeout=30, max_msg_size=0, autoclose=False, headers={"User-Agent": self.user_agent}, compress=0
)
async
inherited
method
get_current_bot_information(self)
¶
Gets the bot's application object without flags.
Returns:
Type | Description |
---|---|
ApplicationData |
application object |
Source code in naff/api/http/http_client.py
async def get_current_bot_information(self) -> discord_typings.ApplicationData:
"""
Gets the bot's application object without flags.
Returns:
application object
"""
return await self.request(Route("GET", "/oauth2/applications/@me"))
async
inherited
method
get_current_user(self)
¶
Shortcut to get requester's user.
Returns:
Type | Description |
---|---|
UserData |
The user object. |
Source code in naff/api/http/http_client.py
async def get_current_user(self) -> discord_typings.UserData:
"""
Shortcut to get requester's user.
Returns:
The user object.
"""
return await self.get_user("@me")
async
inherited
method
create_reaction(self, channel_id, message_id, emoji)
¶
Create a reaction for a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in |
required |
message_id |
Snowflake_Type |
The message to create a a reaction on |
required |
emoji |
str |
The emoji to use (format: |
required |
Source code in naff/api/http/http_client.py
async def create_reaction(self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type", emoji: str) -> None:
"""
Create a reaction for a message.
Args:
channel_id: The channel this is taking place in
message_id: The message to create a a reaction on
emoji: The emoji to use (format: `name:id`)
"""
return await self.request(
Route(
"PUT",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
)
async
inherited
method
get_all_guild_emoji(self, guild_id)
¶
Get all the emoji from a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query. |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.emoji.EmojiData] |
List of emoji objects |
Source code in naff/api/http/http_client.py
async def get_all_guild_emoji(self, guild_id: "Snowflake_Type") -> List[discord_typings.EmojiData]:
"""
Get all the emoji from a guild.
Args:
guild_id: The ID of the guild to query.
Returns:
List of emoji objects
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/emojis"))
async
inherited
method
list_schedules_events(self, guild_id, with_user_count)
¶
Get the scheduled events for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to get scheduled events from |
required |
with_user_count |
bool |
Whether to include the user count in the response |
False |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.resources.guild_scheduled_events.StageGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.VoiceGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.ExternalGuildScheduledEventData]] |
List of Scheduled Events or None |
Source code in naff/api/http/http_client.py
async def list_schedules_events(
self, guild_id: "Snowflake_Type", with_user_count: bool = False
) -> List[discord_typings.GuildScheduledEventData]:
"""
Get the scheduled events for a guild.
Args:
guild_id: The guild to get scheduled events from
with_user_count: Whether to include the user count in the response
Returns:
List of Scheduled Events or None
"""
return await self.request(
Route("GET", f"/guilds/{guild_id}/scheduled-events?with_user_count={with_user_count}")
)
async
inherited
method
create_message(self, payload, channel_id, files)
¶
Send a message to the specified channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The message to send |
required |
files |
list['UPLOADABLE_TYPE'] | None |
Any files to send with this message |
None |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
The resulting message object |
Source code in naff/api/http/http_client.py
async def create_message(
self, payload: dict, channel_id: "Snowflake_Type", files: list["UPLOADABLE_TYPE"] | None = None
) -> discord_typings.MessageData:
"""
Send a message to the specified channel.
Args:
payload: The message to send
files: Any files to send with this message
Returns:
The resulting message object
"""
return await self.request(Route("POST", f"/channels/{channel_id}/messages"), payload=payload, files=files)
async
inherited
method
create_webhook(self, channel_id, name, avatar)
¶
Create a new webhook.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel to add this webhook to |
required |
name |
str |
name of the webhook (1-80 characters) |
required |
avatar |
Any |
The image for the default webhook avatar |
None |
Source code in naff/api/http/http_client.py
async def create_webhook(
self, channel_id: "Snowflake_Type", name: str, avatar: Any = None
) -> discord_typings.WebhookData:
"""
Create a new webhook.
Args:
channel_id: The id of the channel to add this webhook to
name: name of the webhook (1-80 characters)
avatar: The image for the default webhook avatar
"""
return await self.request(
Route("POST", f"/channels/{channel_id}/webhooks"), payload={"name": name, "avatar": avatar}
)
async
inherited
method
delete_application_command(self, application_id, guild_id, command_id)
¶
Delete an existing application command for this application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
Snowflake_Type |
the what application to delete for |
required |
guild_id |
Snowflake_Type |
specify a guild to delete commands from |
required |
Source code in naff/api/http/http_client.py
async def delete_application_command(
self, application_id: "Snowflake_Type", guild_id: "Snowflake_Type", command_id: "Snowflake_Type"
) -> None:
"""
Delete an existing application command for this application.
Args:
application_id: the what application to delete for
guild_id: specify a guild to delete commands from
command_id The command to delete
"""
if guild_id == GLOBAL_SCOPE:
return await self.request(Route("DELETE", f"/applications/{application_id}/commands/{command_id}"))
return await self.request(
Route("DELETE", f"/applications/{application_id}/guilds/{guild_id}/commands/{command_id}")
)
async
inherited
method
get_member(self, guild_id, user_id)
¶
Get a member of a guild by ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The id of the guild |
required |
user_id |
Snowflake_Type |
The user id to grab |
required |
Source code in naff/api/http/http_client.py
async def get_member(
self, guild_id: "Snowflake_Type", user_id: "Snowflake_Type"
) -> discord_typings.GuildMemberData:
"""
Get a member of a guild by ID.
Args:
guild_id: The id of the guild
user_id: The user id to grab
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/members/{user_id}"))
async
inherited
method
get_sticker(self, sticker_id)
¶
Get a specific sticker.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sticker_id |
Snowflake_Type |
The id of the sticker |
required |
Returns:
Type | Description |
---|---|
StickerData |
Sticker or None |
Source code in naff/api/http/http_client.py
async def get_sticker(self, sticker_id: "Snowflake_Type") -> discord_typings.StickerData:
"""
Get a specific sticker.
Args:
sticker_id: The id of the sticker
Returns:
Sticker or None
"""
return await self.request(Route("GET", f"/stickers/{sticker_id}"))
async
inherited
method
get_channel(self, channel_id)
¶
Get a channel by ID. Returns a channel object. If the channel is a thread, a thread member object is included.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.TextChannelData, discord_typings.resources.channel.NewsChannelData, discord_typings.resources.channel.DMChannelData, discord_typings.resources.channel.GroupDMChannelData, discord_typings.resources.channel.ThreadChannelData, discord_typings.resources.channel.VoiceChannelData, discord_typings.resources.channel.CategoryChannelData] |
channel |
Source code in naff/api/http/http_client.py
async def get_channel(self, channel_id: "Snowflake_Type") -> discord_typings.ChannelData:
"""
Get a channel by ID. Returns a channel object. If the channel is a thread, a thread member object is included.
Args:
channel_id: The id of the channel
Returns:
channel
"""
return await self.request(Route("GET", f"/channels/{channel_id}"))
async
inherited
method
get_guilds(self, limit, before, after)
¶
Get a list of partial guild objects the current user is a member of req. guilds
scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
limit |
int |
max number of guilds to return (1-200) |
200 |
before |
Optional[Snowflake_Type] |
get guilds before this guild ID |
None |
after |
Optional[Snowflake_Type] |
get guilds after this guild ID |
None |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild.GuildData] |
List of guild objects |
Source code in naff/api/http/http_client.py
async def get_guilds(
self, limit: int = 200, before: Optional["Snowflake_Type"] = None, after: Optional["Snowflake_Type"] = None
) -> List[discord_typings.GuildData]:
"""
Get a list of partial guild objects the current user is a member of req. `guilds` scope.
Args:
limit: max number of guilds to return (1-200)
before: get guilds before this guild ID
after: get guilds after this guild ID
Returns:
List of guild objects
"""
params: Dict[str, Union[int, str]] = {"limit": limit}
if before:
params["before"] = before
if after:
params["after"] = after
return await self.request(Route("GET", "/users/@me/guilds", params=params))
async
inherited
method
join_thread(self, thread_id)
¶
Join a thread.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Snowflake_Type |
The thread to join. |
required |
Source code in naff/api/http/http_client.py
async def join_thread(self, thread_id: "Snowflake_Type") -> None:
"""
Join a thread.
Args:
thread_id: The thread to join.
"""
return await self.request(Route("PUT", f"/channels/{thread_id}/thread-members/@me"))
async
inherited
method
get_current_authorisation_information(self)
¶
Gets info about the current authorization.
Returns:
Type | Description |
---|---|
dict |
Authorisation information |
Source code in naff/api/http/http_client.py
async def get_current_authorisation_information(self) -> dict:
"""
Gets info about the current authorization.
Returns:
Authorisation information
"""
return await self.request(Route("GET", "/oauth2/@me"))
async
inherited
method
get_user(self, user_id)
¶
Get a user object for a given user ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id |
Snowflake_Type |
The user to get. |
required |
Returns:
Type | Description |
---|---|
UserData |
The user object. |
Source code in naff/api/http/http_client.py
async def get_user(self, user_id: "Snowflake_Type") -> discord_typings.UserData:
"""
Get a user object for a given user ID.
Args:
user_id: The user to get.
Returns:
The user object.
"""
return await self.request(Route("GET", f"/users/{user_id}"))
async
inherited
method
get_guild_emoji(self, guild_id, emoji_id)
¶
Get a specific guild emoji object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
emoji_id |
Snowflake_Type |
The ID of the emoji to get |
required |
Returns:
Type | Description |
---|---|
EmojiData |
PartialEmoji object |
Source code in naff/api/http/http_client.py
async def get_guild_emoji(
self, guild_id: "Snowflake_Type", emoji_id: "Snowflake_Type"
) -> discord_typings.EmojiData:
"""
Get a specific guild emoji object.
Args:
guild_id: The ID of the guild to query
emoji_id: The ID of the emoji to get
Returns:
PartialEmoji object
"""
data = await self.request(Route("GET", f"/guilds/{guild_id}/emojis/{emoji_id}"))
if data:
data["guild_id"] = guild_id
return data
async
inherited
method
leave_thread(self, thread_id)
¶
Leave a thread.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Snowflake_Type |
The thread to leave. |
required |
Source code in naff/api/http/http_client.py
async def leave_thread(self, thread_id: "Snowflake_Type") -> None:
"""
Leave a thread.
Args:
thread_id: The thread to leave.
"""
return await self.request(Route("DELETE", f"/channels/{thread_id}/thread-members/@me"))
async
inherited
method
list_members(self, guild_id, limit, after)
¶
List the members of a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
limit |
int |
How many members to get (max 1000) |
1 |
after |
Snowflake_Type |
Get IDs after this snowflake |
Missing |
Source code in naff/api/http/http_client.py
async def list_members(
self, guild_id: "Snowflake_Type", limit: int = 1, after: "Snowflake_Type" = MISSING
) -> List[discord_typings.GuildMemberData]:
"""
List the members of a guild.
Args:
guild_id: The ID of the guild
limit: How many members to get (max 1000)
after: Get IDs after this snowflake
"""
payload = {"limit": limit, "after": after}
return await self.request(Route("GET", f"/guilds/{guild_id}/members"), params=payload)
async
inherited
method
list_nitro_sticker_packs(self)
¶
Gets the list of sticker packs available to Nitro subscribers.
Returns:
Type | Description |
---|---|
List[discord_typings.resources.sticker.StickerPackData] |
List of sticker packs |
Source code in naff/api/http/http_client.py
async def list_nitro_sticker_packs(self) -> List[discord_typings.StickerPackData]:
"""
Gets the list of sticker packs available to Nitro subscribers.
Returns:
List of sticker packs
"""
return await self.request(Route("GET", "/sticker-packs"))
async
inherited
method
list_voice_regions(self)
¶
Gets an array of voice region objects that can be used when setting a voice or stage channel's rtc_region
.
Returns:
Type | Description |
---|---|
List[discord_typings.resources.voice.VoiceRegionData] |
an array of voice region objects |
Source code in naff/api/http/http_client.py
async def list_voice_regions(self) -> List[discord_typings.VoiceRegionData]:
"""
Gets an array of voice region objects that can be used when setting a voice or stage channel's `rtc_region`.
Returns:
an array of voice region objects
"""
return await self.request(Route("GET", "/voice/regions"))
async
inherited
method
get_channel_messages(self, channel_id, limit, around, before, after)
¶
Get the messages for a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel to get messages from |
required |
limit |
int |
How many messages to get (default 50, max 100) |
50 |
around |
Optional[Snowflake_Type] |
Get messages around this snowflake |
None |
before |
Optional[Snowflake_Type] |
Get messages before this snowflake |
None |
after |
Optional[Snowflake_Type] |
Get messages after this snowflake |
None |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData]] |
List of message dicts |
Source code in naff/api/http/http_client.py
async def get_channel_messages(
self,
channel_id: "Snowflake_Type",
limit: int = 50,
around: Optional["Snowflake_Type"] = None,
before: Optional["Snowflake_Type"] = None,
after: Optional["Snowflake_Type"] = None,
) -> List[discord_typings.MessageData]:
"""
Get the messages for a channel.
Args:
channel_id: The channel to get messages from
limit: How many messages to get (default 50, max 100)
around: Get messages around this snowflake
before: Get messages before this snowflake
after: Get messages after this snowflake
Returns:
List of message dicts
"""
params: Dict[str, Union[int, str]] = {"limit": limit}
params_used = 0
if before:
params_used += 1
params["before"] = before
if after:
params_used += 1
params["after"] = after
if around:
params_used += 1
params["around"] = around
if params_used > 1:
raise ValueError("`before` `after` and `around` are mutually exclusive, only one may be passed at a time.")
return await self.request(Route("GET", f"/channels/{channel_id}/messages"), params=params)
async
inherited
method
delete_message(self, channel_id, message_id, reason)
¶
Deletes a message from the specified channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel to delete the message from |
required |
message_id |
Snowflake_Type |
The id of the message to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def delete_message(
self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Deletes a message from the specified channel.
Args:
channel_id: The id of the channel to delete the message from
message_id: The id of the message to delete
reason: The reason for this action
"""
await self.request(Route("DELETE", f"/channels/{channel_id}/messages/{message_id}"), reason=reason)
async
inherited
method
get_channel_webhooks(self, channel_id)
¶
Return a list of channel webhook objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel to query |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.webhook.WebhookData] |
List of webhook objects |
Source code in naff/api/http/http_client.py
async def get_channel_webhooks(self, channel_id: "Snowflake_Type") -> List[discord_typings.WebhookData]:
"""
Return a list of channel webhook objects.
Args:
channel_id: The id of the channel to query
Returns:
List of webhook objects
"""
return await self.request(Route("GET", f"/channels/{channel_id}/webhooks"))
async
inherited
method
get_scheduled_event(self, guild_id, scheduled_event_id, with_user_count)
¶
Get a scheduled event for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to get scheduled event from |
required |
with_user_count |
bool |
Whether to include the user count in the response |
False |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.guild_scheduled_events.StageGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.VoiceGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.ExternalGuildScheduledEventData] |
Scheduled Event or None |
Source code in naff/api/http/http_client.py
async def get_scheduled_event(
self, guild_id: "Snowflake_Type", scheduled_event_id: "Snowflake_Type", with_user_count: bool = False
) -> discord_typings.GuildScheduledEventData:
"""
Get a scheduled event for a guild.
Args:
guild_id: The guild to get scheduled event from
with_user_count: Whether to include the user count in the response
Returns:
Scheduled Event or None
"""
return await self.request(
Route("GET", f"/guilds/{guild_id}/scheduled-events/{scheduled_event_id}"),
params={"with_user_count": with_user_count},
)
async
inherited
method
get_application_commands(self, application_id, guild_id, with_localisations)
¶
Get all application commands for this application from discord.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
Snowflake_Type |
the what application to query |
required |
guild_id |
Snowflake_Type |
specify a guild to get commands from |
required |
with_localisations |
bool |
whether to include all localisations in the response |
True |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.interactions.commands.ChatInputCommandData, discord_typings.interactions.commands.ContextMenuCommandData]] |
Application command data |
Source code in naff/api/http/http_client.py
async def get_application_commands(
self, application_id: "Snowflake_Type", guild_id: "Snowflake_Type", with_localisations: bool = True
) -> List[discord_typings.ApplicationCommandData]:
"""
Get all application commands for this application from discord.
Args:
application_id: the what application to query
guild_id: specify a guild to get commands from
with_localisations: whether to include all localisations in the response
Returns:
Application command data
"""
if guild_id == GLOBAL_SCOPE:
return await self.request(
Route("GET", f"/applications/{application_id}/commands"),
params={"with_localizations": int(with_localisations)},
)
return await self.request(
Route("GET", f"/applications/{application_id}/guilds/{guild_id}/commands"),
params={"with_localizations": int(with_localisations)},
)
async
inherited
method
remove_self_reaction(self, channel_id, message_id, emoji)
¶
Remove client's reaction from a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in. |
required |
message_id |
Snowflake_Type |
The message to remove the reaction on. |
required |
emoji |
str |
The emoji to remove. (format: |
required |
Source code in naff/api/http/http_client.py
async def remove_self_reaction(
self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type", emoji: str
) -> None:
"""
Remove client's reaction from a message.
Args:
channel_id: The channel this is taking place in.
message_id: The message to remove the reaction on.
emoji: The emoji to remove. (format: `name:id`)
"""
return await self.request(
Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
)
async
inherited
method
modify_client_user(self, payload)
¶
Modify the user account settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The data to send. |
required |
Source code in naff/api/http/http_client.py
async def modify_client_user(self, payload: dict) -> discord_typings.UserData:
"""
Modify the user account settings.
Args:
payload: The data to send.
"""
return await self.request(Route("PATCH", "/users/@me"), payload=payload)
async
inherited
method
add_thread_member(self, thread_id, user_id)
¶
Add another user to a thread.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Snowflake_Type |
The ID of the thread |
required |
user_id |
Snowflake_Type |
The ID of the user to add |
required |
Source code in naff/api/http/http_client.py
async def add_thread_member(self, thread_id: "Snowflake_Type", user_id: "Snowflake_Type") -> None:
"""
Add another user to a thread.
Args:
thread_id: The ID of the thread
user_id: The ID of the user to add
"""
return await self.request(Route("PUT", f"/channels/{thread_id}/thread-members/{user_id}"))
async
inherited
method
list_guild_stickers(self, guild_id)
¶
Get the stickers for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to get stickers from |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.sticker.StickerData] |
List of Stickers or None |
Source code in naff/api/http/http_client.py
async def list_guild_stickers(self, guild_id: "Snowflake_Type") -> List[discord_typings.StickerData]:
"""
Get the stickers for a guild.
Args:
guild_id: The guild to get stickers from
Returns:
List of Stickers or None
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/stickers"))
async
inherited
method
get_guild(self, guild_id, with_counts)
¶
Get the guild object for the given ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
the id of the guild |
required |
with_counts |
Optional[bool] |
when |
True |
Returns:
Type | Description |
---|---|
GuildData |
a guild object |
Source code in naff/api/http/http_client.py
async def get_guild(
self, guild_id: "Snowflake_Type", with_counts: Optional[bool] = True
) -> discord_typings.GuildData:
"""
Get the guild object for the given ID.
Args:
guild_id: the id of the guild
with_counts: when `true`, will return approximate member and presence counts for the guild
Returns:
a guild object
"""
return await self.request(
Route("GET", f"/guilds/{guild_id}"), params={"with_counts": int(with_counts)} # type: ignore
)
async
inherited
method
search_guild_members(self, guild_id, query, limit)
¶
Search a guild for members who's username or nickname starts with provided string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to search |
required |
query |
str |
The string to search for |
required |
limit |
int |
The number of members to return |
1 |
Source code in naff/api/http/http_client.py
async def search_guild_members(
self, guild_id: "Snowflake_Type", query: str, limit: int = 1
) -> List[discord_typings.GuildMemberData]:
"""
Search a guild for members who's username or nickname starts with provided string.
Args:
guild_id: The ID of the guild to search
query: The string to search for
limit: The number of members to return
"""
return await self.request(
Route("GET", f"/guilds/{guild_id}/members/search"), params={"query": query, "limit": limit}
)
async
inherited
method
get_guild_webhooks(self, guild_id)
¶
Return a list of guild webhook objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The id of the guild to query |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.webhook.WebhookData] |
List of webhook objects |
Source code in naff/api/http/http_client.py
async def get_guild_webhooks(self, guild_id: "Snowflake_Type") -> List[discord_typings.WebhookData]:
"""
Return a list of guild webhook objects.
Args:
guild_id: The id of the guild to query
Returns:
List of webhook objects
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/webhooks"))
async
inherited
method
bulk_delete_messages(self, channel_id, message_ids, reason)
¶
Delete multiple messages in a single request.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel these messages are in |
required |
message_ids |
List[Snowflake_Type] |
A list of message ids to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def bulk_delete_messages(
self, channel_id: "Snowflake_Type", message_ids: List["Snowflake_Type"], reason: Absent[str] = MISSING
) -> None:
"""
Delete multiple messages in a single request.
Args:
channel_id: The id of the channel these messages are in
message_ids: A list of message ids to delete
reason: The reason for this action
"""
return await self.request(
Route("POST", f"/channels/{channel_id}/messages/bulk-delete"),
payload={"messages": message_ids},
reason=reason,
)
async
inherited
method
create_guild_emoji(self, payload, guild_id, reason)
¶
Create a guild emoji.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The emoji's data |
required |
guild_id |
Snowflake_Type |
The ID of the guild |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this creation |
Missing |
Returns:
Type | Description |
---|---|
EmojiData |
The created emoji object |
Source code in naff/api/http/http_client.py
async def create_guild_emoji(
self, payload: dict, guild_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> discord_typings.EmojiData:
"""
Create a guild emoji.
Args:
payload: The emoji's data
guild_id: The ID of the guild
reason: The reason for this creation
Returns:
The created emoji object
"""
return await self.request(Route("POST", f"/guilds/{guild_id}/emojis"), payload=payload, reason=reason)
async
inherited
method
get_user_guilds(self)
¶
Returns a list of partial guild objects the current user is a member of.
Requires the guilds OAuth2 scope.
Source code in naff/api/http/http_client.py
async def get_user_guilds(self) -> List[discord_typings.GuildData]:
"""
Returns a list of partial guild objects the current user is a member of.
Requires the guilds OAuth2 scope.
"""
return await self.request(Route("GET", "/users/@me/guilds"))
async
inherited
method
remove_thread_member(self, thread_id, user_id)
¶
Remove another user from a thread.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Snowflake_Type |
The ID of the thread |
required |
user_id |
Snowflake_Type |
The ID of the user to remove |
required |
Source code in naff/api/http/http_client.py
async def remove_thread_member(self, thread_id: "Snowflake_Type", user_id: "Snowflake_Type") -> None:
"""
Remove another user from a thread.
Args:
thread_id: The ID of the thread
user_id: The ID of the user to remove
"""
return await self.request(Route("DELETE", f"/channels/{thread_id}/thread-members/{user_id}"))
async
inherited
method
create_scheduled_event(self, guild_id, payload, reason)
¶
Create a scheduled event for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to create scheduled event from |
required |
payload |
dict |
The scheduled event payload |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason to be displayed in audit logs |
Missing |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.guild_scheduled_events.StageGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.VoiceGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.ExternalGuildScheduledEventData] |
Scheduled Event or None |
Source code in naff/api/http/http_client.py
async def create_scheduled_event(
self,
guild_id: "Snowflake_Type",
payload: dict,
reason: Absent[str] = MISSING,
) -> discord_typings.GuildScheduledEventData:
"""
Create a scheduled event for a guild.
Args:
guild_id: The guild to create scheduled event from
payload: The scheduled event payload
reason: The reason to be displayed in audit logs
Returns:
Scheduled Event or None
"""
return await self.request(Route("POST", f"/guilds/{guild_id}/scheduled-events"), payload=payload, reason=reason)
async
inherited
method
get_guild_sticker(self, guild_id, sticker_id)
¶
Get a sticker from a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to get stickers from |
required |
sticker_id |
Snowflake_Type |
The sticker to get from the guild |
required |
Returns:
Type | Description |
---|---|
StickerData |
Sticker or None |
Source code in naff/api/http/http_client.py
async def get_guild_sticker(
self, guild_id: "Snowflake_Type", sticker_id: "Snowflake_Type"
) -> discord_typings.StickerData:
"""
Get a sticker from a guild.
Args:
guild_id: The guild to get stickers from
sticker_id: The sticker to get from the guild
Returns:
Sticker or None
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/stickers/{sticker_id}"))
async
inherited
method
leave_guild(self, guild_id)
¶
Leave a guild. Returns a 204 empty response on success.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to leave from. |
required |
Source code in naff/api/http/http_client.py
async def leave_guild(self, guild_id: "Snowflake_Type") -> None:
"""
Leave a guild. Returns a 204 empty response on success.
Args:
guild_id: The guild to leave from.
"""
return await self.request(Route("DELETE", f"/users/@me/guilds/{guild_id}"))
async
inherited
method
remove_user_reaction(self, channel_id, message_id, emoji, user_id)
¶
Remove user's reaction from a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in |
required |
message_id |
Snowflake_Type |
The message to remove the reaction on. |
required |
emoji |
str |
The emoji to remove. (format: |
required |
user_id |
Snowflake_Type |
The user to remove reaction of. |
required |
Source code in naff/api/http/http_client.py
async def remove_user_reaction(
self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type", emoji: str, user_id: "Snowflake_Type"
) -> None:
"""
Remove user's reaction from a message.
Args:
channel_id: The channel this is taking place in
message_id: The message to remove the reaction on.
emoji: The emoji to remove. (format: `name:id`)
user_id: The user to remove reaction of.
"""
return await self.request(
Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/{user_id}",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
user_id=user_id,
)
)
async
inherited
method
get_webhook(self, webhook_id, webhook_token)
¶
Return the new webhook object for the given id.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to get |
required |
webhook_token |
str |
The token for the webhook |
None |
Returns:
Type | Description |
---|---|
WebhookData |
Webhook object |
Source code in naff/api/http/http_client.py
async def get_webhook(self, webhook_id: "Snowflake_Type", webhook_token: str = None) -> discord_typings.WebhookData:
"""
Return the new webhook object for the given id.
Args:
webhook_id: The ID of the webhook to get
webhook_token: The token for the webhook
Returns:
Webhook object
"""
endpoint = f"/webhooks/{webhook_id}{f'/{webhook_token}' if webhook_token else ''}"
return await self.request(Route("GET", endpoint))
async
inherited
method
get_guild_preview(self, guild_id)
¶
Get a guild's preview.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
the guilds ID |
required |
Returns:
Type | Description |
---|---|
GuildPreviewData |
guild preview object |
Source code in naff/api/http/http_client.py
async def get_guild_preview(self, guild_id: "Snowflake_Type") -> discord_typings.GuildPreviewData:
"""
Get a guild's preview.
Args:
guild_id: the guilds ID
Returns:
guild preview object
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/preview"))
async
inherited
method
overwrite_application_commands(self, app_id, data, guild_id)
¶
Take a list of commands and overwrite the existing command list within the given scope
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app_id |
Snowflake_Type |
The application ID of this bot |
required |
guild_id |
Snowflake_Type |
The ID of the guild this command is for, if this is a guild command |
None |
data |
List[Dict] |
List of your interaction data |
required |
Source code in naff/api/http/http_client.py
async def overwrite_application_commands(
self, app_id: "Snowflake_Type", data: List[Dict], guild_id: "Snowflake_Type" = None
) -> List[discord_typings.ApplicationCommandData]:
"""
Take a list of commands and overwrite the existing command list within the given scope
Args:
app_id: The application ID of this bot
guild_id: The ID of the guild this command is for, if this is a guild command
data: List of your interaction data
"""
if guild_id == GLOBAL_SCOPE:
return await self.request(Route("PUT", f"/applications/{app_id}/commands"), payload=data)
return await self.request(Route("PUT", f"/applications/{app_id}/guilds/{guild_id}/commands"), payload=data)
async
inherited
method
modify_guild_member(self, guild_id, user_id, nickname, roles, mute, deaf, channel_id, communication_disabled_until, reason)
¶
Modify attributes of a guild member.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
user_id |
Snowflake_Type |
The ID of the user we're modifying |
required |
nickname |
Union[str, naff.client.const.Missing] |
Value to set users nickname to |
Missing |
roles |
List[Snowflake_Type] |
Array of role ids the member is assigned |
Missing |
mute |
Union[bool, naff.client.const.Missing] |
Whether the user is muted in voice channels. Will throw a 400 if the user is not in a voice channel |
Missing |
deaf |
Union[bool, naff.client.const.Missing] |
Whether the user is deafened in voice channels |
Missing |
channel_id |
Snowflake_Type |
id of channel to move user to (if they are connected to voice) |
Missing |
communication_disabled_until |
Union[naff.models.discord.timestamp.Timestamp, NoneType, naff.client.const.Missing] |
when the user's timeout will expire and the user will be able to communicate in the guild again |
Missing |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Returns:
Type | Description |
---|---|
GuildMemberData |
The updated member object |
Source code in naff/api/http/http_client.py
async def modify_guild_member(
self,
guild_id: "Snowflake_Type",
user_id: "Snowflake_Type",
nickname: Absent[str] = MISSING,
roles: List["Snowflake_Type"] = MISSING,
mute: Absent[bool] = MISSING,
deaf: Absent[bool] = MISSING,
channel_id: "Snowflake_Type" = MISSING,
communication_disabled_until: Absent[Union[Timestamp, None]] = MISSING,
reason: Absent[str] = MISSING,
) -> discord_typings.GuildMemberData:
"""
Modify attributes of a guild member.
Args:
guild_id: The ID of the guild
user_id: The ID of the user we're modifying
nickname: Value to set users nickname to
roles: Array of role ids the member is assigned
mute: Whether the user is muted in voice channels. Will throw a 400 if the user is not in a voice channel
deaf: Whether the user is deafened in voice channels
channel_id: id of channel to move user to (if they are connected to voice)
communication_disabled_until: when the user's timeout will expire and the user will be able to communicate in the guild again
reason: An optional reason for the audit log
Returns:
The updated member object
"""
if communication_disabled_until is not MISSING:
if isinstance(communication_disabled_until, Timestamp):
communication_disabled_until = communication_disabled_until.isoformat()
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/members/{user_id}"),
payload={
"nick": nickname,
"roles": roles,
"mute": mute,
"deaf": deaf,
"channel_id": channel_id,
"communication_disabled_until": communication_disabled_until,
},
reason=reason,
)
async
inherited
method
list_thread_members(self, thread_id)
¶
Get a list of members in the thread.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Snowflake_Type |
the id of the thread |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.channel.ThreadMemberData] |
a list of member objects |
Source code in naff/api/http/http_client.py
async def list_thread_members(self, thread_id: "Snowflake_Type") -> List[discord_typings.ThreadMemberData]:
"""
Get a list of members in the thread.
Args:
thread_id: the id of the thread
Returns:
a list of member objects
"""
return await self.request(Route("GET", f"/channels/{thread_id}/thread-members"))
async
inherited
method
get_message(self, channel_id, message_id)
¶
Get a specific message in the channel. Returns a message object on success.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
the channel this message belongs to |
required |
message_id |
Snowflake_Type |
the id of the message |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
message or None |
Source code in naff/api/http/http_client.py
async def get_message(
self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type"
) -> discord_typings.MessageData:
"""
Get a specific message in the channel. Returns a message object on success.
Args:
channel_id: the channel this message belongs to
message_id: the id of the message
Returns:
message or None
"""
return await self.request(Route("GET", f"/channels/{channel_id}/messages/{message_id}"))
async
inherited
method
modify_guild_emoji(self, payload, guild_id, emoji_id, reason)
¶
Modify an existing guild emoji.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The emoji's data |
required |
guild_id |
Snowflake_Type |
The ID of the guild |
required |
emoji_id |
Snowflake_Type |
The ID of the emoji to update |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this creation |
Missing |
Returns:
Type | Description |
---|---|
EmojiData |
The updated emoji object |
Source code in naff/api/http/http_client.py
async def modify_guild_emoji(
self, payload: dict, guild_id: "Snowflake_Type", emoji_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> discord_typings.EmojiData:
"""
Modify an existing guild emoji.
Args:
payload: The emoji's data
guild_id: The ID of the guild
emoji_id: The ID of the emoji to update
reason: The reason for this creation
Returns:
The updated emoji object
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/emojis/{emoji_id}"), payload=payload, reason=reason
)
async
inherited
method
create_dm(self, recipient_id)
¶
Create a new DM channel with a user. Returns a DM channel object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recipient_id |
Snowflake_Type |
The recipient to open a DM channel with. |
required |
Source code in naff/api/http/http_client.py
async def create_dm(self, recipient_id: "Snowflake_Type") -> discord_typings.DMChannelData:
"""
Create a new DM channel with a user. Returns a DM channel object.
Args:
recipient_id: The recipient to open a DM channel with.
"""
return await self.request(Route("POST", "/users/@me/channels"), payload={"recipient_id": recipient_id})
async
inherited
method
create_guild_sticker(self, payload, guild_id, file, reason)
¶
Create a new sticker for the guild. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
the payload to send. |
required |
guild_id |
Snowflake_Type |
The guild to create sticker at. |
required |
file |
UPLOADABLE_TYPE |
the image to use for the sticker |
required |
reason |
Optional[str] |
The reason for this action. |
Missing |
Returns:
Type | Description |
---|---|
StickerData |
The new sticker data on success. |
Source code in naff/api/http/http_client.py
async def create_guild_sticker(
self, payload: dict, guild_id: "Snowflake_Type", file: "UPLOADABLE_TYPE", reason: Optional[str] = MISSING
) -> discord_typings.StickerData:
"""
Create a new sticker for the guild. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Args:
payload: the payload to send.
guild_id: The guild to create sticker at.
file: the image to use for the sticker
reason: The reason for this action.
Returns:
The new sticker data on success.
"""
return await self.request(
Route("POST", f"/guild/{guild_id}/stickers"), payload=payload, files=[file], reason=reason
)
async
inherited
method
modify_scheduled_event(self, guild_id, scheduled_event_id, payload, reason)
¶
Modify a scheduled event for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to modify scheduled event from |
required |
scheduled_event_id |
Snowflake_Type |
The scheduled event to modify |
required |
payload |
dict |
The payload to modify the scheduled event with |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason to be displayed in audit logs |
Missing |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.guild_scheduled_events.StageGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.VoiceGuildScheduledEventData, discord_typings.resources.guild_scheduled_events.ExternalGuildScheduledEventData] |
Scheduled Event or None |
Source code in naff/api/http/http_client.py
async def modify_scheduled_event(
self,
guild_id: "Snowflake_Type",
scheduled_event_id: "Snowflake_Type",
payload: dict,
reason: Absent[str] = MISSING,
) -> discord_typings.GuildScheduledEventData:
"""
Modify a scheduled event for a guild.
Args:
guild_id: The guild to modify scheduled event from
scheduled_event_id: The scheduled event to modify
payload: The payload to modify the scheduled event with
reason: The reason to be displayed in audit logs
Returns:
Scheduled Event or None
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/scheduled-events/{scheduled_event_id}"), payload=payload, reason=reason
)
async
inherited
method
create_guild_channel(self, guild_id, name, channel_type, topic, position, permission_overwrites, parent_id, nsfw, bitrate, user_limit, rate_limit_per_user, reason)
¶
Create a channel in a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to create the channel in |
required |
name |
str |
The name of the channel |
required |
channel_type |
Union[ChannelTypes, int] |
The type of channel to create |
required |
topic |
Union[str, NoneType, naff.client.const.Missing] |
The topic of the channel |
Missing |
position |
Union[int, NoneType, naff.client.const.Missing] |
The position of the channel in the channel list |
Missing |
permission_overwrites |
Union[List[Union[PermissionOverwrite, dict]], NoneType, naff.client.const.Missing] |
Permission overwrites to apply to the channel |
Missing |
parent_id |
Snowflake_Type |
The category this channel should be within |
Missing |
nsfw |
bool |
Should this channel be marked nsfw |
False |
bitrate |
int |
The bitrate of this channel, only for voice |
64000 |
user_limit |
int |
The max users that can be in this channel, only for voice |
0 |
rate_limit_per_user |
int |
The time users must wait between sending messages |
0 |
reason |
Union[str, naff.client.const.Missing] |
The reason for creating this channel |
Missing |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.TextChannelData, discord_typings.resources.channel.NewsChannelData, discord_typings.resources.channel.DMChannelData, discord_typings.resources.channel.GroupDMChannelData, discord_typings.resources.channel.ThreadChannelData, discord_typings.resources.channel.VoiceChannelData, discord_typings.resources.channel.CategoryChannelData] |
The created channel object |
Source code in naff/api/http/http_client.py
async def create_guild_channel(
self,
guild_id: "Snowflake_Type",
name: str,
channel_type: Union["ChannelTypes", int],
topic: Absent[Optional[str]] = MISSING,
position: Absent[Optional[int]] = MISSING,
permission_overwrites: Absent[Optional[List[Union["PermissionOverwrite", dict]]]] = MISSING,
parent_id: "Snowflake_Type" = MISSING,
nsfw: bool = False,
bitrate: int = 64000,
user_limit: int = 0,
rate_limit_per_user: int = 0,
reason: Absent[str] = MISSING,
) -> discord_typings.ChannelData:
"""
Create a channel in a guild.
Args:
guild_id: The ID of the guild to create the channel in
name: The name of the channel
channel_type: The type of channel to create
topic: The topic of the channel
position: The position of the channel in the channel list
permission_overwrites: Permission overwrites to apply to the channel
parent_id: The category this channel should be within
nsfw: Should this channel be marked nsfw
bitrate: The bitrate of this channel, only for voice
user_limit: The max users that can be in this channel, only for voice
rate_limit_per_user: The time users must wait between sending messages
reason: The reason for creating this channel
Returns:
The created channel object
"""
payload = {
"name": name,
"type": channel_type,
"topic": topic,
"position": position,
"rate_limit_per_user": rate_limit_per_user,
"nsfw": nsfw,
"parent_id": parent_id,
"permission_overwrites": permission_overwrites,
}
if channel_type in (2, 13):
payload.update(
bitrate=bitrate,
user_limit=user_limit,
)
return await self.request(Route("POST", f"/guilds/{guild_id}/channels"), payload=payload, reason=reason)
async
inherited
method
get_channels(self, guild_id)
¶
Get a guilds channels.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
the id of the guild |
required |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.resources.channel.TextChannelData, discord_typings.resources.channel.NewsChannelData, discord_typings.resources.channel.DMChannelData, discord_typings.resources.channel.GroupDMChannelData, discord_typings.resources.channel.ThreadChannelData, discord_typings.resources.channel.VoiceChannelData, discord_typings.resources.channel.CategoryChannelData]] |
List of channels |
Source code in naff/api/http/http_client.py
async def get_channels(self, guild_id: "Snowflake_Type") -> List[discord_typings.ChannelData]:
"""
Get a guilds channels.
Args:
guild_id: the id of the guild
Returns:
List of channels
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/channels"))
async
inherited
method
list_public_archived_threads(self, channel_id, limit, before)
¶
Get a list of archived public threads in a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel to get threads from |
required |
limit |
int |
Optional limit of threads to |
None |
before |
Optional[Snowflake_Type] |
Get threads before this snowflake |
None |
Returns:
Type | Description |
---|---|
ListThreadsData |
a list of threads |
Source code in naff/api/http/http_client.py
async def list_public_archived_threads(
self, channel_id: "Snowflake_Type", limit: int = None, before: Optional["Snowflake_Type"] = None
) -> discord_typings.ListThreadsData:
"""
Get a list of archived public threads in a channel.
Args:
channel_id: The channel to get threads from
limit: Optional limit of threads to
before: Get threads before this snowflake
Returns:
a list of threads
"""
payload = {}
if limit:
payload["limit"] = limit
if before:
payload["before"] = timestamp_converter(before)
return await self.request(Route("GET", f"/channels/{channel_id}/threads/archived/public"), params=payload)
async
inherited
method
modify_webhook(self, webhook_id, name, avatar, channel_id, webhook_token)
¶
Modify a webhook.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str |
the default name of the webhook |
required |
avatar |
Any |
image for the default webhook avatar |
required |
channel_id |
Snowflake_Type |
the new channel id this webhook should be moved to |
required |
webhook_id |
Snowflake_Type |
The ID of the webhook to modify |
required |
webhook_token |
str |
The token for the webhook |
None |
Source code in naff/api/http/http_client.py
async def modify_webhook(
self,
webhook_id: "Snowflake_Type",
name: str,
avatar: Any,
channel_id: "Snowflake_Type",
webhook_token: str = None,
) -> discord_typings.WebhookData:
"""
Modify a webhook.
Args:
name: the default name of the webhook
avatar: image for the default webhook avatar
channel_id: the new channel id this webhook should be moved to
webhook_id: The ID of the webhook to modify
webhook_token: The token for the webhook
"""
endpoint = f"/webhooks/{webhook_id}{f'/{webhook_token}' if webhook_token else ''}"
return await self.request(
Route("PATCH", endpoint), payload={"name": name, "avatar": avatar, "channel_id": channel_id}
)
async
inherited
method
create_application_command(self, app_id, command, guild_id)
¶
Add a given command to scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app_id |
Snowflake_Type |
The application ID of this bot |
required |
command |
Dict |
A dictionary representing a command to be created |
required |
guild_id |
Snowflake_Type |
The ID of the guild this command is for, if this is a guild command |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.interactions.commands.ChatInputCommandData, discord_typings.interactions.commands.ContextMenuCommandData] |
An application command object |
Source code in naff/api/http/http_client.py
async def create_application_command(
self, app_id: "Snowflake_Type", command: Dict, guild_id: "Snowflake_Type"
) -> discord_typings.ApplicationCommandData:
"""
Add a given command to scope.
Args:
app_id: The application ID of this bot
command: A dictionary representing a command to be created
guild_id: The ID of the guild this command is for, if this is a guild command
Returns:
An application command object
"""
if guild_id == GLOBAL_SCOPE:
return await self.request(Route("POST", f"/applications/{app_id}/commands"), payload=command)
return await self.request(Route("POST", f"/applications/{app_id}/guilds/{guild_id}/commands"), payload=command)
async
inherited
method
create_group_dm(self, payload)
¶
Create a new group DM channel with multiple users.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The data to send. |
required |
Source code in naff/api/http/http_client.py
async def create_group_dm(self, payload: dict) -> discord_typings.GroupDMChannelData:
"""
Create a new group DM channel with multiple users.
Args:
payload: The data to send.
"""
return await self.request(Route("POST", "/users/@me/channels"), payload=payload)
async
inherited
method
pin_message(self, channel_id, message_id)
¶
Pin a message to a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
Channel to pin message to |
required |
message_id |
Snowflake_Type |
Message to pin |
required |
Source code in naff/api/http/http_client.py
async def pin_message(self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type") -> None:
"""
Pin a message to a channel.
Args:
channel_id: Channel to pin message to
message_id: Message to pin
"""
return await self.request(Route("PUT", f"/channels/{channel_id}/pins/{message_id}"))
async
inherited
method
clear_reaction(self, channel_id, message_id, emoji)
¶
Remove specific reaction from a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in. |
required |
message_id |
Snowflake_Type |
The message to remove the reaction on. |
required |
emoji |
str |
The emoji to remove. (format: |
required |
Source code in naff/api/http/http_client.py
async def clear_reaction(self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type", emoji: str) -> None:
"""
Remove specific reaction from a message.
Args:
channel_id: The channel this is taking place in.
message_id: The message to remove the reaction on.
emoji: The emoji to remove. (format: `name:id`)
"""
return await self.request(
Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
)
async
inherited
method
delete_guild_emoji(self, guild_id, emoji_id, reason)
¶
Delete a guild emoji.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
emoji_id |
Snowflake_Type |
The ID of the emoji to update |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this deletion |
Missing |
Source code in naff/api/http/http_client.py
async def delete_guild_emoji(
self, guild_id: "Snowflake_Type", emoji_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Delete a guild emoji.
Args:
guild_id: The ID of the guild
emoji_id: The ID of the emoji to update
reason: The reason for this deletion
"""
await self.request(Route("DELETE", f"/guilds/{guild_id}/emojis/{emoji_id}"), reason=reason)
async
inherited
method
get_roles(self, guild_id)
¶
Get a guild's roles.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild.RoleData] |
List of roles |
Source code in naff/api/http/http_client.py
async def get_roles(self, guild_id: "Snowflake_Type") -> List[discord_typings.RoleData]:
"""
Get a guild's roles.
Args:
guild_id: The ID of the guild
Returns:
List of roles
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/roles"))
async
inherited
method
get_user_connections(self)
¶
Returns a list of connection objects.
Requires the connections OAuth2 scope.
Source code in naff/api/http/http_client.py
async def get_user_connections(self) -> list:
"""
Returns a list of connection objects.
Requires the connections OAuth2 scope.
"""
return await self.request(Route("GET", "/users/@me/connections"))
async
inherited
method
modify_guild_sticker(self, payload, guild_id, sticker_id, reason)
¶
Modify the given sticker. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
the payload to send. |
required |
guild_id |
Snowflake_Type |
The guild of the target sticker. |
required |
sticker_id |
Snowflake_Type |
The sticker to modify. |
required |
reason |
Optional[str] |
The reason for this action. |
Missing |
Returns:
Type | Description |
---|---|
StickerData |
The updated sticker data on success. |
Source code in naff/api/http/http_client.py
async def modify_guild_sticker(
self, payload: dict, guild_id: "Snowflake_Type", sticker_id: "Snowflake_Type", reason: Optional[str] = MISSING
) -> discord_typings.StickerData:
"""
Modify the given sticker. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Args:
payload: the payload to send.
guild_id: The guild of the target sticker.
sticker_id: The sticker to modify.
reason: The reason for this action.
Returns:
The updated sticker data on success.
"""
return await self.request(
Route("PATCH", f"/guild/{guild_id}/stickers/{sticker_id}"), payload=payload, reason=reason
)
async
inherited
method
unpin_message(self, channel_id, message_id)
¶
Unpin a message to a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
Channel to unpin message to |
required |
message_id |
Snowflake_Type |
Message to unpin |
required |
Source code in naff/api/http/http_client.py
async def unpin_message(self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type") -> None:
"""
Unpin a message to a channel.
Args:
channel_id: Channel to unpin message to
message_id: Message to unpin
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}/pins/{message_id}"))
async
inherited
method
post_initial_response(self, payload, interaction_id, token, files)
¶
Post an initial response to an interaction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
the payload to send |
required |
interaction_id |
str |
the id of the interaction |
required |
token |
str |
the token of the interaction |
required |
files |
list['UPLOADABLE_TYPE'] | None |
The files to send in this message |
None |
Source code in naff/api/http/http_client.py
async def post_initial_response(
self, payload: dict, interaction_id: str, token: str, files: list["UPLOADABLE_TYPE"] | None = None
) -> None:
"""
Post an initial response to an interaction.
Args:
payload: the payload to send
interaction_id: the id of the interaction
token: the token of the interaction
files: The files to send in this message
"""
return await self.request(
Route("POST", f"/interactions/{interaction_id}/{token}/callback"), payload=payload, files=files
)
async
inherited
method
delete_scheduled_event(self, guild_id, scheduled_event_id, reason)
¶
Delete a scheduled event for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to delete scheduled event from |
required |
scheduled_event_id |
Snowflake_Type |
The scheduled event to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason to be displayed in audit logs |
Missing |
Source code in naff/api/http/http_client.py
async def delete_scheduled_event(
self,
guild_id: "Snowflake_Type",
scheduled_event_id: "Snowflake_Type",
reason: Absent[str] = MISSING,
) -> None:
"""
Delete a scheduled event for a guild.
Args:
guild_id: The guild to delete scheduled event from
scheduled_event_id: The scheduled event to delete
reason: The reason to be displayed in audit logs
"""
return await self.request(
Route("DELETE", f"/guilds/{guild_id}/scheduled-events/{scheduled_event_id}"), reason=reason
)
async
inherited
method
group_dm_add_recipient(self, channel_id, user_id, access_token, nick)
¶
Adds a recipient to a Group DM using their access token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the group dm |
required |
user_id |
Snowflake_Type |
The ID of the user to add |
required |
access_token |
str |
Access token of a user that has granted your app the gdm.join scope |
required |
nick |
str |
Nickname of the user being added |
None |
Source code in naff/api/http/http_client.py
async def group_dm_add_recipient(
self, channel_id: "Snowflake_Type", user_id: "Snowflake_Type", access_token: str, nick: str = None
) -> None:
"""
Adds a recipient to a Group DM using their access token.
Args:
channel_id: The ID of the group dm
user_id: The ID of the user to add
access_token: Access token of a user that has granted your app the gdm.join scope
nick: Nickname of the user being added
"""
return await self.request(
Route("PUT", f"/channels/{channel_id}/recipients/{user_id}"),
payload={"access_token": access_token, "nick": nick},
)
async
inherited
method
list_private_archived_threads(self, channel_id, limit, before)
¶
Get a list of archived private threads in a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel to get threads from |
required |
limit |
int |
Optional limit of threads to |
None |
before |
Optional[Snowflake_Type] |
Get threads before this snowflake |
None |
Returns:
Type | Description |
---|---|
ListThreadsData |
a list of threads |
Source code in naff/api/http/http_client.py
async def list_private_archived_threads(
self, channel_id: "Snowflake_Type", limit: int = None, before: Optional["Snowflake_Type"] = None
) -> discord_typings.ListThreadsData:
"""
Get a list of archived private threads in a channel.
Args:
channel_id: The channel to get threads from
limit: Optional limit of threads to
before: Get threads before this snowflake
Returns:
a list of threads
"""
payload = {}
if limit:
payload["limit"] = limit
if before:
payload["before"] = before
return await self.request(Route("GET", f"/channels/{channel_id}/threads/archived/private"), params=payload)
async
inherited
method
modify_guild(self, guild_id, reason, **kwargs)
¶
Modify a guild's attributes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild we want to modify |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this change |
Missing |
kwargs |
The params to change |
{} |
Source code in naff/api/http/http_client.py
async def modify_guild(self, guild_id: "Snowflake_Type", reason: Absent[str] = MISSING, **kwargs) -> None:
"""
Modify a guild's attributes.
Args:
guild_id: The ID of the guild we want to modify
reason: The reason for this change
kwargs: The params to change
"""
expected = (
"name",
"region",
"verification_level",
"default_message_notifications",
"explicit_content_filter",
"afk_channel_id",
"afk_timeout",
"icon",
"owner_id",
"splash",
"discovery_splash",
"banner",
"system_channel_id",
"system_channel_flags",
"rules_channel_id",
"public_updates_channel_id",
"preferred_locale",
"features",
"description",
)
kwargs_copy = kwargs.copy()
for key, value in kwargs.items():
if key not in expected or value is MISSING:
del kwargs_copy[key]
# only do the request if there is something to modify
if kwargs_copy:
await self.request(Route("PATCH", f"/guilds/{guild_id}"), payload=kwargs_copy, reason=reason)
async
inherited
method
delete_webhook(self, webhook_id, webhook_token)
¶
Delete a webhook.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to delete |
required |
webhook_token |
str |
The token for the webhook |
None |
Returns:
Type | Description |
---|---|
None |
Webhook object |
Source code in naff/api/http/http_client.py
async def delete_webhook(self, webhook_id: "Snowflake_Type", webhook_token: str = None) -> None:
"""
Delete a webhook.
Args:
webhook_id: The ID of the webhook to delete
webhook_token: The token for the webhook
Returns:
Webhook object
"""
endpoint = f"/webhooks/{webhook_id}{f'/{webhook_token}' if webhook_token else ''}"
return await self.request(Route("DELETE", endpoint))
async
inherited
method
clear_reactions(self, channel_id, message_id)
¶
Remove reactions from a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in. |
required |
message_id |
Snowflake_Type |
The message to clear reactions from. |
required |
Source code in naff/api/http/http_client.py
async def clear_reactions(self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type") -> None:
"""
Remove reactions from a message.
Args:
channel_id: The channel this is taking place in.
message_id: The message to clear reactions from.
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}/messages/{message_id}/reactions"))
async
inherited
method
edit_message(self, payload, channel_id, message_id, files)
¶
Edit an existing message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
required | |
channel_id |
Snowflake_Type |
Channel of message to edit. |
required |
message_id |
Snowflake_Type |
Message to edit. |
required |
files |
list['UPLOADABLE_TYPE'] | None |
Any files to send with this message |
None |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
Message object of edited message |
Source code in naff/api/http/http_client.py
async def edit_message(
self,
payload: dict,
channel_id: "Snowflake_Type",
message_id: "Snowflake_Type",
files: list["UPLOADABLE_TYPE"] | None = None,
) -> discord_typings.MessageData:
"""
Edit an existing message.
Args:
payload:
channel_id: Channel of message to edit.
message_id: Message to edit.
files: Any files to send with this message
Returns:
Message object of edited message
"""
return await self.request(
Route("PATCH", f"/channels/{channel_id}/messages/{message_id}"), payload=payload, files=files
)
async
inherited
method
modify_current_member(self, guild_id, nickname, reason)
¶
Modify attributes of the user
Parameters:
Name | Type | Description | Default |
---|---|---|---|
nickname |
Union[str, naff.client.const.Missing] |
The new nickname to apply |
Missing |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Source code in naff/api/http/http_client.py
async def modify_current_member(
self,
guild_id: "Snowflake_Type",
nickname: Absent[str] = MISSING,
reason: Absent[str] = MISSING,
) -> None:
"""
Modify attributes of the user
Args:
nickname: The new nickname to apply
reason: An optional reason for the audit log
"""
await self.request(
Route("PATCH", f"/guilds/{guild_id}/members/@me"),
payload={
"nick": nickname or None,
},
reason=reason,
)
async
inherited
method
delete_guild_sticker(self, guild_id, sticker_id, reason)
¶
Delete the given sticker. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild of the target sticker. |
required |
sticker_id |
Snowflake_Type |
The sticker to delete. |
required |
reason |
Optional[str] |
The reason for this action. |
Missing |
Returns:
Type | Description |
---|---|
None |
Returns 204 No Content on success. |
Source code in naff/api/http/http_client.py
async def delete_guild_sticker(
self, guild_id: "Snowflake_Type", sticker_id: "Snowflake_Type", reason: Optional[str] = MISSING
) -> None:
"""
Delete the given sticker. Requires the MANAGE_EMOJIS_AND_STICKERS permission.
Args:
guild_id: The guild of the target sticker.
sticker_id: The sticker to delete.
reason: The reason for this action.
Returns:
Returns 204 No Content on success.
"""
return await self.request(Route("DELETE", f"/guild/{guild_id}/stickers/{sticker_id}"), reason=reason)
async
inherited
method
post_followup(self, payload, application_id, token, files)
¶
Send a followup to an interaction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
the payload to send |
required |
application_id |
Snowflake_Type |
the id of the application |
required |
token |
str |
the token of the interaction |
required |
files |
list['UPLOADABLE_TYPE'] | None |
The files to send with this interaction |
None |
Source code in naff/api/http/http_client.py
async def post_followup(
self, payload: dict, application_id: "Snowflake_Type", token: str, files: list["UPLOADABLE_TYPE"] | None = None
) -> None:
"""
Send a followup to an interaction.
Args:
payload: the payload to send
application_id: the id of the application
token: the token of the interaction
files: The files to send with this interaction
"""
return await self.request(Route("POST", f"/webhooks/{application_id}/{token}"), payload=payload, files=files)
async
inherited
method
get_reactions(self, channel_id, message_id, emoji, limit, after)
¶
Gets specific reaction from a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel this is taking place in. |
required |
message_id |
Snowflake_Type |
The message to get the reaction. |
required |
emoji |
str |
The emoji to get. (format: |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.user.UserData] |
List of users who reacted with the emoji. |
Source code in naff/api/http/http_client.py
async def get_reactions(
self,
channel_id: "Snowflake_Type",
message_id: "Snowflake_Type",
emoji: str,
limit: Absent[int] = MISSING,
after: "Snowflake_Type" = MISSING,
) -> List[discord_typings.UserData]:
"""
Gets specific reaction from a message.
Args:
channel_id: The channel this is taking place in.
message_id: The message to get the reaction.
emoji: The emoji to get. (format: `name:id`)
Returns:
List of users who reacted with the emoji.
"""
return await self.request(
Route(
"GET",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
),
params={"limit": limit, "after": after},
)
async
inherited
method
group_dm_remove_recipient(self, channel_id, user_id)
¶
Remove a recipient from the group dm.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the group dm |
required |
user_id |
Snowflake_Type |
The ID of the user to remove |
required |
Source code in naff/api/http/http_client.py
async def group_dm_remove_recipient(self, channel_id: "Snowflake_Type", user_id: "Snowflake_Type") -> None:
"""
Remove a recipient from the group dm.
Args:
channel_id: The ID of the group dm
user_id: The ID of the user to remove
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}/recipients/{user_id}"))
async
inherited
method
get_scheduled_event_users(self, guild_id, scheduled_event_id, limit, with_member, before, after)
¶
Get the users for a scheduled event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to get scheduled event users from |
required |
scheduled_event_id |
Snowflake_Type |
The scheduled event to get users from |
required |
limit |
int |
how many users to receive from the event |
100 |
with_member |
bool |
include guild member data if it exists |
False |
before |
Snowflake_Type |
consider only users before given user id |
Missing |
after |
Snowflake_Type |
consider only users after given user id |
Missing |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild_scheduled_events.GuildScheduledEventUserData] |
List of Scheduled Event Users or None |
Source code in naff/api/http/http_client.py
async def get_scheduled_event_users(
self,
guild_id: "Snowflake_Type",
scheduled_event_id: "Snowflake_Type",
limit: int = 100,
with_member: bool = False,
before: "Snowflake_Type" = MISSING,
after: "Snowflake_Type" = MISSING,
) -> List[discord_typings.GuildScheduledEventUserData]:
"""
Get the users for a scheduled event.
Args:
guild_id: The guild to get scheduled event users from
scheduled_event_id: The scheduled event to get users from
limit: how many users to receive from the event
with_member: include guild member data if it exists
before: consider only users before given user id
after: consider only users after given user id
Returns:
List of Scheduled Event Users or None
"""
params = {"limit": limit, "with_member": with_member, "before": before, "after": after}
return await self.request(
Route("GET", f"/guilds/{guild_id}/scheduled-events/{scheduled_event_id}/users"),
params=params,
)
async
inherited
method
execute_webhook(self, webhook_id, webhook_token, payload, wait, thread_id, files)
¶
Execute a webhook. Basically send a message as the webhook.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to delete |
required |
webhook_token |
str |
The token for the webhook |
required |
payload |
dict |
The JSON payload for the message |
required |
wait |
bool |
Waits for server confirmation of message send before response |
False |
thread_id |
Snowflake_Type |
Send a message to the specified thread |
None |
suffix |
An optional suffix to add to the end of the endpoint address |
required | |
files |
list['UPLOADABLE_TYPE'] | None |
The files to send with this message |
None |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
The sent |
Source code in naff/api/http/http_client.py
async def execute_webhook(
self,
webhook_id: "Snowflake_Type",
webhook_token: str,
payload: dict,
wait: bool = False,
thread_id: "Snowflake_Type" = None,
files: list["UPLOADABLE_TYPE"] | None = None,
) -> Optional[discord_typings.MessageData]:
"""
Execute a webhook. Basically send a message as the webhook.
Args:
webhook_id: The ID of the webhook to delete
webhook_token: The token for the webhook
payload: The JSON payload for the message
wait: Waits for server confirmation of message send before response
thread_id: Send a message to the specified thread
suffix: An optional suffix to add to the end of the endpoint address
files: The files to send with this message
Returns:
The sent `message`, if `wait` is True else None
"""
return await self.request(
Route("POST", f"/webhooks/{webhook_id}/{webhook_token}"),
params=dict_filter_none({"wait": "true" if wait else "false", "thread_id": thread_id}),
payload=payload,
files=files,
)
async
inherited
method
list_joined_private_archived_threads(self, channel_id, limit, before)
¶
Get a list of archived private threads in a channel that you have joined.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel to get threads from |
required |
limit |
int |
Optional limit of threads to |
None |
before |
Optional[Snowflake_Type] |
Get threads before this snowflake |
None |
Returns:
Type | Description |
---|---|
ListThreadsData |
a list of threads |
Source code in naff/api/http/http_client.py
async def list_joined_private_archived_threads(
self, channel_id: "Snowflake_Type", limit: int = None, before: Optional["Snowflake_Type"] = None
) -> discord_typings.ListThreadsData:
"""
Get a list of archived private threads in a channel that you have joined.
Args:
channel_id: The channel to get threads from
limit: Optional limit of threads to
before: Get threads before this snowflake
Returns:
a list of threads
"""
payload = {}
if limit:
payload["limit"] = limit
if before:
payload["before"] = before
return await self.request(
Route("GET", f"/channels/{channel_id}/users/@me/threads/archived/private"), params=payload
)
async
inherited
method
modify_current_user_nick(self, guild_id, nickname)
¶
Modifies the nickname of the current user in a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
nickname |
str |
The new nickname to use |
None |
Source code in naff/api/http/http_client.py
async def modify_current_user_nick(self, guild_id: "Snowflake_Type", nickname: str = None) -> None:
"""
Modifies the nickname of the current user in a guild.
Args:
guild_id: The ID of the guild
nickname: The new nickname to use
"""
return await self.request(Route("PATCH", f"/guilds/{guild_id}/members/@me/nick"), payload={"nick": nickname})
async
inherited
method
edit_interaction_message(self, payload, application_id, token, message_id, files)
¶
Edits an existing interaction message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload |
dict |
The payload to send. |
required |
application_id |
Snowflake_Type |
The id of the application. |
required |
token |
str |
The token of the interaction. |
required |
message_id |
str |
The target message to edit. Defaults to @original which represents the initial response message. |
'@original' |
files |
list['UPLOADABLE_TYPE'] | None |
The files to send with this interaction |
None |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
The edited message data. |
Source code in naff/api/http/http_client.py
async def edit_interaction_message(
self,
payload: dict,
application_id: "Snowflake_Type",
token: str,
message_id: str = "@original",
files: list["UPLOADABLE_TYPE"] | None = None,
) -> discord_typings.MessageData:
"""
Edits an existing interaction message.
Args:
payload: The payload to send.
application_id: The id of the application.
token: The token of the interaction.
message_id: The target message to edit. Defaults to @original which represents the initial response message.
files: The files to send with this interaction
Returns:
The edited message data.
"""
return await self.request(
Route("PATCH", f"/webhooks/{application_id}/{token}/messages/{message_id}"), payload=payload, files=files
)
async
inherited
method
crosspost_message(self, channel_id, message_id)
¶
Crosspost a message in a News Channel to following channels.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
Channel the message is in |
required |
message_id |
Snowflake_Type |
The id of the message to crosspost |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
message object |
Source code in naff/api/http/http_client.py
async def crosspost_message(
self, channel_id: "Snowflake_Type", message_id: "Snowflake_Type"
) -> discord_typings.MessageData:
"""
Crosspost a message in a News Channel to following channels.
Args:
channel_id: Channel the message is in
message_id: The id of the message to crosspost
Returns:
message object
"""
return await self.request(Route("POST", f"/channels/{channel_id}/messages/{message_id}/crosspost"))
async
inherited
method
move_channel(self, guild_id, channel_id, new_pos, parent_id, lock_perms, reason)
¶
Move a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild this affects |
required |
channel_id |
Snowflake_Type |
The ID of the channel to move |
required |
new_pos |
int |
The new position of this channel |
required |
parent_id |
Snowflake_Type |
The parent ID if needed |
None |
lock_perms |
bool |
Sync permissions with the new parent |
False |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Source code in naff/api/http/http_client.py
async def move_channel(
self,
guild_id: "Snowflake_Type",
channel_id: "Snowflake_Type",
new_pos: int,
parent_id: "Snowflake_Type" = None,
lock_perms: bool = False,
reason: Absent[str] = MISSING,
) -> None:
"""
Move a channel.
Args:
guild_id: The ID of the guild this affects
channel_id: The ID of the channel to move
new_pos: The new position of this channel
parent_id: The parent ID if needed
lock_perms: Sync permissions with the new parent
reason: An optional reason for the audit log
"""
payload = {"id": channel_id, "position": new_pos, "lock_permissions": lock_perms}
if parent_id:
payload["parent_id"] = parent_id
return await self.request(Route("PATCH", f"/guilds/{guild_id}/channels"), payload=payload, reason=reason)
async
inherited
method
add_guild_member_role(self, guild_id, user_id, role_id, reason)
¶
Adds a role to a guild member.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
user_id |
Snowflake_Type |
The ID of the user |
required |
role_id |
Snowflake_Type |
The ID of the role to add |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def add_guild_member_role(
self,
guild_id: "Snowflake_Type",
user_id: "Snowflake_Type",
role_id: "Snowflake_Type",
reason: Absent[str] = MISSING,
) -> None:
"""
Adds a role to a guild member.
Args:
guild_id: The ID of the guild
user_id: The ID of the user
role_id: The ID of the role to add
reason: The reason for this action
"""
return await self.request(Route("PUT", f"/guilds/{guild_id}/members/{user_id}/roles/{role_id}"), reason=reason)
async
inherited
method
delete_guild(self, guild_id)
¶
Delete the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild that we want to delete |
required |
Source code in naff/api/http/http_client.py
async def delete_guild(self, guild_id: "Snowflake_Type") -> None:
"""
Delete the guild.
Args:
guild_id: The ID of the guild that we want to delete
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}"))
async
inherited
method
list_active_threads(self, guild_id)
¶
List active threads within a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
the guild id to get threads from |
required |
Returns:
Type | Description |
---|---|
ListThreadsData |
A list of active threads |
Source code in naff/api/http/http_client.py
async def list_active_threads(self, guild_id: "Snowflake_Type") -> discord_typings.ListThreadsData:
"""
List active threads within a guild.
Args:
guild_id: the guild id to get threads from
Returns:
A list of active threads
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/threads/active"))
async
inherited
method
get_webhook_message(self, webhook_id, webhook_token, message_id)
¶
Returns a previously-sent webhook message from the same token. Returns a message object on success.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to delete |
required |
webhook_token |
str |
The token for the webhook |
required |
message_id |
Snowflake_Type |
The ID of a message sent by this webhook |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
A message object on success |
Source code in naff/api/http/http_client.py
async def get_webhook_message(
self, webhook_id: "Snowflake_Type", webhook_token: str, message_id: "Snowflake_Type"
) -> discord_typings.MessageData:
"""
Returns a previously-sent webhook message from the same token. Returns a message object on success.
Args:
webhook_id: The ID of the webhook to delete
webhook_token: The token for the webhook
message_id: The ID of a message sent by this webhook
Returns:
A message object on success
"""
return await self.request(Route("GET", f"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}"))
async
inherited
method
add_guild_member(self, guild_id, user_id, access_token, nick, roles, mute, deaf)
¶
Add a user to the guild. All parameters to this endpoint except for access_token
, guild_id
and user_id
are optional.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
user_id |
Snowflake_Type |
The ID of the user to add |
required |
access_token |
str |
The access token of the user |
required |
nick |
str |
value to set users nickname to |
None |
roles |
List[Snowflake_Type] |
array of role ids the member is assigned |
None |
mute |
bool |
whether the user is muted in voice channels |
False |
deaf |
bool |
whether the user is deafened in voice channels |
False |
Returns:
Type | Description |
---|---|
GuildMemberData |
Guild Member Object |
Source code in naff/api/http/http_client.py
async def add_guild_member(
self,
guild_id: "Snowflake_Type",
user_id: "Snowflake_Type",
access_token: str,
nick: str = None,
roles: List["Snowflake_Type"] = None,
mute: bool = False,
deaf: bool = False,
) -> discord_typings.GuildMemberData:
"""
Add a user to the guild. All parameters to this endpoint except for `access_token`, `guild_id` and `user_id` are optional.
Args:
guild_id: The ID of the guild
user_id: The ID of the user to add
access_token: The access token of the user
nick: value to set users nickname to
roles: array of role ids the member is assigned
mute: whether the user is muted in voice channels
deaf: whether the user is deafened in voice channels
Returns:
Guild Member Object
"""
return await self.request(
Route("PUT", f"/guilds/{guild_id}/members/{user_id}"),
payload=dict_filter_none(
{"access_token": access_token, "nick": nick, "roles": roles, "mute": mute, "deaf": deaf}
),
)
async
inherited
method
remove_guild_member_role(self, guild_id, user_id, role_id, reason)
¶
Remove a role from a guild member.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
user_id |
Snowflake_Type |
The ID of the user |
required |
role_id |
Snowflake_Type |
The ID of the role to remove |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def remove_guild_member_role(
self,
guild_id: "Snowflake_Type",
user_id: "Snowflake_Type",
role_id: "Snowflake_Type",
reason: Absent[str] = MISSING,
) -> None:
"""
Remove a role from a guild member.
Args:
guild_id: The ID of the guild
user_id: The ID of the user
role_id: The ID of the role to remove
reason: The reason for this action
"""
return await self.request(
Route("DELETE", f"/guilds/{guild_id}/members/{user_id}/roles/{role_id}"), reason=reason
)
async
inherited
method
get_interaction_message(self, application_id, token, message_id)
¶
Gets an existing interaction message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
str |
The id of the application. |
required |
token |
str |
The token of the interaction. |
required |
message_id |
str |
The target message to get. Defaults to @original which represents the initial response message. |
'@original' |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
The message data. |
Source code in naff/api/http/http_client.py
async def get_interaction_message(
self, application_id: str, token: str, message_id: str = "@original"
) -> discord_typings.MessageData:
"""
Gets an existing interaction message.
Args:
application_id: The id of the application.
token: The token of the interaction.
message_id: The target message to get. Defaults to @original which represents the initial response message.
Returns:
The message data.
"""
return await self.request(Route("GET", f"/webhooks/{application_id}/{token}/messages/{message_id}"))
async
inherited
method
modify_channel(self, channel_id, data, reason)
¶
Update a channel's settings, returns the updated channel object on success.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to update |
required |
data |
dict |
The data to update with |
required |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.TextChannelData, discord_typings.resources.channel.NewsChannelData, discord_typings.resources.channel.DMChannelData, discord_typings.resources.channel.GroupDMChannelData, discord_typings.resources.channel.ThreadChannelData, discord_typings.resources.channel.VoiceChannelData, discord_typings.resources.channel.CategoryChannelData] |
Channel object on success |
Source code in naff/api/http/http_client.py
async def modify_channel(
self, channel_id: "Snowflake_Type", data: dict, reason: Absent[str] = MISSING
) -> discord_typings.ChannelData:
"""
Update a channel's settings, returns the updated channel object on success.
Args:
channel_id: The ID of the channel to update
data: The data to update with
reason: An optional reason for the audit log
Returns:
Channel object on success
"""
return await self.request(Route("PATCH", f"/channels/{channel_id}"), payload=data, reason=reason)
async
inherited
method
create_thread(self, channel_id, name, auto_archive_duration, thread_type, invitable, message_id, reason)
¶
Create a thread in the given channel. Can either create a thread with or without a message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to create this thread in |
required |
name |
str |
The name of the thread |
required |
auto_archive_duration |
int |
duration in minutes to automatically archive the thread after recent activity, |
required |
can |
be set to |
60, 1440, 4320, 10080 |
required |
thread_type |
Union[int, naff.client.const.Missing] |
The type of thread, defaults to public. ignored if creating thread from a message |
Missing |
invitable |
Union[bool, naff.client.const.Missing] |
Missing |
|
message_id |
Union[Snowflake_Type, naff.client.const.Missing] |
An optional message to create a thread from. |
Missing |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Returns:
Type | Description |
---|---|
ThreadChannelData |
The created thread |
Source code in naff/api/http/http_client.py
async def create_thread(
self,
channel_id: "Snowflake_Type",
name: str,
auto_archive_duration: int,
thread_type: Absent[int] = MISSING,
invitable: Absent[bool] = MISSING,
message_id: Absent["Snowflake_Type"] = MISSING,
reason: Absent[str] = MISSING,
) -> discord_typings.ThreadChannelData:
"""
Create a thread in the given channel. Can either create a thread with or without a message.
Args:
channel_id: The ID of the channel to create this thread in
name: The name of the thread
auto_archive_duration: duration in minutes to automatically archive the thread after recent activity,
can be set to: 60, 1440, 4320, 10080
thread_type: The type of thread, defaults to public. ignored if creating thread from a message
invitable:
message_id: An optional message to create a thread from.
reason: An optional reason for the audit log
Returns:
The created thread
"""
payload = {"name": name, "auto_archive_duration": auto_archive_duration}
if message_id:
return await self.request(
Route("POST", f"/channels/{channel_id}/messages/{message_id}/threads"), payload=payload, reason=reason
)
else:
payload["type"] = thread_type or ChannelTypes.GUILD_PUBLIC_THREAD
payload["invitable"] = invitable
return await self.request(Route("POST", f"/channels/{channel_id}/threads"), payload=payload, reason=reason)
method
get_ratelimit(self, route)
¶
Get a route's rate limit bucket.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
route |
Route |
The route to fetch the ratelimit bucket for |
required |
Returns:
Type | Description |
---|---|
BucketLock |
The BucketLock object for this route |
Source code in naff/api/http/http_client.py
def get_ratelimit(self, route: Route) -> BucketLock:
"""
Get a route's rate limit bucket.
Args:
route: The route to fetch the ratelimit bucket for
Returns:
The BucketLock object for this route
"""
if bucket_hash := self._endpoints.get(route.rl_bucket):
# we have seen this route before, we know which bucket it is associated with
lock = self.ratelimit_locks.get(bucket_hash)
if lock:
# if we have an active lock on this route, it'll still be in the cache
# return that lock
return lock
# if no cached lock exists, return a new lock
return BucketLock()
async
inherited
method
edit_webhook_message(self, webhook_id, webhook_token, message_id, payload, files)
¶
Edits a previously-sent webhook message from the same token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to delete |
required |
webhook_token |
str |
The token for the webhook |
required |
message_id |
Snowflake_Type |
The ID of a message sent by this webhook |
required |
payload |
dict |
The JSON payload for the message |
required |
files |
None | list['UPLOADABLE_TYPE'] |
The files to send in this message |
None |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData] |
The updated message on success |
Source code in naff/api/http/http_client.py
async def edit_webhook_message(
self,
webhook_id: "Snowflake_Type",
webhook_token: str,
message_id: "Snowflake_Type",
payload: dict,
files: None | list["UPLOADABLE_TYPE"] = None,
) -> discord_typings.MessageData:
"""
Edits a previously-sent webhook message from the same token.
Args:
webhook_id: The ID of the webhook to delete
webhook_token: The token for the webhook
message_id: The ID of a message sent by this webhook
payload: The JSON payload for the message
files: The files to send in this message
Returns:
The updated message on success
"""
return await self.request(
Route("PATCH", f"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}"),
payload=payload,
files=files,
)
async
inherited
method
edit_application_command_permissions(self, application_id, scope, cmd_id, permissions)
¶
Edits command permissions for a specific command.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
Snowflake_Type |
the id of the application |
required |
scope |
Snowflake_Type |
The scope this command is in |
required |
cmd_id |
Snowflake_Type |
The command id to edit |
required |
permissions |
List[dict] |
The permissions to set to this command |
required |
Returns:
Type | Description |
---|---|
ApplicationCommandPermissionsData |
Guild Application Command Permissions |
Source code in naff/api/http/http_client.py
async def edit_application_command_permissions(
self,
application_id: "Snowflake_Type",
scope: "Snowflake_Type",
cmd_id: "Snowflake_Type",
permissions: List[dict],
) -> discord_typings.ApplicationCommandPermissionsData:
"""
Edits command permissions for a specific command.
Args:
application_id: the id of the application
scope: The scope this command is in
cmd_id: The command id to edit
permissions: The permissions to set to this command
Returns:
Guild Application Command Permissions
"""
return await self.request(
Route("PUT", f"/applications/{application_id}/guilds/{scope}/commands/{cmd_id}/permissions"),
payload=permissions,
)
async
inherited
method
delete_channel(self, channel_id, reason)
¶
Delete the channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Source code in naff/api/http/http_client.py
async def delete_channel(self, channel_id: "Snowflake_Type", reason: Absent[str] = MISSING) -> None:
"""
Delete the channel.
Args:
channel_id: The ID of the channel to delete
reason: An optional reason for the audit log
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}"), reason=reason)
method
ingest_ratelimit(self, route, header, bucket_lock)
¶
Ingests a ratelimit header from discord to determine ratelimit.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
route |
Route |
The route we're ingesting ratelimit for |
required |
header |
CIMultiDictProxy |
The rate limit header in question |
required |
bucket_lock |
BucketLock |
The rate limit bucket for this route |
required |
Source code in naff/api/http/http_client.py
def ingest_ratelimit(self, route: Route, header: CIMultiDictProxy, bucket_lock: BucketLock) -> None:
"""
Ingests a ratelimit header from discord to determine ratelimit.
Args:
route: The route we're ingesting ratelimit for
header: The rate limit header in question
bucket_lock: The rate limit bucket for this route
"""
bucket_lock.ingest_ratelimit_header(header)
if bucket_lock.bucket_hash:
# We only ever try and cache the bucket if the bucket hash has been set (ignores unlimited endpoints)
logger.debug(f"Caching ingested rate limit data for: {bucket_lock.bucket_hash}")
self._endpoints[route.rl_bucket] = bucket_lock.bucket_hash
self.ratelimit_locks[bucket_lock.bucket_hash] = bucket_lock
async
inherited
method
remove_guild_member(self, guild_id, user_id, reason)
¶
Remove a member from a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
user_id |
Snowflake_Type |
The ID of the user to remove |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def remove_guild_member(
self, guild_id: "Snowflake_Type", user_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Remove a member from a guild.
Args:
guild_id: The ID of the guild
user_id: The ID of the user to remove
reason: The reason for this action
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}/members/{user_id}"), reason=reason)
async
inherited
method
get_channel_invites(self, channel_id)
¶
Get the invites for the channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to retrieve from |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.invite.InviteData] |
List of invite objects |
Source code in naff/api/http/http_client.py
async def get_channel_invites(self, channel_id: "Snowflake_Type") -> List[discord_typings.InviteData]:
"""
Get the invites for the channel.
Args:
channel_id: The ID of the channel to retrieve from
Returns:
List of invite objects
"""
return await self.request(Route("GET", f"/channels/{channel_id}/invites"))
async
inherited
method
create_forum_thread(self, channel_id, name, auto_archive_duration, message, applied_tags, rate_limit_per_user, files, reason)
¶
Create a thread within a forum channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the forum channel |
required |
name |
str |
The name of the thread |
required |
auto_archive_duration |
int |
Time before the thread will be automatically archived. Note 3 day and 7 day archive durations require the server to be boosted. |
required |
message |
dict | aiohttp.formdata.FormData |
The message-content for the post/thread |
required |
rate_limit_per_user |
Union[int, naff.client.const.Missing] |
The time users must wait between sending messages |
Missing |
reason |
Union[str, naff.client.const.Missing] |
The reason for creating this thread |
Missing |
Returns:
Type | Description |
---|---|
dict |
The created thread object |
Source code in naff/api/http/http_client.py
async def create_forum_thread(
self,
channel_id: "Snowflake_Type",
name: str,
auto_archive_duration: int,
message: dict | FormData,
applied_tags: List[str] = None,
rate_limit_per_user: Absent[int] = MISSING,
files: Absent["UPLOADABLE_TYPE"] = MISSING,
reason: Absent[str] = MISSING,
) -> dict:
"""
Create a thread within a forum channel.
Args:
channel_id: The id of the forum channel
name: The name of the thread
auto_archive_duration: Time before the thread will be automatically archived. Note 3 day and 7 day archive durations require the server to be boosted.
message: The message-content for the post/thread
rate_limit_per_user: The time users must wait between sending messages
reason: The reason for creating this thread
Returns:
The created thread object
"""
# note: `{"use_nested_fields": 1}` seems to be a temporary flag until forums launch
return await self.request(
Route("POST", f"/channels/{channel_id}/threads"),
payload={
"name": name,
"auto_archive_duration": auto_archive_duration,
"rate_limit_per_user": rate_limit_per_user,
"applied_tags": applied_tags,
"message": message,
},
params={"use_nested_fields": 1},
files=files,
reason=reason,
)
async
inherited
method
delete_webhook_message(self, webhook_id, webhook_token, message_id)
¶
Delete a message that was created by the same token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
webhook_id |
Snowflake_Type |
The ID of the webhook to delete |
required |
webhook_token |
str |
The token for the webhook |
required |
message_id |
Snowflake_Type |
The ID of a message sent by this webhook |
required |
Source code in naff/api/http/http_client.py
async def delete_webhook_message(
self, webhook_id: "Snowflake_Type", webhook_token: str, message_id: "Snowflake_Type"
) -> None:
"""
Delete a message that was created by the same token.
Args:
webhook_id: The ID of the webhook to delete
webhook_token: The token for the webhook
message_id: The ID of a message sent by this webhook
"""
return await self.request(Route("DELETE", f"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}"))
async
inherited
method
get_application_command_permissions(self, application_id, scope, cmd_id)
¶
Get permission data for a command.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
Snowflake_Type |
the id of the application |
required |
scope |
Snowflake_Type |
The scope this command is in |
required |
cmd_id |
Snowflake_Type |
The command id to edit |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.interactions.commands.ApplicationCommandPermissionsData] |
guild application command permissions |
Source code in naff/api/http/http_client.py
async def get_application_command_permissions(
self, application_id: "Snowflake_Type", scope: "Snowflake_Type", cmd_id: "Snowflake_Type"
) -> List[discord_typings.ApplicationCommandPermissionsData]:
"""
Get permission data for a command.
Args:
application_id: the id of the application
scope: The scope this command is in
cmd_id: The command id to edit
Returns:
guild application command permissions
"""
return await self.request(
Route("GET", f"/applications/{application_id}/guilds/{scope}/commands/{cmd_id}/permissions")
)
async
inherited
method
get_guild_bans(self, guild_id, before, after, limit)
¶
Return a list of ban objects for the users banned from this guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild.BanData] |
List of ban objects |
Source code in naff/api/http/http_client.py
async def get_guild_bans(
self,
guild_id: "Snowflake_Type",
before: Absent["Snowflake_Type"] = MISSING,
after: Absent["Snowflake_Type"] = MISSING,
limit: int = 1000,
) -> List[discord_typings.BanData]:
"""
Return a list of ban objects for the users banned from this guild.
Args:
guild_id: The ID of the guild to query
Returns:
List of ban objects
"""
params = {
"limit": limit,
"before": before,
"after": after,
}
return await self.request(Route("GET", f"/guilds/{guild_id}/bans"), params=params)
async
inherited
method
create_channel_invite(self, channel_id, max_age, max_uses, temporary, unique, target_type, target_user_id, target_application_id, reason)
¶
Create an invite for the given channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to create an invite for |
required |
max_age |
int |
duration of invite in seconds before expiry, or 0 for never. between 0 and 604800 (7 days) (default 24 hours) |
86400 |
max_uses |
int |
max number of uses or 0 for unlimited. between 0 and 100 |
0 |
temporary |
bool |
whether this invite only grants temporary membership |
False |
unique |
bool |
if true, don't try to reuse a similar invite (useful for creating many unique one time use invites) |
False |
target_type |
int |
the type of target for this voice channel invite |
None |
target_user_id |
Snowflake_Type |
the id of the user whose stream to display for this invite, required if target_type is 1, the user must be streaming in the channel |
None |
target_application_id |
Snowflake_Type |
the id of the embedded application to open for this invite, required if target_type is 2, the application must have the EMBEDDED flag |
None |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Returns:
Type | Description |
---|---|
InviteData |
an invite object |
Source code in naff/api/http/http_client.py
async def create_channel_invite(
self,
channel_id: "Snowflake_Type",
max_age: int = 86400,
max_uses: int = 0,
temporary: bool = False,
unique: bool = False,
target_type: int = None,
target_user_id: "Snowflake_Type" = None,
target_application_id: "Snowflake_Type" = None,
reason: Absent[str] = MISSING,
) -> discord_typings.InviteData:
"""
Create an invite for the given channel.
Args:
channel_id: The ID of the channel to create an invite for
max_age: duration of invite in seconds before expiry, or 0 for never. between 0 and 604800 (7 days) (default 24 hours)
max_uses: max number of uses or 0 for unlimited. between 0 and 100
temporary: whether this invite only grants temporary membership
unique: if true, don't try to reuse a similar invite (useful for creating many unique one time use invites)
target_type: the type of target for this voice channel invite
target_user_id: the id of the user whose stream to display for this invite, required if target_type is 1, the user must be streaming in the channel
target_application_id: the id of the embedded application to open for this invite, required if target_type is 2, the application must have the EMBEDDED flag
reason: An optional reason for the audit log
Returns:
an invite object
"""
payload = {"max_age": max_age, "max_uses": max_uses, "temporary": temporary, "unique": unique}
if target_type:
payload["target_type"] = target_type
if target_user_id:
payload["target_user_id"] = target_user_id
if target_application_id:
payload["target_application_id"] = target_application_id
return await self.request(Route("POST", f"/channels/{channel_id}/invites"), payload=payload, reason=reason)
async
inherited
method
batch_get_application_command_permissions(self, application_id, scope)
¶
Get permission data for all commands in a scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
application_id |
Snowflake_Type |
the id of the application |
required |
scope |
Snowflake_Type |
The scope this command is in |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.interactions.commands.ApplicationCommandPermissionsData] |
list of guild application command permissions |
Source code in naff/api/http/http_client.py
async def batch_get_application_command_permissions(
self, application_id: "Snowflake_Type", scope: "Snowflake_Type"
) -> List[discord_typings.ApplicationCommandPermissionsData]:
"""
Get permission data for all commands in a scope.
Args:
application_id: the id of the application
scope: The scope this command is in
Returns:
list of guild application command permissions
"""
return await self.request(Route("GET", f"/applications/{application_id}/guilds/{scope}/commands/permissions"))
async
inherited
method
get_guild_ban(self, guild_id, user_id)
¶
Returns a ban object for the given user or a 404 not found if the ban cannot be found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
user_id |
Snowflake_Type |
The ID of the user to query |
required |
Returns:
Type | Description |
---|---|
Optional[discord_typings.resources.guild.BanData] |
Ban object if exists |
Exceptions:
Type | Description |
---|---|
NotFound |
if no ban exists |
Source code in naff/api/http/http_client.py
async def get_guild_ban(
self, guild_id: "Snowflake_Type", user_id: "Snowflake_Type"
) -> Optional[discord_typings.BanData]:
"""
Returns a ban object for the given user or a 404 not found if the ban cannot be found.
Args:
guild_id: The ID of the guild to query
user_id: The ID of the user to query
Returns:
Ban object if exists
Raises:
NotFound: if no ban exists
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/bans/{user_id}"))
async
method
request(self, route, payload, files, reason, params, **kwargs)
¶
Make a request to discord.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
route |
Route |
The route to take |
required |
payload |
Union[dict, naff.client.const.Missing] |
The payload for this request |
Missing |
files |
Union[list[Union[naff.models.discord.file.File, io.IOBase, BinaryIO, pathlib.Path, str]], naff.client.const.Missing] |
The files to send with this request |
Missing |
reason |
Union[str, naff.client.const.Missing] |
Attach a reason to this request, used for audit logs |
Missing |
Source code in naff/api/http/http_client.py
async def request(
self,
route: Route,
payload: Absent[dict] = MISSING,
files: Absent[list[UPLOADABLE_TYPE]] = MISSING,
reason: Absent[str] = MISSING,
params: Absent[dict] = MISSING,
**kwargs: dict,
) -> Any:
"""
Make a request to discord.
Args:
route: The route to take
payload: The payload for this request
files: The files to send with this request
reason: Attach a reason to this request, used for audit logs
"""
# Assemble headers
kwargs["headers"] = {"User-Agent": self.user_agent}
if self.token:
kwargs["headers"]["Authorization"] = f"Bot {self.token}"
if reason not in (None, MISSING):
kwargs["headers"]["X-Audit-Log-Reason"] = _uriquote(reason, safe="/ ")
if isinstance(payload, (list, dict)) and not files:
kwargs["headers"]["Content-Type"] = "application/json"
if isinstance(params, dict):
kwargs["params"] = dict_filter(params)
lock = self.get_ratelimit(route)
# this gets a BucketLock for this route.
# If this endpoint has been used before, it will get an existing ratelimit for the respective buckethash
# otherwise a brand-new bucket lock will be returned
for attempt in range(self._max_attempts):
async with lock:
try:
await self.global_lock.rate_limit()
# prevent us exceeding the global rate limit by throttling http requests
if self.__session.closed:
await self.login(self.token)
processed_data = self._process_payload(payload, files)
if isinstance(processed_data, FormData):
kwargs["data"] = processed_data
else:
kwargs["json"] = processed_data
async with self.__session.request(route.method, route.url, **kwargs) as response:
result = await response_decode(response)
self.ingest_ratelimit(route, response.headers, lock)
if response.status == 429:
# ratelimit exceeded
if result.get("global", False):
# global ratelimit is reached
# if we get a global, that's pretty bad, this would usually happen if the user is hitting the api from 2 clients sharing a token
logger.error(
f"Bot has exceeded global ratelimit, locking REST API for {result.get('retry_after')} seconds"
)
await self.global_lock.lock(float(result.get("retry_after")))
continue
elif result.get("message") == "The resource is being rate limited.":
# resource ratelimit is reached
logger.warning(
f"{route.endpoint} The resource is being rate limited! "
f"Reset in {result.get('retry_after')} seconds"
)
# lock this resource and wait for unlock
await lock.defer_unlock(float(result.get("retry_after")))
continue
else:
# endpoint ratelimit is reached
# 429's are unfortunately unavoidable, but we can attempt to avoid them
# so long as these are infrequent we're doing well
logger.warning(
f"{route.endpoint} Has exceeded it's ratelimit ({lock.limit})! Reset in {lock.delta} seconds"
)
await lock.defer_unlock() # lock this route and wait for unlock
continue
elif lock.remaining == 0:
# Last call available in the bucket, lock until reset
logger.debug(
f"{route.endpoint} Has exhausted its ratelimit ({lock.limit})! Locking route for {lock.delta} seconds"
)
await lock.blind_defer_unlock() # lock this route, but continue processing the current response
elif response.status in {500, 502, 504}:
# Server issues, retry
logger.warning(
f"{route.endpoint} Received {response.status}... retrying in {1 + attempt * 2} seconds"
)
await asyncio.sleep(1 + attempt * 2)
continue
if not 300 > response.status >= 200:
await self._raise_exception(response, route, result)
logger.debug(
f"{route.endpoint} Received {response.status} :: [{lock.remaining}/{lock.limit} calls remaining]"
)
return result
except OSError as e:
if attempt < self._max_attempts - 1 and e.errno in (54, 10054):
await asyncio.sleep(1 + attempt * 2)
continue
raise
async
inherited
method
get_invite(self, invite_code, with_counts, with_expiration, scheduled_event_id)
¶
Get an invite object for a given code.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
invite_code |
str |
The code of the invite |
required |
with_counts |
bool |
whether the invite should contain approximate member counts |
False |
with_expiration |
bool |
whether the invite should contain the expiration date |
True |
scheduled_event_id |
Snowflake_Type |
the guild scheduled event to include with the invite |
None |
Returns:
Type | Description |
---|---|
InviteData |
an invite object |
Source code in naff/api/http/http_client.py
async def get_invite(
self,
invite_code: str,
with_counts: bool = False,
with_expiration: bool = True,
scheduled_event_id: "Snowflake_Type" = None,
) -> discord_typings.InviteData:
"""
Get an invite object for a given code.
Args:
invite_code: The code of the invite
with_counts: whether the invite should contain approximate member counts
with_expiration: whether the invite should contain the expiration date
scheduled_event_id: the guild scheduled event to include with the invite
Returns:
an invite object
"""
params = dict_filter_none(
{
"with_counts": with_counts,
"with_expiration": with_expiration,
"guild_scheduled_event_id": scheduled_event_id,
}
)
return await self.request(Route("GET", f"/invites/{invite_code}", params=params))
async
inherited
method
create_guild_ban(self, guild_id, user_id, delete_message_days, reason)
¶
Create a guild ban, and optionally delete previous messages sent by the banned user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to create the ban in |
required |
user_id |
Snowflake_Type |
The ID of the user to ban |
required |
delete_message_days |
int |
number of days to delete messages for (0-7) |
0 |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def create_guild_ban(
self,
guild_id: "Snowflake_Type",
user_id: "Snowflake_Type",
delete_message_days: int = 0,
reason: Absent[str] = MISSING,
) -> None:
"""
Create a guild ban, and optionally delete previous messages sent by the banned user.
Args:
guild_id: The ID of the guild to create the ban in
user_id: The ID of the user to ban
delete_message_days: number of days to delete messages for (0-7)
reason: The reason for this action
"""
return await self.request(
Route("PUT", f"/guilds/{guild_id}/bans/{user_id}"),
payload={"delete_message_days": delete_message_days},
reason=reason,
)
async
inherited
method
remove_guild_ban(self, guild_id, user_id, reason)
¶
Remove a guild ban.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to remove the ban in |
required |
user_id |
Snowflake_Type |
The ID of the user to unban |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def remove_guild_ban(
self, guild_id: "Snowflake_Type", user_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Remove a guild ban.
Args:
guild_id: The ID of the guild to remove the ban in
user_id: The ID of the user to unban
reason: The reason for this action
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}/bans/{user_id}"), reason=reason)
async
inherited
method
delete_invite(self, invite_code, reason)
¶
Delete an invite.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
invite_code |
str |
The code of the invite to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason to delete the invite |
Missing |
Returns:
Type | Description |
---|---|
InviteData |
The deleted invite object |
Source code in naff/api/http/http_client.py
async def delete_invite(self, invite_code: str, reason: Absent[str] = MISSING) -> discord_typings.InviteData:
"""
Delete an invite.
Args:
invite_code: The code of the invite to delete
reason: The reason to delete the invite
Returns:
The deleted invite object
"""
return await self.request(Route("DELETE", f"/invites/{invite_code}"), reason=reason)
async
inherited
method
get_guild_prune_count(self, guild_id, days, include_roles)
¶
Returns an object with one 'pruned' key indicating the number of members that would be removed in a prune operation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
days |
int |
number of days to count prune for (1-30) |
7 |
include_roles |
List[Snowflake_Type] |
role(s) to include |
None |
Returns:
Type | Description |
---|---|
{"pruned" |
int} |
Source code in naff/api/http/http_client.py
async def get_guild_prune_count(
self, guild_id: "Snowflake_Type", days: int = 7, include_roles: List["Snowflake_Type"] = None
) -> dict:
"""
Returns an object with one 'pruned' key indicating the number of members that would be removed in a prune operation.
Args:
guild_id: The ID of the guild to query
days: number of days to count prune for (1-30)
include_roles: role(s) to include
Returns:
{"pruned": int}
"""
payload = {"days": days}
if include_roles:
payload["include_roles"] = ", ".join(include_roles)
return await self.request(Route("GET", f"/guilds/{guild_id}/prune"), params=payload)
async
inherited
method
edit_channel_permission(self, channel_id, overwrite_id, allow, deny, perm_type, reason)
¶
Edit the channel permission overwrites for a user or role in a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel |
required |
overwrite_id |
Snowflake_Type |
The id of the object to override |
required |
allow |
Union[Permissions, int] |
the bitwise value of all allowed permissions |
required |
deny |
Union[Permissions, int] |
the bitwise value of all disallowed permissions |
required |
perm_type |
Union[OverwriteTypes, int] |
0 for a role or 1 for a member |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Source code in naff/api/http/http_client.py
async def edit_channel_permission(
self,
channel_id: "Snowflake_Type",
overwrite_id: "Snowflake_Type",
allow: Union["Permissions", int],
deny: Union["Permissions", int],
perm_type: Union["OverwriteTypes", int],
reason: Absent[str] = MISSING,
) -> None:
"""
Edit the channel permission overwrites for a user or role in a channel.
Args:
channel_id: The id of the channel
overwrite_id: The id of the object to override
allow: the bitwise value of all allowed permissions
deny: the bitwise value of all disallowed permissions
perm_type: 0 for a role or 1 for a member
reason: The reason for this action
"""
return await self.request(
Route("PUT", f"/channels/{channel_id}/permissions/{overwrite_id}"),
payload={"allow": allow, "deny": deny, "type": perm_type},
reason=reason,
)
async
inherited
method
begin_guild_prune(self, guild_id, days, include_roles, compute_prune_count, reason)
¶
Begin a prune operation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
days |
int |
number of days to count prune for (1-30) |
7 |
include_roles |
Optional[List[Snowflake_Type]] |
role(s) to include |
None |
compute_prune_count |
bool |
whether 'pruned' is returned, discouraged for large guilds |
True |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Returns:
Type | Description |
---|---|
{"pruned" |
Optional[int]} |
Source code in naff/api/http/http_client.py
async def begin_guild_prune(
self,
guild_id: "Snowflake_Type",
days: int = 7,
include_roles: Optional[List["Snowflake_Type"]] = None,
compute_prune_count: bool = True,
reason: Absent[str] = MISSING,
) -> dict:
"""
Begin a prune operation.
Args:
guild_id: The ID of the guild to query
days: number of days to count prune for (1-30)
include_roles: role(s) to include
compute_prune_count: whether 'pruned' is returned, discouraged for large guilds
reason: The reason for this action
Returns:
{"pruned": Optional[int]}
"""
payload = {"days": days, "compute_prune_count": compute_prune_count}
if include_roles:
payload["include_roles"] = ", ".join(include_roles)
return await self.request(Route("POST", f"/guilds/{guild_id}/prune"), payload=payload, reason=reason)
async
inherited
method
delete_channel_permission(self, channel_id, overwrite_id, reason)
¶
Delete a channel permission overwrite for a user or role in a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel. |
required |
overwrite_id |
int |
The ID of the overwrite |
required |
reason |
Union[str, naff.client.const.Missing] |
An optional reason for the audit log |
Missing |
Source code in naff/api/http/http_client.py
async def delete_channel_permission(
self, channel_id: "Snowflake_Type", overwrite_id: int, reason: Absent[str] = MISSING
) -> None:
"""
Delete a channel permission overwrite for a user or role in a channel.
Args:
channel_id: The ID of the channel.
overwrite_id: The ID of the overwrite
reason: An optional reason for the audit log
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}/{overwrite_id}"), reason=reason)
async
inherited
method
follow_news_channel(self, channel_id, webhook_channel_id)
¶
Follow a news channel to send messages to the target channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The channel to follow |
required |
webhook_channel_id |
Snowflake_Type |
ID of the target channel |
required |
Returns:
Type | Description |
---|---|
FollowedChannelData |
Followed channel object |
Source code in naff/api/http/http_client.py
async def follow_news_channel(
self, channel_id: "Snowflake_Type", webhook_channel_id: "Snowflake_Type"
) -> discord_typings.FollowedChannelData:
"""
Follow a news channel to send messages to the target channel.
Args:
channel_id: The channel to follow
webhook_channel_id: ID of the target channel
Returns:
Followed channel object
"""
return await self.request(
Route("POST", f"/channels/{channel_id}/followers"), payload={"webhook_channel_id": webhook_channel_id}
)
async
inherited
method
get_guild_invites(self, guild_id)
¶
Returns a list of invite objects (with invite metadata) for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.invite.InviteData] |
List of invite objects |
Source code in naff/api/http/http_client.py
async def get_guild_invites(self, guild_id: "Snowflake_Type") -> List[discord_typings.InviteData]:
"""
Returns a list of invite objects (with invite metadata) for the guild.
Args:
guild_id: The ID of the guild to query
Returns:
List of invite objects
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/invites"))
async
inherited
method
create_guild_role(self, guild_id, payload, reason)
¶
Create a new role for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
payload |
dict |
A dict representing the role to add |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Returns:
Type | Description |
---|---|
RoleData |
Role object |
Source code in naff/api/http/http_client.py
async def create_guild_role(
self, guild_id: "Snowflake_Type", payload: dict, reason: Absent[str] = MISSING
) -> discord_typings.RoleData:
"""
Create a new role for the guild.
Args:
guild_id: The ID of the guild
payload: A dict representing the role to add
reason: The reason for this action
Returns:
Role object
"""
return await self.request(Route("POST", f"/guilds/{guild_id}/roles"), payload=payload, reason=reason)
async
inherited
method
trigger_typing_indicator(self, channel_id)
¶
Post a typing indicator for the specified channel. Generally bots should not implement this route.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the channel to "type" in |
required |
Source code in naff/api/http/http_client.py
async def trigger_typing_indicator(self, channel_id: "Snowflake_Type") -> None:
"""
Post a typing indicator for the specified channel. Generally bots should not implement this route.
Args:
channel_id: The id of the channel to "type" in
"""
return await self.request(Route("POST", f"/channels/{channel_id}/typing"))
async
inherited
method
get_pinned_messages(self, channel_id)
¶
Get all pinned messages from a channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to get pins from |
required |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.resources.channel.ChannelMessageData, discord_typings.resources.channel.GuildMessageData]] |
A list of pinned message objects |
Source code in naff/api/http/http_client.py
async def get_pinned_messages(self, channel_id: "Snowflake_Type") -> List[discord_typings.MessageData]:
"""
Get all pinned messages from a channel.
Args:
channel_id: The ID of the channel to get pins from
Returns:
A list of pinned message objects
"""
return await self.request(Route("GET", f"/channels/{channel_id}/pins"))
async
inherited
method
modify_guild_role_positions(self, guild_id, role_id, position, reason)
¶
Modify the position of a role in the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
role_id |
Snowflake_Type |
The ID of the role to move |
required |
position |
int |
The new position of this role in the hierarchy |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild.RoleData] |
List of guild roles |
Source code in naff/api/http/http_client.py
async def modify_guild_role_positions(
self, guild_id: "Snowflake_Type", role_id: "Snowflake_Type", position: int, reason: Absent[str] = MISSING
) -> List[discord_typings.RoleData]:
"""
Modify the position of a role in the guild.
Args:
guild_id: The ID of the guild
role_id: The ID of the role to move
position: The new position of this role in the hierarchy
reason: The reason for this action
Returns:
List of guild roles
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/roles"), payload={"id": role_id, "position": position}, reason=reason
)
async
inherited
method
create_stage_instance(self, channel_id, topic, privacy_level, reason)
¶
Create a new stage instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the stage channel |
required |
topic |
str |
The topic of the stage instance (1-120 characters) |
required |
privacy_level |
StagePrivacyLevel |
Them privacy_level of the stage instance (default guild only) |
1 |
reason |
Union[str, naff.client.const.Missing] |
The reason for the creating the stage instance |
Missing |
Returns:
Type | Description |
---|---|
StageInstanceData |
The stage instance |
Source code in naff/api/http/http_client.py
async def create_stage_instance(
self,
channel_id: "Snowflake_Type",
topic: str,
privacy_level: StagePrivacyLevel = 1,
reason: Absent[str] = MISSING,
) -> discord_typings.StageInstanceData:
"""
Create a new stage instance.
Args:
channel_id: The ID of the stage channel
topic: The topic of the stage instance (1-120 characters)
privacy_level: Them privacy_level of the stage instance (default guild only)
reason: The reason for the creating the stage instance
Returns:
The stage instance
"""
return await self.request(
Route("POST", "/stage-instances"),
payload={
"channel_id": channel_id,
"topic": topic,
"privacy_level": StagePrivacyLevel(privacy_level),
},
reason=reason,
)
async
method
login(self, token)
¶
"Login" to the gateway, basically validates the token and grabs user data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
str |
the token to use |
required |
Returns:
Type | Description |
---|---|
dict |
The currently logged in bot's data |
Source code in naff/api/http/http_client.py
async def login(self, token: str) -> dict:
"""
"Login" to the gateway, basically validates the token and grabs user data.
Args:
token: the token to use
Returns:
The currently logged in bot's data
"""
self.__session = ClientSession(connector=self.connector)
self.token = token
try:
return await self.request(Route("GET", "/users/@me"))
except HTTPException as e:
if e.status == 401:
raise LoginError("An improper token was passed") from e
raise
async
inherited
method
modify_guild_role(self, guild_id, role_id, payload, reason)
¶
Modify an existing role for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
role_id |
Snowflake_Type |
The ID of the role to move |
required |
payload |
dict |
A dict representing the role to add |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
Returns:
Type | Description |
---|---|
RoleData |
Role object |
Source code in naff/api/http/http_client.py
async def modify_guild_role(
self, guild_id: "Snowflake_Type", role_id: "Snowflake_Type", payload: dict, reason: Absent[str] = MISSING
) -> discord_typings.RoleData:
"""
Modify an existing role for the guild.
Args:
guild_id: The ID of the guild
role_id: The ID of the role to move
payload: A dict representing the role to add
reason: The reason for this action
Returns:
Role object
"""
return await self.request(Route("PATCH", f"/guilds/{guild_id}/roles/{role_id}"), payload=payload, reason=reason)
async
method
close(self)
¶
Close the session.
Source code in naff/api/http/http_client.py
async def close(self) -> None:
"""Close the session."""
if self.__session and not self.__session.closed:
await self.__session.close()
async
method
get_gateway(self)
¶
Gets the gateway url.
Returns:
Type | Description |
---|---|
str |
The gateway url |
Source code in naff/api/http/http_client.py
async def get_gateway(self) -> str:
"""
Gets the gateway url.
Returns:
The gateway url
"""
try:
data: dict = await self.request(Route("GET", "/gateway"))
except HTTPException as exc:
raise GatewayNotFound from exc
return "{0}?encoding={1}&v={2}&compress=zlib-stream".format(data["url"], "json", __api_version__)
async
inherited
method
get_stage_instance(self, channel_id)
¶
Get the stage instance associated with a given channel, if it exists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to retrieve the instance for. |
required |
Returns:
Type | Description |
---|---|
StageInstanceData |
A stage instance. |
Source code in naff/api/http/http_client.py
async def get_stage_instance(self, channel_id: "Snowflake_Type") -> discord_typings.StageInstanceData:
"""
Get the stage instance associated with a given channel, if it exists.
Args:
channel_id: The ID of the channel to retrieve the instance for.
Returns:
A stage instance.
"""
return await self.request(Route("GET", f"/stage-instances/{channel_id}"))
async
inherited
method
delete_guild_role(self, guild_id, role_id, reason)
¶
Delete a guild role.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
role_id |
Snowflake_Type |
The ID of the role to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for this action |
Missing |
guild_id |
Snowflake_Type |
The ID of the guild |
required |
Source code in naff/api/http/http_client.py
async def delete_guild_role(
self, guild_id: "Snowflake_Type", role_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Delete a guild role.
Args:
role_id: The ID of the role to delete
reason: The reason for this action
guild_id: The ID of the guild
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}/roles/{role_id}"), reason=reason)
async
inherited
method
modify_stage_instance(self, channel_id, topic, privacy_level, reason)
¶
Update the fields of a given stage instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The id of the stage channel. |
required |
topic |
str |
The new topic for the stage instance |
None |
privacy_level |
int |
The privacy level for the stage instance |
None |
reason |
Union[str, naff.client.const.Missing] |
The reason for the change |
Missing |
Returns:
Type | Description |
---|---|
StageInstanceData |
The updated stage instance. |
Source code in naff/api/http/http_client.py
async def modify_stage_instance(
self, channel_id: "Snowflake_Type", topic: str = None, privacy_level: int = None, reason: Absent[str] = MISSING
) -> discord_typings.StageInstanceData:
"""
Update the fields of a given stage instance.
Args:
channel_id: The id of the stage channel.
topic: The new topic for the stage instance
privacy_level: The privacy level for the stage instance
reason: The reason for the change
Returns:
The updated stage instance.
"""
return await self.request(
Route("PATCH", f"/stage-instances/{channel_id}"),
payload=dict_filter_none({"topic": topic, "privacy_level": privacy_level}),
reason=reason,
)
async
inherited
method
get_audit_log(self, guild_id, user_id, action_type, before, after, limit)
¶
Get the audit log for a guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
user_id |
Union[Snowflake_Type, naff.client.const.Missing] |
filter by user ID |
Missing |
action_type |
Union[AuditLogEventType, naff.client.const.Missing] |
filter by action type |
Missing |
before |
Union[Snowflake_Type, naff.client.const.Missing] |
snowflake to get entries before |
Missing |
after |
Union[Snowflake_Type, naff.client.const.Missing] |
snowflake to get entries after |
Missing |
limit |
int |
max number of entries to get |
100 |
Returns:
Type | Description |
---|---|
AuditLogData |
audit log object for the guild |
Source code in naff/api/http/http_client.py
async def get_audit_log(
self,
guild_id: "Snowflake_Type",
user_id: Absent["Snowflake_Type"] = MISSING,
action_type: Absent["AuditLogEventType"] = MISSING,
before: Absent["Snowflake_Type"] = MISSING,
after: Absent["Snowflake_Type"] = MISSING,
limit: int = 100,
) -> discord_typings.AuditLogData:
"""
Get the audit log for a guild.
Args:
guild_id: The ID of the guild to query
user_id: filter by user ID
action_type: filter by action type
before: snowflake to get entries before
after: snowflake to get entries after
limit: max number of entries to get
Returns:
audit log object for the guild
"""
params = {
"action_type": action_type,
"user_id": user_id,
"limit": limit,
"before": before,
"after": after,
}
return await self.request(Route("GET", f"/guilds/{guild_id}/audit-logs"), params=params)
async
method
websocket_connect(self, url)
¶
Connect to the websocket.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url |
str |
the url to connect to |
required |
Source code in naff/api/http/http_client.py
async def websocket_connect(self, url: str) -> ClientWebSocketResponse:
"""
Connect to the websocket.
Args:
url: the url to connect to
"""
return await self.__session.ws_connect(
url, timeout=30, max_msg_size=0, autoclose=False, headers={"User-Agent": self.user_agent}, compress=0
)
async
inherited
method
delete_stage_instance(self, channel_id, reason)
¶
Delete a stage instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel_id |
Snowflake_Type |
The ID of the channel to delete the stage instance for. |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for the deletion |
Missing |
Source code in naff/api/http/http_client.py
async def delete_stage_instance(self, channel_id: "Snowflake_Type", reason: Absent[str] = MISSING) -> None:
"""
Delete a stage instance.
Args:
channel_id: The ID of the channel to delete the stage instance for.
reason: The reason for the deletion
"""
return await self.request(Route("DELETE", f"/stage-instances/{channel_id}"), reason=reason)
async
inherited
method
create_tag(self, channel_id, name, emoji_id, emoji_name)
¶
Create a new tag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str |
The name of the tag |
required |
emoji_id |
Optional[Snowflake_Type] |
The ID of the emoji to use for the tag |
None |
emoji_name |
Optional[str] |
The name of the emoji to use for the tag |
None |
Note
Can either have an emoji_id or an emoji_name, but not both. emoji_id is meant for custom emojis, emoji_name is meant for unicode emojis.
Source code in naff/api/http/http_client.py
async def create_tag(
self,
channel_id: "Snowflake_Type",
name: str,
emoji_id: Optional["Snowflake_Type"] = None,
emoji_name: Optional[str] = None,
) -> discord_typings.ChannelData:
"""
Create a new tag.
Args:
name: The name of the tag
emoji_id: The ID of the emoji to use for the tag
emoji_name: The name of the emoji to use for the tag
Note:
Can either have an emoji_id or an emoji_name, but not both.
emoji_id is meant for custom emojis, emoji_name is meant for unicode emojis.
"""
return await self.request(
Route("POST", f"/channels/{channel_id}/tags"),
payload=dict_filter_none({"name": name, "emoji_id": emoji_id, "emoji_name": emoji_name}),
)
async
inherited
method
get_guild_voice_regions(self, guild_id)
¶
Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when the guild is VIP- enabled.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.voice.VoiceRegionData] |
List of voice region objects |
Source code in naff/api/http/http_client.py
async def get_guild_voice_regions(self, guild_id: "Snowflake_Type") -> List[discord_typings.VoiceRegionData]:
"""
Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when the guild is VIP- enabled.
Args:
guild_id: The ID of the guild to query
Returns:
List of voice region objects
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/regions"))
async
inherited
method
get_guild_integrations(self, guild_id)
¶
Returns a list of integration objects for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
List[Union[discord_typings.resources.guild.StreamingIntegrationData, discord_typings.resources.guild.DiscordIntegrationData]] |
list of integration objects |
Source code in naff/api/http/http_client.py
async def get_guild_integrations(self, guild_id: "Snowflake_Type") -> List[discord_typings.IntegrationData]:
"""
Returns a list of integration objects for the guild.
Args:
guild_id: The ID of the guild to query
Returns:
list of integration objects
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/integrations"))
async
inherited
method
edit_tag(self, channel_id, tag_id, name, emoji_id, emoji_name)
¶
Update a tag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tag_id |
Snowflake_Type |
The ID of the tag to update |
required |
name |
str |
The new name of the tag |
required |
emoji_id |
Optional[Snowflake_Type] |
The ID of the emoji to use for the tag |
None |
emoji_name |
Optional[str] |
The name of the emoji to use for the tag |
None |
Note
Can either have an emoji_id or an emoji_name, but not both. emoji_id is meant for custom emojis, emoji_name is meant for unicode emojis.
Source code in naff/api/http/http_client.py
async def edit_tag(
self,
channel_id: "Snowflake_Type",
tag_id: "Snowflake_Type",
name: str,
emoji_id: Optional["Snowflake_Type"] = None,
emoji_name: Optional[str] = None,
) -> discord_typings.ChannelData:
"""
Update a tag.
Args:
tag_id: The ID of the tag to update
name: The new name of the tag
emoji_id: The ID of the emoji to use for the tag
emoji_name: The name of the emoji to use for the tag
Note:
Can either have an emoji_id or an emoji_name, but not both.
emoji_id is meant for custom emojis, emoji_name is meant for unicode emojis.
"""
return await self.request(
Route("PUT", f"/channels/{channel_id}/tags/{tag_id}"),
payload=dict_filter_none({"name": name, "emoji_id": emoji_id, "emoji_name": emoji_name}),
)
async
inherited
method
delete_guild_integration(self, guild_id, integration_id, reason)
¶
Delete an integration from the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
integration_id |
Snowflake_Type |
The ID of the integration to remove |
required |
Source code in naff/api/http/http_client.py
async def delete_guild_integration(
self, guild_id: "Snowflake_Type", integration_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> None:
"""
Delete an integration from the guild.
Args:
guild_id: The ID of the guild
integration_id: The ID of the integration to remove
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}/integrations/{integration_id}"), reason=reason)
async
inherited
method
get_guild_widget_settings(self, guild_id)
¶
Get guild widget settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
GuildWidgetSettingsData |
guild widget object |
Source code in naff/api/http/http_client.py
async def get_guild_widget_settings(self, guild_id: "Snowflake_Type") -> discord_typings.GuildWidgetSettingsData:
"""
Get guild widget settings.
Args:
guild_id: The ID of the guild to query
Returns:
guild widget object
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/widget"))
async
inherited
method
delete_tag(self, channel_id, tag_id)
¶
Delete a forum tag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tag_id |
Snowflake_Type |
The ID of the tag to delete |
required |
Source code in naff/api/http/http_client.py
async def delete_tag(self, channel_id: "Snowflake_Type", tag_id: "Snowflake_Type") -> discord_typings.ChannelData:
"""
Delete a forum tag.
Args:
tag_id: The ID of the tag to delete
"""
return await self.request(Route("DELETE", f"/channels/{channel_id}/tags/{tag_id}"))
async
inherited
method
get_guild_widget(self, guild_id)
¶
Returns the widget for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
GuildWidgetData |
Guild widget |
Source code in naff/api/http/http_client.py
async def get_guild_widget(self, guild_id: "Snowflake_Type") -> discord_typings.GuildWidgetData:
"""
Returns the widget for the guild.
Args:
guild_id: The ID of the guild to query
Returns:
Guild widget
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/widget.json"))
async
inherited
method
get_guild_widget_image(self, guild_id, style)
¶
Get a url representing a png image widget for the guild.
For styles see: https://discord.com/developers/docs/resources/guild#get-guild-widget-image
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The guild to query |
required |
style |
Optional[str] |
The style of widget required. |
None |
Returns:
Type | Description |
---|---|
str |
A url pointing to this image |
Source code in naff/api/http/http_client.py
async def get_guild_widget_image(self, guild_id: "Snowflake_Type", style: Optional[str] = None) -> str:
"""
Get a url representing a png image widget for the guild.
For styles see: https://discord.com/developers/docs/resources/guild#get-guild-widget-image
Args:
guild_id: The guild to query
style: The style of widget required.
Returns:
A url pointing to this image
"""
route = Route("GET", f"/guilds/{guild_id}/widget.png{f'?style={style}' if style else ''}")
return route.url
async
inherited
method
get_guild_welcome_screen(self, guild_id)
¶
Get the welcome screen for this guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
WelcomeScreenData |
Welcome screen object |
Source code in naff/api/http/http_client.py
async def get_guild_welcome_screen(self, guild_id: "Snowflake_Type") -> discord_typings.WelcomeScreenData:
"""
Get the welcome screen for this guild.
Args:
guild_id: The ID of the guild to query
Returns:
Welcome screen object
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/welcome-screen"))
async
inherited
method
get_guild_vanity_url(self, guild_id)
¶
Get a partial invite object for the guilds vanity invite url.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query |
required |
Returns:
Type | Description |
---|---|
dict |
Returns a partial invite object. Code is None if a vanity url for the guild is not set. |
Source code in naff/api/http/http_client.py
async def get_guild_vanity_url(self, guild_id: "Snowflake_Type") -> dict:
"""
Get a partial invite object for the guilds vanity invite url.
Args:
guild_id: The ID of the guild to query
Returns:
Returns a partial invite object. Code is None if a vanity url for the guild is not set.
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/vanity-url"))
async
inherited
method
get_guild_channels(self, guild_id)
¶
Gets a list of guild channel objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
Returns:
Type | Description |
---|---|
dict |
A list of channels in this guild. Does not include threads. |
Source code in naff/api/http/http_client.py
async def get_guild_channels(self, guild_id: "Snowflake_Type") -> dict:
"""
Gets a list of guild channel objects.
Args:
guild_id: The ID of the guild
Returns:
A list of channels in this guild. Does not include threads.
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/channels"))
async
inherited
method
modify_guild_widget(self, guild_id, enabled, channel_id)
¶
Modify a guild widget.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to modify. |
required |
enabled |
bool |
Should the guild widget be enabled |
None |
channel_id |
Snowflake_Type |
The widget's channel ID |
None |
Returns:
Type | Description |
---|---|
GuildWidgetData |
Updated guild widget. |
Source code in naff/api/http/http_client.py
async def modify_guild_widget(
self, guild_id: "Snowflake_Type", enabled: bool = None, channel_id: "Snowflake_Type" = None
) -> discord_typings.GuildWidgetData:
"""
Modify a guild widget.
Args:
guild_id: The ID of the guild to modify.
enabled: Should the guild widget be enabled
channel_id: The widget's channel ID
Returns:
Updated guild widget.
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/widget"),
payload=dict_filter_none({"enabled": enabled, "channel_id": channel_id}),
)
async
inherited
method
modify_guild_welcome_screen(self, guild_id, enabled, welcome_channels, description)
¶
Modify the guild's welcome screen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild. |
required |
enabled |
bool |
Whether the welcome screen is enabled |
required |
welcome_channels |
List[Snowflake_Type] |
Channels linked in the welcome screen and their display options |
required |
description |
str |
The server description to show in the welcome screen |
required |
Returns:
Type | Description |
---|---|
WelcomeScreenData |
Updated welcome screen object |
Source code in naff/api/http/http_client.py
async def modify_guild_welcome_screen(
self, guild_id: "Snowflake_Type", enabled: bool, welcome_channels: List["Snowflake_Type"], description: str
) -> discord_typings.WelcomeScreenData:
"""
Modify the guild's welcome screen.
Args:
guild_id: The ID of the guild.
enabled: Whether the welcome screen is enabled
welcome_channels: Channels linked in the welcome screen and their display options
description: The server description to show in the welcome screen
Returns:
Updated welcome screen object
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/welcome-screen"),
payload={"enabled": enabled, "welcome_channels": welcome_channels, "description": description},
)
async
inherited
method
modify_current_user_voice_state(self, guild_id, channel_id, suppress, request_to_speak_timestamp)
¶
Update the current user voice state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to update. |
required |
channel_id |
Snowflake_Type |
The id of the channel the user is currently in |
required |
suppress |
bool |
Toggle the user's suppress state. |
None |
request_to_speak_timestamp |
str |
Sets the user's request to speak |
None |
Source code in naff/api/http/http_client.py
async def modify_current_user_voice_state(
self,
guild_id: "Snowflake_Type",
channel_id: "Snowflake_Type",
suppress: bool = None,
request_to_speak_timestamp: str = None,
) -> None:
"""
Update the current user voice state.
Args:
guild_id: The ID of the guild to update.
channel_id: The id of the channel the user is currently in
suppress: Toggle the user's suppress state.
request_to_speak_timestamp: Sets the user's request to speak
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/voice-states/@me"),
payload=dict_filter_none(
{
"channel_id": channel_id,
"suppress": suppress,
"request_to_speak_timestamp": request_to_speak_timestamp,
}
),
)
async
inherited
method
modify_user_voice_state(self, guild_id, user_id, channel_id, suppress)
¶
Modify the voice state of a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild. |
required |
user_id |
Snowflake_Type |
The ID of the user to modify. |
required |
channel_id |
Snowflake_Type |
The ID of the channel the user is currently in. |
required |
suppress |
bool |
Toggles the user's suppress state. |
None |
Source code in naff/api/http/http_client.py
async def modify_user_voice_state(
self, guild_id: "Snowflake_Type", user_id: "Snowflake_Type", channel_id: "Snowflake_Type", suppress: bool = None
) -> None:
"""
Modify the voice state of a user.
Args:
guild_id: The ID of the guild.
user_id: The ID of the user to modify.
channel_id: The ID of the channel the user is currently in.
suppress: Toggles the user's suppress state.
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/voice-states/{user_id}"),
payload=dict_filter_none({"channel_id": channel_id, "suppress": suppress}),
)
async
inherited
method
create_guild_from_guild_template(self, template_code, name, icon)
¶
Creates a new guild based on a template.
Note
This endpoint can only be used by bots in less than 10 guilds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
template_code |
str |
The code of the template to use. |
required |
name |
str |
The name of the guild (2-100 characters) |
required |
icon |
str |
Data URI scheme |
required |
Returns:
Type | Description |
---|---|
GuildData |
The newly created guild object |
Source code in naff/api/http/http_client.py
async def create_guild_from_guild_template(
self, template_code: str, name: str, icon: str
) -> discord_typings.GuildData:
"""
Creates a new guild based on a template.
note:
This endpoint can only be used by bots in less than 10 guilds.
Args:
template_code: The code of the template to use.
name: The name of the guild (2-100 characters)
icon: Data URI scheme
Returns:
The newly created guild object
"""
return await self.request(
Route("POST", f"/guilds/templates/{template_code}"), payload={"name": name, "icon": icon}
)
async
inherited
method
get_guild_templates(self, guild_id)
¶
Returns an array of guild templates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to query. |
required |
Returns:
Type | Description |
---|---|
List[discord_typings.resources.guild_template.GuildTemplateData] |
An array of guild templates |
Source code in naff/api/http/http_client.py
async def get_guild_templates(self, guild_id: "Snowflake_Type") -> List[discord_typings.GuildTemplateData]:
"""
Returns an array of guild templates.
Args:
guild_id: The ID of the guild to query.
Returns:
An array of guild templates
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/templates"))
async
inherited
method
create_guild_template(self, guild_id, name, description)
¶
Create a guild template for the guild.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to create a template for. |
required |
name |
str |
The name of the template |
required |
description |
Union[str, naff.client.const.Missing] |
The description of the template |
Missing |
Returns:
Type | Description |
---|---|
GuildTemplateData |
The created guild template |
Source code in naff/api/http/http_client.py
async def create_guild_template(
self, guild_id: "Snowflake_Type", name: str, description: Absent[str] = MISSING
) -> discord_typings.GuildTemplateData:
"""
Create a guild template for the guild.
Args:
guild_id: The ID of the guild to create a template for.
name: The name of the template
description: The description of the template
Returns:
The created guild template
"""
return await self.request(
Route("POST", f"/guilds/{guild_id}/templates"),
payload={"name": name, "description": description},
)
async
inherited
method
sync_guild_template(self, guild_id, template_code)
¶
Sync the template to the guild's current state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
template_code |
str |
The code for the template to sync |
required |
Returns:
Type | Description |
---|---|
GuildTemplateData |
The updated guild template |
Source code in naff/api/http/http_client.py
async def sync_guild_template(
self, guild_id: "Snowflake_Type", template_code: str
) -> discord_typings.GuildTemplateData:
"""
Sync the template to the guild's current state.
Args:
guild_id: The ID of the guild
template_code: The code for the template to sync
Returns:
The updated guild template
"""
return await self.request(Route("PUT", f"/guilds/{guild_id}/templates/{template_code}"))
async
inherited
method
modify_guild_template(self, guild_id, template_code, name, description)
¶
Modifies the template's metadata.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
template_code |
str |
The template code |
required |
name |
Union[str, naff.client.const.Missing] |
The name of the template |
Missing |
description |
Union[str, naff.client.const.Missing] |
The description of the template |
Missing |
Returns:
Type | Description |
---|---|
GuildTemplateData |
The updated guild template |
Source code in naff/api/http/http_client.py
async def modify_guild_template(
self,
guild_id: "Snowflake_Type",
template_code: str,
name: Absent[str] = MISSING,
description: Absent[str] = MISSING,
) -> discord_typings.GuildTemplateData:
"""
Modifies the template's metadata.
Args:
guild_id: The ID of the guild
template_code: The template code
name: The name of the template
description: The description of the template
Returns:
The updated guild template
"""
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/templates/{template_code}"),
payload={"name": name, "description": description},
)
async
inherited
method
delete_guild_template(self, guild_id, template_code)
¶
Delete the guild template.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
template_code |
str |
The ID of the template |
required |
Returns:
Type | Description |
---|---|
GuildTemplateData |
The deleted template object |
Source code in naff/api/http/http_client.py
async def delete_guild_template(
self, guild_id: "Snowflake_Type", template_code: str
) -> discord_typings.GuildTemplateData:
"""
Delete the guild template.
Args:
guild_id: The ID of the guild
template_code: The ID of the template
Returns:
The deleted template object
"""
# why on earth does this return the deleted template object?
return await self.request(Route("DELETE", f"/guilds/{guild_id}/templates/{template_code}"))
async
inherited
method
get_auto_moderation_rules(self, guild_id)
¶
Get this guilds auto moderation rules.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to get |
required |
Returns:
Type | Description |
---|---|
list |
A list of auto moderation rules |
Source code in naff/api/http/http_client.py
async def get_auto_moderation_rules(
self, guild_id: "Snowflake_Type"
) -> list[discord_typings.AutoModerationRuleData]:
"""
Get this guilds auto moderation rules.
Args:
guild_id: The ID of the guild to get
Returns:
A list of auto moderation rules
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/auto-moderation/rules"))
async
inherited
method
get_auto_moderation_rule(self, guild_id, rule_id)
¶
Get a specific auto moderation rule.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild |
required |
rule_id |
Snowflake_Type |
The ID of the rule to get |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.auto_moderation.KeywordAutoModerationRuleData, discord_typings.resources.auto_moderation.KeywordPresetAutoModerationRuleData, discord_typings.resources.auto_moderation.HarmfulLinkSpamAutoModerationRuleData] |
The auto moderation rule |
Source code in naff/api/http/http_client.py
async def get_auto_moderation_rule(
self, guild_id: "Snowflake_Type", rule_id: "Snowflake_Type"
) -> discord_typings.AutoModerationRuleData:
"""
Get a specific auto moderation rule.
Args:
guild_id: The ID of the guild
rule_id: The ID of the rule to get
Returns:
The auto moderation rule
"""
return await self.request(Route("GET", f"/guilds/{guild_id}/auto-moderation/rules/{rule_id}"))
async
inherited
method
create_auto_moderation_rule(self, guild_id, payload)
¶
Create an auto moderation rule.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to create this rule within |
required |
payload |
Union[discord_typings.resources.auto_moderation.KeywordAutoModerationRuleData, discord_typings.resources.auto_moderation.KeywordPresetAutoModerationRuleData, discord_typings.resources.auto_moderation.HarmfulLinkSpamAutoModerationRuleData] |
A dict representing the auto moderation rule |
required |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.auto_moderation.KeywordAutoModerationRuleData, discord_typings.resources.auto_moderation.KeywordPresetAutoModerationRuleData, discord_typings.resources.auto_moderation.HarmfulLinkSpamAutoModerationRuleData] |
The created auto moderation rule |
Source code in naff/api/http/http_client.py
async def create_auto_moderation_rule(
self, guild_id: "Snowflake_Type", payload: discord_typings.AutoModerationRuleData
) -> discord_typings.AutoModerationRuleData:
"""
Create an auto moderation rule.
Args:
guild_id: The ID of the guild to create this rule within
payload: A dict representing the auto moderation rule
Returns:
The created auto moderation rule
"""
return await self.request(Route("POST", f"/guilds/{guild_id}/auto-moderation/rules"), payload=payload)
async
inherited
method
modify_auto_moderation_rule(self, guild_id, rule_id, name, trigger_type, trigger_metadata, actions, exempt_channels, exempt_roles, event_type, enabled, reason)
¶
Modify an existing auto moderation rule.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild the rule belongs to |
required |
rule_id |
Snowflake_Type |
The ID of the rule to modify |
required |
name |
Union[str, naff.client.const.Missing] |
The name of the rule |
Missing |
trigger_type |
Union[dict, naff.client.const.Missing] |
The type trigger for this rule |
Missing |
trigger_metadata |
Union[dict, naff.client.const.Missing] |
Metadata for the trigger |
Missing |
actions |
Union[list[dict], naff.client.const.Missing] |
A list of actions to take upon triggering |
Missing |
exempt_roles |
Union[list['Snowflake_Type'], naff.client.const.Missing] |
Roles that ignore this rule |
Missing |
exempt_channels |
Union[list['Snowflake_Type'], naff.client.const.Missing] |
Channels that ignore this role |
Missing |
enabled |
Union[bool, naff.client.const.Missing] |
Is this rule enabled? |
Missing |
event_type |
Union[dict, naff.client.const.Missing] |
The type of event that triggers this rule |
Missing |
reason |
Union[str, naff.client.const.Missing] |
The reason for this change |
Missing |
Returns:
Type | Description |
---|---|
Union[discord_typings.resources.auto_moderation.KeywordAutoModerationRuleData, discord_typings.resources.auto_moderation.KeywordPresetAutoModerationRuleData, discord_typings.resources.auto_moderation.HarmfulLinkSpamAutoModerationRuleData] |
The updated rule object |
Source code in naff/api/http/http_client.py
async def modify_auto_moderation_rule(
self,
guild_id: "Snowflake_Type",
rule_id: "Snowflake_Type",
name: Absent[str] = MISSING,
trigger_type: Absent[dict] = MISSING,
trigger_metadata: Absent[dict] = MISSING,
actions: Absent[list[dict]] = MISSING,
exempt_channels: Absent[list["Snowflake_Type"]] = MISSING,
exempt_roles: Absent[list["Snowflake_Type"]] = MISSING,
event_type: Absent[dict] = MISSING,
enabled: Absent[bool] = MISSING,
reason: Absent[str] = MISSING,
) -> discord_typings.AutoModerationRuleData:
"""
Modify an existing auto moderation rule.
Args:
guild_id: The ID of the guild the rule belongs to
rule_id: The ID of the rule to modify
name: The name of the rule
trigger_type: The type trigger for this rule
trigger_metadata: Metadata for the trigger
actions: A list of actions to take upon triggering
exempt_roles: Roles that ignore this rule
exempt_channels: Channels that ignore this role
enabled: Is this rule enabled?
event_type: The type of event that triggers this rule
reason: The reason for this change
Returns:
The updated rule object
"""
payload = {
"name": name,
"trigger_type": trigger_type,
"trigger_metadata": trigger_metadata,
"actions": actions,
"exempt_roles": exempt_roles,
"exempt_channels": exempt_channels,
"event_type": event_type,
"enabled": enabled,
}
return await self.request(
Route("PATCH", f"/guilds/{guild_id}/auto-moderation/rules/{rule_id}"), payload=payload, reason=reason
)
async
inherited
method
delete_auto_moderation_rule(self, guild_id, rule_id, reason)
¶
Delete an auto moderation rule.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
guild_id |
Snowflake_Type |
The ID of the guild to delete this rule from |
required |
rule_id |
Snowflake_Type |
The ID of the role to delete |
required |
reason |
Union[str, naff.client.const.Missing] |
The reason for deleting this rule |
Missing |
Source code in naff/api/http/http_client.py
async def delete_auto_moderation_rule(
self, guild_id: "Snowflake_Type", rule_id: "Snowflake_Type", reason: Absent[str] = MISSING
) -> discord_typings.AutoModerationRuleData:
"""
Delete an auto moderation rule.
Args:
guild_id: The ID of the guild to delete this rule from
rule_id: The ID of the role to delete
reason: The reason for deleting this rule
"""
return await self.request(Route("DELETE", f"/guilds/{guild_id}/auto-moderation/rules/{rule_id}"), reason=reason)