Ctx discord py что это
Перейти к содержимому

Ctx discord py что это

  • автор:

Name already in use

discord.ext.context / README.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

A globally accessible context object for discord.py events.

Able to be used in both base clients and the commands extension.

  • Python 3.7+

Register a Discord bot/client

Subclass the context.ContextClient base class, ensuring that it’s first in inheritance order.

Import context.ctx from anywhere, and it’ll have its attributes set based on the event that your call stack originates from.

Accessing a context value before it’s set will have this exception raised. To have a fallback value used instead, use the contextmanager with ctx.default(): .

Should always be a PartialMessage . If a Message instance is needed, an up to date copy can be retrieved with PartialMessage.fetch() .

Often representing a reaction interacted with by a user; useful for user interactions that use reaction-based sessions.

Will always be a text channel or user-type object that’s possible to send messages to. Does not include voice channels.

If setting a discord.User instance and the user shares only a single guild with the client, it’ll replace it with the discord.Member instance.

Will only be set on guild-specific events.

Will only be set on the command event, with other EventContext values being set using it.

The name of the event type this context originates from.

The instance of the discord.py client being hooked into.

Alias for ctx.client .

ctx.set(*, message=None, emoji=None, user=None, channel=None, guild=None)

Sets the values for the current context to be used across future call stacks. Won’t impact asynchronous calls from other events.

Decorator for registering an event to be handled by the decorated function. Will override existing hooks if a duplicate exists.

ctx.default(all_default, *, message=_NoValue, emoji=_NoValue, user=_NoValue, channel=_NoValue, guild=_NoValue, cmd_ext=_NoValue)

Context manager for registering default values to be used if a value isn’t set. On leaving the context manager’s scope, ctx will revert to original state.

Use all_default to set all the available ctx.values to the one value. This can be useful for allowing None to be returned for nonset contexts.

If ctx.channel or ctx.user is not yet set, it’ll be assigned the fallback arguments. This includes being able to set a value to None instead of raising ContextNotSet .

It can also be used as a decorator for a function.

ctx.ephemeral(*, message=_NoValue, emoji=_NoValue, user=_NoValue, channel=_NoValue, guild=_NoValue, cmd_ext=_NoValue)

Context manager for overriding context values. On leaving the context manager’s scope, ctx will revert to original state.

If ctx.channel or ctx.user is not yet set, it’ll be assigned the fallback arguments. This includes being able to set a value to None instead of raising ContextNotSet .

It can also be used as a decorator for a function.

By default, the following events are hooked by EventContext:

  • message
  • message_delete
  • message_edit
  • raw_message_delete
  • raw_message_edit
  • reaction_add
  • reaction_remove
  • raw_reaction_add
  • raw_reaction_remove
  • reaction_clear
  • reaction_clear_emoji
  • raw_reaction_clear
  • raw_reaction_clear_emoji
  • typing
  • guild_channel_update
  • guild_channel_create
  • guild_channel_delete
  • guild_channel_pins_update
  • webhooks_update
  • guild_update
  • guild_join
  • guild_remove
  • guild_integrations_update
  • guild_emojis_update
  • guild_available
  • guild_unavailable
  • member_update
  • member_join
  • member_remove
  • member_ban_hook
  • member_unban_hook
  • guild_role_update_hook
  • guild_role_create_hook
  • guild_role_delete_hook
  • command

You can add more event hooks or replace the default ones with the decorator:

Footer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Бот для Discord API на Python (discord.py) с командами

Бот для Discord API на Python (discord.py) с командами

Сегодня разберём создание бота для популярной соцсети Discord. Эта платформа предназначена для общения посредством голосовых чатов и сообщений и чем-то схожа с телеграмом.

Недавно я столкнулся с задачей написания подобного бота. Поскольку на просторах интернета, нет внятных гайдов, решил сделать свой. Про официальную документацию можно не говорить, там чёрт ногу сломит. В YouTube охватывают лишь самое начало. Я постараюсь более детально погрузиться в discord.py и работу с Discord API.

Структура проекта и установка библиотек

  1. Компьютер или ноутбук
  2. Редактор кода (Notepad++ тоже подойдет).
  3. Python версии 3.9 и выше.
  4. Соединение с интернетом

Установка для Windows:

Установка для MacOS:

Структура максимально простая, все модули для обработки команд будут храниться в директории cogs. Остальное можно структурировать как угодно.

Создание бота и получение токена

Заходим на этот сайт https://discord.com/developers/docs/intro и нажимаем на «applications». После проходим авторизацию (видео инструкция тут ).

Создаем новое приложение:

Дальше переходим во вкладку Bot и создаем бота. Тут вы сможет создать и скопировать токен:

После всех манипуляций выбираем уровень доступа для бота — administrator.

Как добавить бота на сервер

Переходим во вкладку OAuth2 General, ставим такие настройки и сохраняем:

Потом переходим в URL General, выбираем те же самые настройки и копируем ссылку ниже:

Переходим по ссылке и выбираем на какой сервер хотим добавить бота. Добавлять можно только на тот сервер, который вы администрируете (у вас есть права администратора на нем). Дальше следуем иструкциям Discord.

Разработка бота

Main.py

Подробнее остановимся на commands и config .

В commands будет инициализироваться и храниться бот. В дальнейшем через этот объект класса будем обращаться к методам.

Config – там будут храниться все глобальные переменные — токены, ID каналов, ID ролей и т д.

discord_intents – мы наделяем бота полными правами доступа (когда будем добавлять его, то он запросит разрешение для управления)

bot – тут собирается бот. Аргументы: command_prefix — на какой спец символ будет откликаться бот; intents — права доступа.

Пробежимся по функциям.

On_ready – срабатывает при загрузке бота. bot.change_presence — тут мы устанавливаем активность (Discord может показывать во что вы сейчас играете).

Дальше подгружаются все винтики. Почему пакеты в Discord называют винтики? Потому что в официальной документации разработчики назвали именно так;)

Load и unload — позволяют отключить и подключить винтики. Загрузка происходит с помощью обращения к методам объекта бота.

Reload — по сути вызывает по очереди unload и load.

Цикл for перебирает все файлы и загружает их в первый раз.

Ну и в конце мы запускаем бота, передавая в него токен.

Config.py

Этот файл будет хранить в себе только служебные переменные — токены, ID ролей, ID серверов.

Директория cogs

Everyone.py

В этом файле будут храниться все команды доступные обычному пользователю. Импорты отдельно разбирать не буду, там и так все понятно.

Вероятно, вы спросите что это за класс. Everyone наследуется от commands.Cog . Винтики работают за счёт объектов — когда мы запускаем бота, то перебираем все объекты и собираем всё вместе.

Для отслеживания команд мы используем декоратор commands.command() . Для корректной работы при создании класса мы передаём в него нашего бота. Дальше описываем в методах логику.

Функция info будет высылать пользователю embed (сообщение) с указанием доступных команд. Внутрь функции передаем ctx (полное его название context) — это полученное сообщение.

Мы создаем объект, в который передаем: заголовок, свет линии с краю, подпись автора и ссылку на изображение. Дальше, обращаясь к методу add_field , добавляем строки с именем и значением — можно их назвать заголовок и текст.

Метод set_footer добавляет маленькую подпись в конце сообщения. В завершение мы обращаемся к await ctx.channel.purge(limit=1) , что удаляет одно сообщение (можно указать любое количество в limit). Await позволяет нам дождаться окончания асинхронного метода.

После этого отправляем сообщение с помощью await ctx.send(embed=embed) , передавая внутрь сформированное сообщение. Или можно просто отправить текст await ctx.send(text=”your message”) .

Эта конструкция нужна библиотеке, что бы она могла увидеть и загрузить винтик:

Удобный конструктор embed, который сразу выдает python код, находится тут .

Moder.py

Пройдёмся по функциям сверху вниз.

@commands.has_any_role(config.admin_id_role) — это новый декоратор, он проверяет есть ли у пользователя роль (нужен ID роли). Также можно указывать перечень ролей в массиве (для этого распаковывайте массив).

Mute принимает в себя само сообщение, пользователя (пример @user), и причину. Первым делом мы заготавливаем объект чата, в который будем присылать действия администратора. Потом сам сервер (в документации discord.py сервер называется гильдия). И в конце получаем роль, которую будем давать пользователю.

Когда всё готово, собираем сообщение-уведомление (не забывайте пользоваться конструктором embed тут ). Дальше к объекту пользователя добавляем роль. И отправляем сообщение в логи и в чат, откуда пришла команда. Не забываем удалять отправленную команду.

Unmute зеркальна с функций mute, только для пользователя мы используем метод remove role .

Ban — выгоняет пользователя с сервера и добавляет его в черный список (в дальнейшем его не смогут пригласить на сервер пока он в ЧС).

Для работы в переменных нам потребуется только канал для системы логов. Следом проходим процедуру сборки красивого сообщения и отправляем его как в mute.

Unban — не просто зеркальная функция, потому что тут нам потребуется обращаться к списку ЧС. banned_users делает запрос к ЧС сервера. Дальше мы делаем полный перебор всех заблокированных и сравниваем с нашим пользователем. Как только находим его, убираем юзера из списка и выводим сообщение о разблокировке.

Kick — с этой функций дела обстоят намного проще, так как у пользователя есть метод для изгнания user.kick .

Clear — последняя возможность для администрирования. В нее поступает не только сообщение, но и количество сообщений, которое нужно удалить. Дальше идет защита от опечатки.

ctx.channel.purge(limit=int(amount)) отвечает за удаление сообщений, в limit передаем полученное значение.

Заключение

