Что такое guild в дискорде

Discord сервер и гильдия-чат сообщества

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

Всем привет. Напоминаем, что у нашего русскоязычного сообщества есть свой Discord сервер, на котором вы всегда можете задать вопросы другим игрокам, найти новых знакомых, гильдии, или просто компанию на несколько часов игры. Также для удобства игроков была создана «гильдия-чат», которая позволит вам все то же самое только прямо в игре.

Некоторое время гильдия находилась в режиме тестирования и неплохо себя показала, так что было решено далее её развивать.
Гильдия создана не для того, чтобы стать крупной ГИ, добивающейся чего-либо. По сути, это выделенный внутриигровой чат, где вы сможете найти русскоязычных игроков, находящихся на данный момент в игре, и пойти с ними по своим игровым делам.
Репрезента не требуется, каких-либо сборов, обязательств и требований (кроме как нормально общаться и не нарушать банальных правил хорошего тона) нет.

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

Получился вполне удобный инструмент для поиска новых друзей, товарищей и согильдийцев.
Чтобы получить приглашение в гильдию, напишите ник в выделенный канал в дискорде (#community_guild) и ждите приглашения в игре.

И еще раз ссылка для входа на Discord сервер — https://discord.gg/cAPSahg

Ну и не забываем про сообщество в VK, где вам также ответят на вопросы по игре и где есть выделенные темы для поиска друзей и гильдий.

Источник

Вступление

Всем привет! Недавно я написал Discord бота для World of Warcraft гильдии. Он регулярно забирает данные об игроках с серверов игры и пишет сообщения в Discord о том что к гильдии присоединился новый игрок или о том что гильдию покинул старый игрок. Между собой мы прозвали этого бота Батрак.

От вас не потребуется никаких знаний об игре. Я написал материал так чтобы можно было абстрагироваться от игры и сделал заглушку для данных об игроках. Но если у вас есть учетная запись в Battle.net, то вы сможете получать реальные данные.

Для понимания материала, от вас ожидается хотя бы минимальный опыт создания веб сервисов с помощью фреймворка ASP.NET и небольшой опыт работы с Docker.

На каждом шаге будем постепенно наращивать функционал.

Создадим новый web api проект с одним контроллером /check. При обращении к этому адресу будем отправлять строку “Hello!” в Discord чат.

Научимся получать данные о составе гильдии с помощью готовой библиотеки или заглушки.

Научимся сохранять в кэш полученный список игроков чтобы при следующих проверках находить различия с предыдущей версией списка. Обо всех изменениях будем писать в Discord.

Напишем Dockerfile для нашего проекта и разместим проект на хостинге Heroku.

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

Реализуем автоматическую сборку, запуск тестов и публикацию проекта после каждого коммита в master

Шаг 1. Отправляем сообщение в Discord

Нам потребуется создать новый ASP.NET Core Web API проект.

Добавим к проекту новый контроллер

Получить его можно в пункте integrations в настройках любого текстового канала вашего Discord сервера.

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискордеСоздание webhook

Добавим webhook в appsettings.json нашего проекта. Позже мы унесем его в переменные окружения Heroku. Если вы не знакомы с тем как работать с конфигурацией в ASP Core проектах предварительно изучите эту тему.

Теперь создадим новый сервис DiscordBroker, который умеет отправлять сообщения в Discord. Создайте папку Services и поместите туда новый класс, эта папка нам еще пригодится.

По сути этот новый сервис делает post запрос по адресу из webhook и содержит сообщение в теле запроса.

Как видите, мы используем внедрение зависимостей. IConfiguration позволит нам достать webhook из конфигов, а IHttpClientFactory создать новый HttpClient.

Кроме того, я извлек интерфейс этого класса, чтобы в дальнейшем можно было сделать его заглушку при тестировании. Делайте это для всех сервисов которые мы будем создавать далее.

Не забудьте что новый класс нужно будет зарегистрировать в Startup.

А также нужно будет зарегистрировать HttpClient, для работы IHttpClientFactory.

Теперь можно воспользоваться новым классом в контроллере.

Запустите проект, зайдите по адресу /check в браузере и убедитесь что в Discord пришло новое сообщение.

Шаг 2. Получаем данные из Battle.net

У нас есть два варианта: получать данные из настоящих серверов battle.net или из моей заглушки. Если у вас нет аккаунта в battle.net, то пропустите следующий кусок статьи до момента где приводится реализация заглушки.

Получаем реальные данные

Вам понадобится зайти на https://develop.battle.net/ и получить там две персональных строки BattleNetId и BattleNetSecret. Они будут нужны нам чтобы авторизоваться в api перед отправкой запросов. Поместите их в appsettings.

Подключим к проекту библиотеку ArgentPonyWarcraftClient.

Создадим новый класс BattleNetApiClient в папке Services.

В конструкторе мы создаем новый экземпляр класса WarcraftClient.
Этот класс относится к библиотеке, которую мы установили ранее. С его помощью можно получать данные об игроках.

Кроме этого, нужно создать в appsettings проекта две новых записи RealmName и GuildName. RealmName это название игрового мира, а GuildName это название гильдии. Их будем использовать как параметры при запросе.

Сделаем метод GetGuildMembers чтобы получать состав гильдии и создадим модель WowCharacterToken которая будет представлять собой информацию об игроке.

Класс WowCharacterToken следует поместить в папку Models.

Не забудьте подключить BattleNetApiClient в Startup.

Берем данные из заглушки

Для начала создадим модель WowCharacterToken и поместим ее в папку Models. Она представляет собой информацию об игроке.

Дальше сделаем вот такой класс

Он возвращает зашитый в него список игроков. При первом вызове метода мы вернем один список, при последующих другой. Это нужно нам что смоделировать изменчивое поведение api. Этой заглушки хватит чтобы продолжить делать проект.

Сделайте интерфейс и подключите все что мы создали в Startup.

Выведем результаты в Discord

После того как мы сделали BattleNetApiClient, им можно воспользоваться в контроллере чтобы вывести кол-во игроков в Discord.

Шаг 3. Находим новых и ушедших игроков

Нужно научиться определять какие игроки появились или пропали из списка при последующих запросах к api. Для этого мы можем закэшировать список в InMemory кэше (в оперативной памяти) или во внешнем хранилище.

Если закэшировать список в InMemory кэше, то мы потеряем его при перезапуске приложения. Поэтому позже мы подключим базу данных Redis как аддон в Heroku и будем кешировать туда.

А пока что подключим InMemory кэш в Startup.

GuildRepository нужно зарегистрировать как Singletone зависимость, чтобы кэш не пересоздавался на каждый запрос.

Теперь можно написать сервис который будет сравнивать новый список игроков с сохраненным.

В качестве возвращаемого результата используется модель Report. Ее нужно создать и поместить в папку Models.

Применим GuildService в контроллере.

Теперь отправим в Discord какие игроки присоединились или покинули гильдию.

Эту логику я добавил в GuildService в конец метода Check. Писать бизнес логику в контроллере не стоит, у него другое назначение. В самом начале мы делали там отправку сообщения в Discord потому что еще не существовало GuildService.

Можно вывести больше информации об игроке. Ее можно получить если воспользоваться библиотекой ArgentPonyWarcraftClient

Я решил не добавлять в статью больше кода в BattleNetApiClient, чтобы статья не разрослась до безумных размеров.

Unit тесты

У нас появился класс GuildService с нетривиальной логикой, который будет изменяться и расширяться в будущем. Стоит написать на него тесты. Для этого нужно будет сделать заглушки для BattleNetApiClient, GuildRepository и DiscordBroker. Я специально просил создавать интерфейсы для этих классов чтобы можно было сделать их фейки.

Создайте новый проект для Unit тестов. Заведите в нем папку Fakes и сделайте три фейка.

Эти фейки позволяют заранее задать возвращаемое значение для методов. Для этих же целей можно использовать популярную библиотеку Moq. Но для нашего простого примера достаточно самодельных фейков.

Первый тест на GuildService будет выглядеть так:

Как видно из названия, тест позволяет проверить что мы сохраним список игроков, если кэш пуст. Заметьте, в конце теста используется специальный набор методов Should, Be. Это методы из библиотеки FluentAssertions, которые помогают нам сделать Assertion более читабельным.

Теперь у нас есть база для написания тестов. Я показал вам основную идею, дальнейшее написание тестов оставляю вам.

Главный функционал проекта готов. Теперь можно подумать о его публикации.

Шаг 4. Привет Docker и Heroku!

Чтобы упаковать проект в Docker нам понадобится создать в корне репозитория Dockerfile со следующим содержимым

peon.dll это название моего Solution. Peon переводится как батрак.

О том как работать с Docker и Heroku можно прочитать здесь. Но я все же опишу последовательность действий.

Вам понадобится создать аккаунт в Heroku, установить Heroku CLI.

Создайте новый проект в heroku и свяжите его с вашим репозиторием.

Теперь нам необходимо создать файл heroku.yml в папке с проектом. У него будет такое содержимое:

Дальше выполним небольшую череду команд:

Можете открыть приложение в браузере с помощью команды:

После того как мы разместили приложение в Heroku, нужно подключить базу данных Redis для кэша. Как вы помните InMemory кэш будет исчезать после перезапуска приложения.

Установите для нашего Heroku приложения бесплатный аддон RedisCloud.

Строку подключения для Redis можно будет получить через переменную окружения REDISCLOUD_URL. Она будет доступна, когда приложение будет запущено в экосистеме Heroku.

Нам нужно получить эту переменную в коде приложения.

С помощью нее можно зарегистрировать Redis реализацию для IDistributedCache в Startup.

В этом коде мы получили переменную REDISCLOUD_URL из переменных окружения системы. После этого мы извлекли адрес и пароль базы данных с помощью класса RedisUtils. Его написал я сам:

На этот класс можно сделать простой Unit тест.

После того что мы сделали, GuildRepository будет сохранять кэш не в оперативную память, а в Redis. Нам даже не нужно ничего менять в коде приложения.

Опубликуйте новую версию приложения.

Шаг 5. Реализуем циклическое выполнение

Нам нужно сделать так чтобы проверка состава гильдии происходила регулярно, например каждые 15 минут.

Есть несколько способов это реализовать:

Шаг 6. Автоматическая сборка, прогон тестов и публикация

Во-первых, зайдите в настройки приложения в Heroku.

Там есть пункт Deploy. Подключите там свой Github аккаунт и включите Automatic deploys после каждого коммита в master.

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

Поставьте галочку у пункта Wait for CI to pass before deploy. Нам нужно чтобы Heroku дожидался сборки и прогонки тестов. Если тесты покраснеют, то публикация не случится.

Сделаем сборку и прогонку тестов в Github Actions.

Зайдите в репозиторий и перейдите в пункт Actions. Теперь создайте новый workflow на основе шаблона .NET

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

В репозитории появится новый файл dotnet.yml. Он описывает процесс сборки.

Как видите по его содержимому, задание build будет запускаться после пуша в ветку master.

Содержимое самого задания нас полностью устраивает. Если вы вчитаетесь в то что там происходит, то увидите что там происходит запуск команд dotnet build и dotnet test.

Менять в этом файле ничего не нужно, все уже будет работать из коробки.

Запушьте что-нибудь в master и посмотрите что задание запускается. Кстати, оно уже должно было запуститься после создания нового workflow.

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

Надеюсь данная статья подкинула вам пару новых идей и тем для изучения. Спасибо за внимание. Удачи вам в ваших проектах!

Источник

Что такое шард в дискорд боте?

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

Шардирование (горизонтальное партиционирование) — это принцип проектирования базы данных, при котором логически независимые строки таблицы базы данных хранятся раздельно, заранее сгруппированные в секции, которые, в свою очередь, размещаются на разных, физически и логически независимых серверах базы данных, при этом один физический узел кластера может содержать несколько серверов баз данных.

Что такое guild в дискорде. Смотреть фото Что такое guild в дискорде. Смотреть картинку Что такое guild в дискорде. Картинка про Что такое guild в дискорде. Фото Что такое guild в дискорде

As bots grow and are added to an increasing number of guilds, some developers may find it necessary to break or split portions of their bots operations into separate logical processes. As such, Discord gateways implement a method of user-controlled guild sharding which allows for splitting events across a number of gateway connections. Guild sharding is entirely user controlled, and requires no state-sharing between separate connections to operate

В то время как боты растут, и растёт количество серверов, некоторые разработчики могут посчитать нужным разбавлять или разделять операции ботов на несколько логических процессов. Поэтому, Discord gateway (то, к чему бот подключается через websockets для прослушивания событий, и контроля статуса) представляют метод разделения серверов пользователем, который допускает разделение событий на несколько подключений к gateway. Разделение серверов полностью контроллируется пользователем, и не требует общего доступа меж разных подключений для управления.

Источник

Class DiscordGuild

Represents a Discord guild.

Inheritance
Inherited Members
Namespace: DSharpPlus.Entities
Assembly: cs.temp.dll.dll
Syntax

Properties

AfkChannel

Gets the guild’s AFK voice channel.

Declaration
Property Value

AfkTimeout

Gets the guild’s AFK timeout.

Declaration
Property Value

ApplicationId

Gets the application id of this guild if it is bot created.

Declaration
Property Value

ApproximateMemberCount

Gets the approximate number of members in this guild, when using GetGuildAsync(UInt64, Nullable ) and having withCounts set to true.

Declaration
Property Value

ApproximatePresenceCount

Gets the approximate number of presences in this guild, when using GetGuildAsync(UInt64, Nullable ) and having withCounts set to true.

Declaration
Property Value

Banner

Gets this guild’s banner hash, when applicable.

Declaration
Property Value

BannerUrl

Gets this guild’s banner in url form.

Declaration
Property Value

Channels

Gets a dictionary of all the channels associated with this guild. The dictionary’s key is the channel ID.

Declaration
Property Value

CurrentMember

Gets the guild member for current user.

Declaration
Property Value

DefaultMessageNotifications

Gets the guild’s default notification settings.

Declaration
Property Value

Description

Gets the guild description, when applicable.

Declaration
Property Value

DiscoverySplashHash

Gets the guild discovery splash’s hash.

Declaration
Property Value

DiscoverySplashUrl

Gets the guild discovery splash’s url.

Declaration
Property Value

Emojis

Gets a collection of this guild’s emojis.

Declaration
Property Value

EveryoneRole

Gets the @everyone role for this guild.

Declaration
Property Value

ExplicitContentFilter

Gets the guild’s explicit content filter settings.

Declaration
Property Value

Features

Gets a collection of this guild’s features.

Declaration
Property Value

IconHash

Gets the guild icon’s hash.

Declaration
Property Value

IconUrl

Gets the guild icon’s url.

Declaration
Property Value

IsLarge

Gets whether this guild is considered to be a large guild.

Declaration
Property Value

IsNSFW

Gets whether this guild is designated as NSFW.

Declaration
Property Value

IsOwner

Gets whether the current user is the guild’s owner.

Declaration
Property Value

IsUnavailable

Gets whether this guild is unavailable.

Declaration
Property Value

JoinedAt

Gets this guild’s join date.

Declaration
Property Value

MaxMembers

Gets the maximum amount of members allowed for this guild.

Declaration
Property Value

MaxPresences

Gets the maximum amount of presences allowed for this guild.

Declaration
Property Value

MaxVideoChannelUsers

Gets the maximum amount of users allowed per video channel.

Declaration
Property Value

MemberCount

Gets the total number of members in this guild.

Declaration
Property Value

Members

Gets a dictionary of all the members that belong to this guild. The dictionary’s key is the member ID.

Declaration
Property Value

MfaLevel

Gets the required multi-factor authentication level for this guild.

Declaration
Property Value

Gets the guild’s name.

Declaration
Property Value

NsfwLevel

Gets the guild’s nsfw level.

Declaration
Property Value

Owner

Gets the guild’s owner.

Declaration
Property Value

OwnerId

Gets the ID of the guild’s owner.

Declaration
Property Value

Permissions

Gets permissions for the user in the guild (does not include channel overrides)

Declaration
Property Value

PreferredLocale

Gets the preferred locale of this guild.

This is used for server discovery and notices from Discord. Defaults to en-US.

Declaration
Property Value

PremiumSubscriptionCount

Gets the amount of members that boosted this guild.

Declaration
Property Value

PremiumTier

Gets this guild’s premium tier (Nitro boosting).

Declaration
Property Value

PublicUpdatesChannel

Gets the public updates channel (where admins and moderators receive messages from Discord) for this guild.

This is only available if the guild is considered «discoverable».

Declaration
Property Value

Roles

Gets a collection of this guild’s roles.

Declaration
Property Value

RulesChannel

Gets the rules channel for this guild.

This is only available if the guild is considered «discoverable».

Declaration
Property Value

SplashHash

Gets the guild splash’s hash.

Declaration
Property Value

SplashUrl

Gets the guild splash’s url.

Declaration
Property Value

Stickers

Gets a collection of this guild’s stickers.

Declaration
Property Value

SystemChannel

Gets the channel where system messages (such as boost and welcome messages) are sent.

Declaration
Property Value

SystemChannelFlags

Gets the settings for this guild’s system channel.

Declaration
Property Value

VanityUrlCode

Gets the vanity URL code for this guild, when applicable.

Declaration
Property Value

VerificationLevel

Gets the guild’s verification level.

Declaration
Property Value

VoiceRegion

Gets the guild’s voice region.

Declaration
Property Value

VoiceStates

Gets a dictionary of all the voice states for this guilds. The key for this dictionary is the ID of the user the voice state corresponds to.

Declaration
Property Value

WidgetChannel

Gets the widget channel for this guild.

Declaration
Property Value

WidgetEnabled

Gets whether this guild’s widget is enabled.

Declaration
Property Value

Methods

Adds a new member to this guild

Declaration
Parameters

User’s access token (OAuth2)

whether this user has to be muted

whether this user has to be deafened

Returns
Exceptions

Thrown when the client does not have the CreateInstantInvite permission.

Thrown when the user or access_token is not found.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

AttachUserIntegrationAsync(DiscordIntegration)

Attaches an integration from current user to this guild.

Declaration
Parameters

Integration to attach.

Returns

The integration after being attached to the guild.

Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

BanMemberAsync(DiscordMember, Int32, String)

Bans a specified member from this guild.

Declaration
Parameters

How many days to remove messages from.

Reason for audit logs.

Returns
Exceptions

Thrown when the client does not have the BanMembers permission.

Thrown when the member does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

BanMemberAsync(UInt64, Int32, String)

Bans a specified user by ID. This doesn’t require the user to be in this guild.

Declaration
Parameters

ID of the user to ban.

How many days to remove messages from.

Reason for audit logs.

Returns
Exceptions

Thrown when the client does not have the BanMembers permission.

Thrown when the member does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

BatchEditApplicationCommandPermissionsAsync(IEnumerable )

Batch edits permissions for a slash command in this guild.

Declaration
Parameters

The list of permissions to use.

Returns

A list of edited permissions.

BulkOverwriteApplicationCommandsAsync(IEnumerable )

Overwrites the existing slash commands in this guild. New commands are automatically created and missing commands are automatically delete

Declaration
Parameters

The list of commands to overwrite with.

Returns

The list of guild commands

CreateApplicationCommandAsync(DiscordApplicationCommand)

Creates or overwrites a slash command in this guild.

Declaration
Parameters

The command to create.

Returns

The created command.

Creates a new channel in this guild.

Declaration
Parameters

Name of the new channel.

Type of the new channel.

Category to put this channel in.

Topic of the channel.

Bitrate of the channel. Applies to voice only.

Maximum number of users in the channel. Applies to voice only.

Permission overwrites for this channel.

Whether the channel is to be flagged as not safe for work. Applies to text only.

Slow mode timeout for users.

Video quality mode of the channel. Applies to voice only.

Reason for audit logs.

Returns

The newly-created channel.

Exceptions

Thrown when the client does not have the ManageChannels permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Creates a new channel category in this guild.

Declaration
Parameters

Name of the new category.

Permission overwrites for this category.

Reason for audit logs.

Returns

The newly-created channel category.

Exceptions

Thrown when the client does not have the ManageChannels permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Creates a new custom emoji for this guild.

Declaration
Parameters

Name of the new emoji.

Image to use as the emoji.

Roles for which the emoji will be available. This works only if your application is whitelisted as integration.

Reason for audit log.

Returns

The newly-created emoji.

Exceptions

Thrown when the client does not have the ManageEmojis permission.

Thrown when Discord is unable to process the request.

CreateRoleAsync(String, Nullable

Creates a new role in this guild.

Declaration
Parameters

Permissions for the role.

Color for the role.

Whether the role is to be hoisted.

Whether the role is to be mentionable.

Reason for audit logs.

Returns

The newly-created role.

Exceptions

Thrown when the client does not have the ManageRoles permission.

Thrown when Discord is unable to process the request.

CreateStickerAsync(String, String, String, Stream, StickerFormat)

Creates a sticker in this guild.

Declaration
Parameters

The name of the sticker.

The description of the sticker.

The tags of the sticker.

The image content of the sticker.

The image format of the sticker.

Returns

CreateTemplateAsync(String, String)

Creates a guild template.

Declaration
Parameters

Name of the template.

Description of the template.

Returns

The template created.

Exceptions

Throws when a template already exists for the guild or a null parameter is provided for the name.

Throws when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

Creates a new text channel in this guild.

Declaration
Parameters

Name of the new channel.

Category to put this channel in.

Topic of the channel.

Permission overwrites for this channel.

Whether the channel is to be flagged as not safe for work.

Slow mode timeout for users.

Reason for audit logs.

Returns

The newly-created channel.

Exceptions

Thrown when the client does not have the ManageChannels permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Creates a new voice channel in this guild.

Declaration
Parameters

Name of the new channel.

Category to put this channel in.

Bitrate of the channel.

Maximum number of users in the channel.

Permission overwrites for this channel.

Video quality mode of the channel.

Reason for audit logs.

Returns

The newly-created channel.

Exceptions

Thrown when the client does not have the ManageChannels permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

DeleteAllChannelsAsync()

Deletes all channels in this guild.

Note that this is irreversible. Use carefully!

Declaration
Returns

DeleteAsync()

Deletes this guild. Requires the caller to be the owner of the guild.

Declaration
Returns
Exceptions

Thrown when the client is not the owner of the guild.

Thrown when Discord is unable to process the request.

DeleteEmojiAsync(DiscordGuildEmoji, String)

Deletes this guild’s custom emoji.

Declaration
Parameters

Reason for audit log.

Returns
Exceptions

Thrown when the client does not have the ManageEmojis permission.

Thrown when Discord is unable to process the request.

DeleteIntegrationAsync(DiscordIntegration)

Removes an integration from this guild.

Declaration
Parameters

Integration to remove.

Returns
Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

DeleteStickerAsync(UInt64)

Declaration
Parameters
Returns

DeleteTemplateAsync(String)

Deletes the template.

Declaration
Parameters

The code of the template to delete.

Returns

The deleted template.

Exceptions

Throws when the template for the code cannot be found

Throws when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

EditApplicationCommandAsync(UInt64, Action)

Edits a slash command in this guild.

Declaration
Parameters

The id of the command to edit.

Returns

EditApplicationCommandPermissionsAsync(DiscordApplicationCommand, IEnumerable )

Edits permissions for a slash command in this guild.

Declaration
Parameters

The command to edit permissions for.

The list of permissions to use.

Returns

The edited permissions.

Equals(DiscordGuild)

Checks whether this DiscordGuild is equal to another DiscordGuild.

Declaration
Parameters
Returns

Whether the DiscordGuild is equal to this DiscordGuild.

Equals(Object)

Checks whether this DiscordGuild is equal to another object.

Declaration
Parameters

Object to compare to.

Returns

Whether the object is equal to this DiscordGuild.

Overrides

GetAllMembersAsync()

Retrieves a full list of members from Discord. This method will bypass cache.

Declaration
Returns

A collection of all members in this guild.

Exceptions

Thrown when Discord is unable to process the request.

GetApplicationCommandPermissionsAsync(DiscordApplicationCommand)

Gets permissions for a slash command in this guild.

Declaration
Parameters

The command to get them for.

Returns

GetApplicationCommandsAsync()

Gets all the slash commands in this guild.

Declaration
Returns

A list of slash commands in this guild.

GetApplicationCommandsPermissionsAsync()

Gets all slash command permissions in this guild.

Declaration
Returns

A list of permissions.

Gets audit log entries for this guild.

Declaration
Parameters

Maximum number of entries to fetch.

Filter by member responsible.

Filter by action type.

Returns

A collection of requested audit log entries.

Exceptions

Thrown when the client does not have the ViewAuditLog permission.

Thrown when Discord is unable to process the request.

GetBanAsync(DiscordUser)

Gets a ban for a specific user.

Declaration
Parameters

The user to get the ban for.

Returns

The requested ban object.

GetBanAsync(UInt64)

Gets a ban for a specific user.

Declaration
Parameters

The Id of the user to get the ban for.

Returns

The requested ban object.

GetBansAsync()

Gets the bans for this guild.

Declaration
Returns

Collection of bans in this guild.

Exceptions

Thrown when the client does not have the BanMembers permission.

Thrown when Discord is unable to process the request.

GetChannel(UInt64)

Gets a channel from this guild by its ID.

Declaration
Parameters

ID of the channel to get.

Returns
Exceptions

Thrown when Discord is unable to process the request.

GetChannelsAsync()

Gets all the channels this guild has.

Declaration
Returns

A collection of this guild’s channels.

Exceptions

Thrown when Discord is unable to process the request.

GetDefaultChannel()

Gets the default channel for this guild.

Default channel is the first channel current member can see.

Declaration
Returns

This member’s default guild.

Exceptions

Thrown when Discord is unable to process the request.

GetEmojiAsync(UInt64)

Gets this guild’s specified custom emoji.

Declaration
Parameters

ID of the emoji to get.

Returns

The requested custom emoji.

Exceptions

Thrown when Discord is unable to process the request.

GetEmojisAsync()

Gets all of this guild’s custom emojis.

Declaration
Returns

All of this guild’s custom emojis.

Exceptions

Thrown when Discord is unable to process the request.

GetHashCode()

Gets the hash code for this DiscordGuild.

Declaration
Returns

The hash code for this DiscordGuild.

Overrides

GetIntegrationsAsync()

Gets integrations attached to this guild.

Declaration
Returns

Collection of integrations attached to this guild.

Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

GetInvite(String)

Gets an invite from this guild from an invite code.

Declaration
Parameters
Returns

An invite, or null if not in cache.

GetInvitesAsync()

Gets all the invites created for all the channels in this guild.

Declaration
Returns

A collection of invites.

Exceptions

Thrown when Discord is unable to process the request.

GetMemberAsync(UInt64)

Gets a member of this guild by their user ID.

Declaration
Parameters

ID of the member to get.

Returns

The requested member.

Exceptions

Thrown when Discord is unable to process the request.

GetMembershipScreeningFormAsync()

Gets this guild’s membership screening form.

Declaration
Returns

This guild’s membership screening form.

Exceptions

Thrown when Discord is unable to process the request.

GetPruneCountAsync(Int32, IEnumerable )

Estimates the number of users to be pruned.

Declaration
Parameters

Minimum number of inactivity days required for users to be pruned. Defaults to 7.

The roles to be included in the prune.

Returns

Number of users that will be pruned.

Exceptions

Thrown when the client does not have the KickMembers permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

GetRole(UInt64)

Gets a role from this guild by its ID.

Declaration
Parameters

ID of the role to get.

Returns
Exceptions

Thrown when Discord is unable to process the request.

GetStickerAsync(UInt64)

Gets a sticker from this guild.

Declaration
Parameters

The id of the sticker.

Returns

GetStickersAsync()

Gets a list of stickers from this guild.

Declaration
Returns

GetTemplatesAsync()

Gets all of this guild’s templates.

Declaration
Returns

All of the guild’s templates.

Exceptions

Throws when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

GetVanityInviteAsync()

Gets the vanity invite for this guild.

Declaration
Returns

A partial vanity invite.

Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

GetWebhooksAsync()

Gets all the webhooks created for all the channels in this guild.

Declaration
Returns

A collection of webhooks this guild has.

Exceptions

Thrown when the client does not have the ManageWebhooks permission.

Thrown when Discord is unable to process the request.

GetWelcomeScreenAsync()

Gets this guild’s welcome screen.

Declaration
Returns

This guild’s welcome screen object.

Exceptions

Thrown when Discord is unable to process the request.

GetWidgetAsync()

Gets the guild’s widget

Declaration
Returns

GetWidgetImage(WidgetType)

Gets this guild’s widget image.

Declaration
Parameters

The format of the widget.

Returns

The URL of the widget image.

GetWidgetSettingsAsync()

Gets the guild’s widget settings

Declaration
Returns

The guild’s widget settings

LeaveAsync()

Declaration
Returns
Exceptions

Thrown when Discord is unable to process the request.

ListVoiceRegionsAsync()

Gets the voice regions for this guild.

Declaration
Returns

Voice regions available for this guild.

Exceptions

Thrown when Discord is unable to process the request.

ModifyAsync(Action )

Modifies this guild.

Declaration
Parameters

Action to perform on this guild..

Returns

The modified guild object.

Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Modifies a this guild’s custom emoji.

Declaration
Parameters

New name for the emoji.

Roles for which the emoji will be available. This works only if your application is whitelisted as integration.

Reason for audit log.

Returns

The modified emoji.

Exceptions

Thrown when the client does not have the ManageEmojis permission.

Thrown when Discord is unable to process the request.

ModifyIntegrationAsync(DiscordIntegration, Int32, Int32, Boolean)

Modifies an integration in this guild.

Declaration
Parameters

Integration to modify.

Number of days after which the integration expires.

Length of grace period which allows for renewing the integration.

Whether emotes should be synced from this integration.

Returns

The modified integration.

Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

ModifyMembershipScreeningFormAsync(Action )

Modifies this guild’s membership screening form.

Declaration
Parameters
Returns

The modified screening form.

Exceptions

Thrown when the client doesn’t have the ManageGuild permission, or community is not enabled on this guild.

Thrown when Discord is unable to process the request.

ModifyStickerAsync(UInt64, Action )

Declaration
Parameters
TypeNameDescription
System.UInt64stickerId
Action StickerEditModel >action
Returns

ModifyTemplateAsync(String, String, String)

Modifies the template’s metadata.

Declaration
Parameters

The template’s code.

Name of the template.

Description of the template.

Returns

The template modified.

Exceptions

Throws when the template for the code cannot be found

Throws when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

ModifyWelcomeScreenAsync(Action )

Modifies this guild’s welcome screen.

Declaration
Parameters
Returns

The modified welcome screen.

Exceptions

Thrown when the client doesn’t have the ManageGuild permission, or community is not enabled on this guild.

Thrown when Discord is unable to process the request.

Modifies the guild’s widget settings

Declaration
Parameters

If the widget is enabled or not

Reason the widget settings were modified

Returns

The newly modified widget settings

Prunes inactive users from this guild.

Declaration
Parameters

Minimum number of inactivity days required for users to be pruned. Defaults to 7.

Whether to return the prune count after this method completes. This is discouraged for larger guilds.

The roles to be included in the prune.

Reason for audit logs.

Returns

Number of users pruned.

Exceptions

Thrown when the client does not have the ManageChannels permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Requests that Discord send a list of guild members based on the specified arguments. This method will fire the GuildMembersChunked event.

If no arguments aside from presences and nonce are specified, this will request all guild members.

Declaration
Parameters

Filters the returned members based on what the username starts with. Either this or userIds must not be null. The limit must also be greater than 0 if this is specified.

Total number of members to request. This must be greater than 0 if query is specified.

Whether to include the associated with the fetched members.

Whether to limit the request to the specified user ids. Either this or query must not be null.

The unique string to identify the response.

Returns

SearchMembersAsync(String, Nullable )

Searches the current guild for members who’s display name start with the specified name.

Declaration
Parameters

The name to search for.

The maximum amount of members to return. Max 1000. Defaults to 1.

Returns

The members found, if any.

SyncIntegrationAsync(DiscordIntegration)

Forces re-synchronization of an integration for this guild.

Declaration
Parameters

Integration to synchronize.

Returns
Exceptions

Thrown when the client does not have the ManageGuild permission.

Thrown when the guild does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

SyncTemplateAsync(String)

Syncs the template to the current guild’s state.

Declaration
Parameters

The code of the template to sync.

Returns

The template synced.

Exceptions

Throws when the template for the code cannot be found

Throws when the client does not have the ManageGuild permission.

Thrown when Discord is unable to process the request.

ToString()

Returns a string representation of this guild.

Declaration
Returns

String representation of this guild.

Overrides

UnbanMemberAsync(DiscordUser, String)

Unbans a user from this guild.

Declaration
Parameters

Reason for audit logs.

Returns
Exceptions

Thrown when the client does not have the BanMembers permission.

Thrown when the user does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

UnbanMemberAsync(UInt64, String)

Unbans a user by ID.

Declaration
Parameters

ID of the user to unban.

Reason for audit logs.

Returns
Exceptions

Thrown when the client does not have the BanMembers permission.

Thrown when the user does not exist.

Thrown when an invalid parameter was provided.

Thrown when Discord is unable to process the request.

Operators

Equality(DiscordGuild, DiscordGuild)

Gets whether the two DiscordGuild objects are equal.

Declaration
Parameters

First member to compare.

Second member to compare.

Returns

Whether the two members are equal.

Inequality(DiscordGuild, DiscordGuild)

Gets whether the two DiscordGuild objects are not equal.

Источник

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

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

TypeDescription
System.Threading.Tasks.Task System.Nullable System.Int32 >>