General
General questions regarding library usage belong here.
This content has been taken directly from the documentation, and inherited from discord.py
. It will most likely be rewritten in the future.
Where can I find usage examples?
Example code can be found in the examples folder in the repository.
How do I set the "Playing" status?
The activity
keyword argument may be passed in the commands.Bot
constructor or Bot.change_presence
, given an Activity
object.
The constructor may be used for static activities, while Bot.change_presence
may be used to update the activity at runtime.
It is highly discouraged to use Bot.change_presence
or API calls in on_ready
as this event may be called many times while running, not just once. There is a high chance of disconnecting if presences are changed right after connecting.
The status type (playing, listening, streaming, watching) can be set using the ActivityType
enum.
For memory optimisation purposes, some activities are offered in slimmed-down versions:
Putting both of these pieces of info together, you get the following:
bot = commands.Bot(..., activity=disnake.Game(name="My game"))
# Or, for watching:
activity = disnake.Activity(
name="My activity",
type=disnake.ActivityType.watching,
)
bot = commands.Bot(..., activity=activity)
How do I send a message to a specific channel?
You must get or fetch the channel directly and then call the appropriate method. Example:
# If Bot.get_channel returns None because the channel is not in the Bot's cache,
# make an API call to fetch the channel
channel = bot.get_channel(12324234183172) or await bot.fetch_channel(12324234183172)
await channel.send("hello")
How do I send a DM?
Get the User
or Member
object and call abc.Messageable.send
. For example:
user = bot.get_user(381870129706958858)
await user.send("👀")
If you are responding to an event, such as on_message
, you already have the User
object via Message.author
:
await message.author.send("👋")
How do I get the ID of a sent message?
The abc.Messageable.send
method returns the Message
that was sent.
The ID of a message can be accessed via Message.id
:
message = await channel.send("hmm…")
message_id = message.id
How do I upload an image?
To upload something to Discord you have to use the File
object.
A File
accepts two parameters, the file-like object (or file path) and the filename
to pass to Discord when uploading.
If you want to upload an image it's as simple as:
await channel.send(file=disnake.File("my_file.png"))
If you have a file-like object you can do as follows:
with open("my_file.png", "rb") as fp:
await channel.send(file=disnake.File(fp, "new_filename.png"))
To upload multiple files, you can use the files
keyword argument instead of file
:
my_files = [
disnake.File("result.zip"),
disnake.File("teaser_graph.png"),
]
await channel.send(files=my_files)
If you want to upload something from a URL, you will have to use an HTTP request using aiohttp
and then pass an io.BytesIO instance
to File
like so:
import io
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(my_url) as resp:
if resp.status != 200:
return await channel.send("Could not download file...")
data = io.BytesIO(await resp.read())
await channel.send(file=disnake.File(data, "cool_image.png"))
How can I add a reaction to a message?
You use the Message.add_reaction
method.
If you want to use unicode emoji, you must pass a valid unicode code point in a string. In your code, you can write this in a few different ways:
'👍'
'\U0001F44D'
'\N{THUMBS UP SIGN}'
Quick example:
emoji = "\N{THUMBS UP SIGN}"
# or '\U0001f44d' or '👍'
await message.add_reaction(emoji)
In case you want to use emoji that come from a message, you already get their code points in the content without needing
to do anything special. You cannot send ':thumbsup:'
style shorthands.
For custom emoji, you should pass an instance of Emoji
. You can also pass a '<:name:id>'
string, but if you
can use said emoji, you should be able to use Bot.get_emoji
to get an emoji via ID or use utils.find
or utils.get
on Bot.emojis
or Guild.emojis
collections.
The name and ID of a custom emoji can be found with the client by prefixing :custom_emoji:
with a backslash.
For example, sending the message \:python3:
with the client will result in <:python3:232720527448342530>
.
Quick example:
# If you have the ID already
emoji = bot.get_emoji(310177266011340803)
await message.add_reaction(emoji)
# No ID, do a lookup
emoji = disnake.utils.get(guild.emojis, name="LUL")
if emoji:
await message.add_reaction(emoji)
# If you have the name and ID of a custom emoji:
emoji = "<:python3:232720527448342530>"
await message.add_reaction(emoji)
How do I pass a coroutine to the player's "after" function?
The library's music player launches on a separate thread, ergo it does not execute inside a coroutine.
This does not mean that it is not possible to call a coroutine in the after
parameter. To do so you must pass a callable
that wraps up a couple of aspects.
The first gotcha that you must be aware of is that calling a coroutine is not a thread-safe operation. Since we are
technically in another thread, we must take caution in calling thread-safe operations so things do not bug out. Luckily for
us, asyncio
comes with a asyncio.run_coroutine_threadsafe
function that allows us to call
a coroutine from another thread.
However, this function returns a Future
and to actually call it we have to fetch its result. Putting all of
this together we can do the following:
def my_after(error):
coro = some_channel.send("Song is done!")
fut = asyncio.run_coroutine_threadsafe(coro, bot.loop)
try:
fut.result()
except:
# An error happened sending the message
pass
voice.play(disnake.FFmpegPCMAudio(url), after=my_after)
How do I run something in the background?
Check the background_task.py
example.
How do I get a specific model?
There are multiple ways of doing this. If you have a specific model's ID then you can use one of the following functions:
The following use an HTTP request:
abc.Messageable.fetch_message
Bot.fetch_user
Bot.fetch_guilds
Bot.fetch_guild
Bot.fetch_emojis
Bot.fetch_emoji
Bot.fetch_member
If the functions above do not help you, then use of utils.find
or utils.get
would serve some use in finding
specific models.
Quick example:
# Find a guild by name
guild = disnake.utils.get(bot.guilds, name="My Server")
# Make sure to check if it's found
if guild is not None:
# Find a channel by name
channel = disnake.utils.get(guild.text_channels, name="cool-channel")
How do I make a web request?
To make a request, you should use a non-blocking library.
This library already uses and requires a 3rd party library for making requests, aiohttp
.
Quick example:
async with aiohttp.ClientSession() as session:
async with session.get("http://aws.random.cat/meow") as r:
if r.status == 200:
js = await r.json()
See aiohttp
's full documentation for more information.
How do I use a local image file for an embed image?
Setting a local image for the embed can be done using the file
argument of Embed.set_image
method. It accepts a File
object.
Quick example:
embed = disnake.Embed()
embed.set_image(file=disnake.File("path/to/file.png"))
await channel.send(embed=embed)
Is there an event for audit log entries being created?
As of version 2.8, there's now an event for it, called on_audit_log_entry_create
.