Библиотека discord.py не проста в понимании и требует много времени на разбор. Но лучших аналогов для Python не найти из-за обширности API.

Если захотите разобраться глубже, самостоятельно изучайте новые методы и классы. Производите глубокий анализ, что откуда исходит (какой вы получаете объект в ответе и как его можно получить еще).

Для дальнейшего развития советую попытаться добавить в бота интеграцию с базой данных. Например есть хорошая БД MongoDB — на ней можно простроить мощную многоуровневую систему администрирования сервера.

Creating commands

This page is a follow-up, and the base code used is from the previous page (Initial files). The code can be found on the GitHub repository here.

Discord also allows developers to register slash commands, which provides users a first-class way of interacting directly with your application. These slash commands shall be covered by the guide here, in the Interactions section.

A note on prefix commands​

Bot commands that are initiated when a keyword is used along with a specified prefix (such as ! or $ ) are known as prefix commands (are also often referred to as text commands).

Message Intent — Privileged

It is to be noted that handling prefix commands require the message intent, which allows the bot to get content and data of messages sent by users. This intent has recently been privileged, i.e., it needs to be manually enabled for the bot application, and its requirement will eventually be reviewed if your bot is in over 100 servers.

You can read more about the message intent here.

Therefore, to minimize the permissions your bot has to use, we will be covering prefix commands under the Popular Topics section, and advancing with the basics of slash commands in this article; more advanced topics of the same will be covered in the Interactions section.

Registering commands​

This section covers the bare minimum to get you started with registering slash commands. Once again, you can refer to this page for an in-depth coverage of topics, including guild commands, global commands, options, option types, autocomplete and choices.

Now, we shall continue with the base code used in the previous section.

The first step is to use the @bot.slash_command coroutine, along with an async function in order to define the code for your slash command. Below is a script demonstrating the same (focus on the use of inter , which is short for interaction ).

The inter passed into the function is analogous to context, or ctx used in prefix commands — it passes through all information relative to the interaction — data regarding the user who initiated the command, as an example. It is also necessary for replying to the use of the command.

Using ctx vs. inter

If you have experience with coding bots with discord.py , you would be familiar with using ctx as an abbreviation for passing context into the function. This guide will primarily be using inter , as it is short for interaction and refers to ApplicationCommandInteraction . Of course, you're open to using your preferred abbreviation in code.

Registering commands in specific guilds​

Note that servers are referred to as "guilds" in the Discord API and disnake library. On running the above code, the slash command will be registered globally, and will be accessible on all servers the bot is in.

You can also use the guild_ids argument for the command to only be registered in a list of specified servers, for example your development server.

Using test_guilds in commands.Bot()

When you have multiple commands registered under the same test guilds, it is convenient to only have your guild_ids defined once. Therefore, you can use the test_guilds argument in the commands.Bot() instance instead of passing guild_ids to every single command —

Now that you're all set with registering the slash command, you can proceed with responding to the initiated command.

Ctx discord py что это

Using the commands extension

Breaking it down

If you noticed, we changed the client variable to bot , just for the sake of understandability. We also imported the commands module from discord library, changed discord.Client() and created an instance of commands.Bot using commands.Bot(command_prefix = «!») . Note that commands.Bot() inherits all attributes and methods of the discord.Client() class.

Now you may be wondering what await bot.process_commands(message) does. It tells the bot, to check the messages and process them as commands if possible. If you forget to add this line, the bot will not process the commands you write afterwards.

Now we can use the @bot.command() decorator to define commands. As you can see, the ping command is defined on the next line. We provide the argument parameters inside the brackets. The ctx parameter is necessary as the first argument of every command.

Since we use async/await in discord.py, await ctx.send() will be used to send messages. It will send the message provided as argument in the channel where the command is used.

ctx stands for commands.Context . ctx basically contains all the information you need to know about how the command was invoked. For example, ctx.send() is as the same as ctx.channel.send() , where ctx.channel refers to the channel where the command was invoked.

ctx.channel returns data as discord.TextChannel instance. You can also access the channel ID and name, using ctx.channel.id and ctx.channel.name . There’s a whole lot of data you can use from the discord.TextChannel class.

Same way, you can also access the server where the command was used. In discord.py[rewrite], we use the term guild in place of server . So ctx.guild will return data in discord.Guild instance. Once again, you can use alot of stuff accessed from the discord.Guild class.

Now if you want to send the message to the command author instead, that is, the member who used the command, you can simply use ctx.author.send() to send a direct message to the command author. ctx.author can also be used to access other stuff such as name, id and avatar of the command author

Now let’s go ahead, run the bot, and test it on discord.

As you can see, the bot replied with «Pong!» right after the command.
Congrats! You just made your very first command using discord.py!

We have created a collection of the resultant code we end up with at the end of every tutorial. The repository is available right here on this website. You can click here to get list of contents in our repository.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *