Intents discord py как включить

Обновлено: 30.06.2024

Intents are an important part of Discord which I briefly cover in this tutorial part, but which deserve their own section explaining them in more depth, so here it is!

1 - What are Gateway Intents?

Gateway intents are a way of getting only the data your application needs from the Discord gateway. When you first identify with the gateway upon starting your bot you send the intents you are going to use as an integer which represents a field of bits that describe which intents you need.

There are a few different gateway intents that you can select:

Gateway Intent Name in Docs Bit Shift Description Privileged
GUILDS 1 << 0 Allows you to receive guild events like joining/leaving guilds, role events, and channel events. No
GUILD_MEMBERS 1 << 1 Allows you to receive member events like joins and leaves. Yes
GUILD_BANS 1 << 2 Allowd you to receive ban add and remove events. No
GUILD_EMOJIS 1 << 3 Allows you to receive emoji updates. No
GUILD_INTEGRATIONS 1 << 4 Allows you to receive integration update events. No
GUILD_WEBHOOKS 1 << 5 Allows you to receive webhook update events. No
GUILD_INVITES 1 << 6 Allows you to receive invite create and delete events. No
GUILD_VOICE_STATES 1 << 7 Allows you to receive voice state update events. No
GUILD_PRESENCES 1 << 8 Allows you to receive members' presence updates. Yes
GUILD_MESSAGES 1 << 9 Allows you to receive message events like create and delete from guilds. No
GUILD_MESSAGE_REACTIONS 1 << 10 Allows you to receive message reaction events like add and remove on guild messages. No
GUILD_MESSAGE_TYPING 1 << 11 Allows you to receive typing events in guilds. No
DIRECT_MESSAGES 1 << 12 Allows you to receive message events like create and delete from DMs. No
DIRECT_MESSAGE_REACTIONS 1 << 13 Allows you to receive message reaction events like add and remove on DM messages. No
DIRECT_MESSAGE_TYPING 1 << 14 Allows you to receive typing events in DMs. No

Bear in mind that these intents often also determine which data you receive upon connecting to the gateway. For example if you have members intents disabled you will not receive guild member lists upon connecting, in addition to not receiving member events.

Enabling Privileged Intents

To enable privileged intents for your application, first head over to the Discord developer portal and click on your application. Next, head to the Bot tab on the left, and scroll down to the privileged intents section:

Beyond 100 servers you bot will need to be verified and whitelisted for these intents to be able to use them.

Privileged Intents

Now you can select either or both of these intents so that you can use them in your code. Bear in mind that if one of these intents is not enabled on this page you cannot use it when connecting to the gateway.

Using Intents in Your Bot

Let's start out with a simple bot setup:

This example has most of the intents enabled, all except members and presences. There are a couple of ways we can enable these intents, the first option being using all intents - which you should only use if you actually use both memebrs and presence intents:

You shouldn't use all intents like this unless you actually use them!

The next method is to create a default intents object, and explicitly enable an intent on it, in this example I'll enabled the members intent since this is the most common one to need:

That's pretty much it for gateway intents, they're not too complicated but can definitely catch you out if you don't know about them, so watch out for where you might need to change them!

Всем привет! Это мой первый пост на Хабре, и в нём я попытаюсь научить делать вас ботов для Discord на языке Python. Итак, приступим.

Первое, что нам нужно сделать, это установить нужные библиотеки и сам питон.

Шаг 1.

После успешно установки нажимаем сочетание клавиш "win" + "r", в открывшемся окошке вводим cmd


В открывшемся окне пишем "pip install discord", ждём когда всё установится, затем прописываем "pip install discord.py".

Шаг 2. Создаём аккаунт нашему боту

Переходим во вкладку "Bot", там нажимаем кнопку "Add bot"

В разделе Privileged Gateway Intents включаем SERVER MEMBERS INTENT и PRESENCE INTENT

Возле аватара нашего бота ищем надпись Token, под ней нажимаем кнопку copy.

Шаг 3. Теперь мы можем перейти к написанию кода

Создаём где нибудь на диске папку.

Я назову её bot. Создаём в ней файл нашего бота с форматом .py, его можно называть как угодно, но я назову его bot. Чем проще тем лучше)

Теперь можно написать первые строчки кода.

После этого открываем файл с помощью Python'а и ваш бот должен появиться в сети.

Надеюсь, что у вас всё получилось без труда, и вы не просто всё скопировали, а пытались понять, что да как

Удачи вам, с вами был klikis(polyhedron).

Если я что-то забыл написать, или вам что-то не понятно, то пишите в комментарии. Увидимся в следующей части!

P.S. Не бейте за оформление)

Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

О песочнице

Это «Песочница» — раздел, в который попадают дебютные посты пользователей, желающих стать полноправными участниками сообщества.

Если у вас есть приглашение, отправьте его автору понравившейся публикации — тогда её смогут прочитать и обсудить все остальные пользователи Хабра.

Чтобы исключить предвзятость при оценке, все публикации анонимны, псевдонимы показываются случайным образом.

If you're wondering what Gateway Intents are, what Privileged Intents are, why your bot can't see statuses, or why your bot can't see member joins anymore, then this page should explain it to you!

if you do not know what intents are, please read this entire page

Examples of gateway events you are probably familiar with are Message Create (a message was sent) and Guild Member Add (a user joined a server).

What are Gateway Intents?

Gateway Intents are groups of events. Bots can choose which intents to receive events from. You can see the docs and full list of intents here.

Need help with setting intents in your code? These links should help: discord.js, discord.py, JDA

Discord has made 2 intents privileged intents: GUILD_MEMBERS (Server Members) and GUILD_PRESENCES (Presence). These intents are now disabled by default in Gateway v6.

What are these privileged intents needed for?

Guild Members (Server Members Intent) is used for:

  • Doing something when someone joins a server (Guild Member Add event)
  • Doing something when a member/user's data is updated (Guild Member Update event)
  • Doing something when someone leaves a server (Guild Member Remove event)
  • Getting the entire list of members in a server (Request/List Guild Members)

It is not needed for:

  • Seeing data of the author of a message (that is included in the message data)
  • Getting a specific member/user by ID
  • Getting a guild member by their name
  • Getting a guild's member count (that can be retreived with the Get Guild endpoint)

Guild Presences (Presence Intent) is used for getting member presences, which includes:

  • "Playing"/"Streaming"/"Watching"/"Competing" activities
  • Custom Status
  • User status: online, idle, dnd, or offline

The intent is needed to fetch this data as well as get the Presence Update event when it changes; all users other than the bot will appear offline with no activities if you do not have this intent.

It is not needed for:

The presence intent is also required for the initial guild member list (which includes all members for small guilds and online members + members without roles for larger guilds), but note that your bot will not be whitelisted for the presence intent if you just need it for member caching. You should be fetching members/users when needed instead of relying on your bot's member/user cache.

Common Privileged Intent Misconceptions

You do not need, and will not get, privileged intents to get a "user count" for your bot. If intents affects your "user count", then you are probably showing the amount of cached users. Instead, if you really want a "user count", add up the member counts of all servers; for help doing this in your library, go to its support server.

You do not need privileged intents to get a server's member count or online member count. Instead, you should fetch the guild and and use the approximate_member_count and approximate_presence_count properties. (discord.py seems to not currently support this, so if you use discord.py you should do a direct API request. discord.js supports this.)

Getting Privileged Intents

You cannot just specify privileged intents in your list and get them, you must enable or be whitelisted for them:

for bots in less than 76 servers:

  • Go to the Developer Portal, select your bot, and click the Bot tab
  • Turn on the switches for the intents you need

for bigger bots:

You should request the privileged intents your bot requires in the bot verification form when applying for verification.

Note: You will not be approved for privileged intents for userinfo/serverinfo commands.

If your bot is verified but you did not do that and you need the intent now, create a support ticket (Privileged Gateway Intent Application) and request them. The wait time is currently

a month due to the influx of late requests.

On the new Gateway v8, sending intents is required to connect. However, your bot is probably using Gateway v6.
On v6, bots now get events from all intents they qualify for. This includes all non-privileged intents as well as all intents you have enabled (for bots in <100 servers) or all events you are whitelisted for (for bigger bots).

New versions of discord.py use Gateway v6 but send an intents value of all non-privileged intents by default, so if you want privileged intents you have to specify intents in your code.


Verified bots: Don't know if you are whitelisted? Click to see an image showing the states of the intent switches for verified bots.

To start out, we'll once again use the same code from the previous part and add to that. First, we have a modification we need to make to the bot.py file. Up until this point we've been using the default gateway intents that discord.py sends to the gateway - which is all except the privileged intents (server members and presences).

Before we can proceed to modify the code, we need to enable these privileged intents on the Discord developer portal. Go to your bot's bot page on the portal, and scroll down to the privileged intents section:

Beyond 100 servers you bot will need to be verified and whitelisted for these intents to be able to use them.

Privileged Intents

Now, you need to enable the server members intent, and click save to update the application.

Privileged Intents

Intents exist for a good reason - to reduce computational burden. On larger bots it may be an issue to have these intents enabled as it means Discord sends a lot more data to the bot, which may overwhelm it, although this should not be an issue for small or even fairly large bots. Even without the server members intent enabled, Discord will sometimes still provide you with members, such as in messages, voice state updates, etc. This means that you can often use them as members in things like commands, and they will populate the member cache too. The main thing to note is that with members intent disabled, you will not initially be given the member list, you will not receive member updates such as joins/leaves/nickname changes, and you will not be able to fetch members from the API.

With that done, let's get back to the code - this will be the last time we have to visit the developer portal for a while. First, we need to tell discord.py to use these intents when connecting to the gateway, which we'll do by creating an intents object with the default intents, and enabling members intent, after which the bot file will look like this:

This is a insecure way of setting the token used for brevity, please read this bonus part about storing tokens.

That's all that needed to enable intents, and now we can harness the full power of Discord gateway events! Now, we have to create the code that welcomes people, which we will stick in the somecommands.py for now, but you're free to make another file and another cog, and load it in the same way as before.

Again, this will be within the class, just under the commands we already have - but wait, this isn't a command, its an event. Luckily discord.py has us covered for events too, and provides listeners so that we can use them.

As with previous examples I'll show the code we need to use and then explain what the new bits do afterwards:

Next, we get a channel from the bot, this is the channel that we'll send the welcome message in. To do this we use self.bot.get_channel() to get a channel from the bot's cache of channels.

Note that I explicitly use the word get here, not fetch . This is because in discord.py, and now throughout this tutorial, get will refer to fetching something from the local cache, and fetch will mean fetching something from the API. It's important to distinguish which is which, because the get methods are synchronous, while fetch methods are asynchronous and must be awaited.

Now, you'll likely have noticed the long number in there, that's the channel's unique snowflake ID. All objects in Discord, be it a role, channel, guild, user, etc. have an ID (excluding things like permission overwrites which just map user and role IDs to a set of permissions) which can be found in the client by right clicking the object and clicking copy ID. To have this option you need to have developer mode enabled. Make sure to replace my channel ID with one of your own, or the message won't be sent!

Next, we need to check if we actually have a channel to send to, since it's not guaranteed, so we check if channel is truthy, and return if it isnt.

It's possible to mention the user without pinging them using a Discord feature called allowed mentions which discord.py has support for. If you would like to learn more about allowed mentions please read this bonus part. If you do decide to have the bot DM people on join do be careful - Discord will disable and quarantine a bot's access to DMing people if it DMs members too quickly. This applies in general not just with welcome messages.

That's it for this part - your bot should now have a fully functioning welcome message when new people join the server. If it doesn't work be sure to check that you have used the correct channel ID for the channel you want to send it in, and that the ID is an integer, not a string.

Читайте также: