Documentation Overhaul (#1161)

* Add XML docs

* Clean up style switcher

* Squash commits on branch docs/faq-n-patches

* Fix broken theme selector

* Add local image embed instruction

* Add a bunch of XML docs

* Add a bunch of XML docs

* Fix broken search
+ DocFX by default ships with an older version of jQuery, switching to a newer version confuses parts of the DocFX Javascript.

* Minor fixes for CONTRIBUTING.md and README.md

* Clean up filterConfig.yml

+ New config exposes Discord.Net namespace since it has several common public exceptions that may be helpful to users

* Add XML docs

* Read token from Environment Variable instead of hardcode

* Add XMLDocs

* Compress some assets & add OAuth2 URL generator

* Fix sample link & add missing pictures

* Add tag examples

* Fix embed docs consistency

* Add details regarding userbot support

* Add XML Docs

* Add XML Docs

* Add XML Docs

* Minor fixes in documentations
+ Fix unescaped '<'
+ Fix typo

* Fix seealso for preconditions and add missing descriptions

* Add missing exceptions

* Document exposed TypeReaders

* Fix letter-casing for files

* Add 'last modified' plugin

Source: https://github.com/Still34/DocFx.Plugin.LastModified
Licensed under MIT License

* XML Docs

* Fix minor consistencies & redundant impl

* Add properties examples to overwrite

* Fix missing Username prop

* Add warning for bulk-delete endpoint

* Replace note block

* Add BaseSocketClient docs

* Add XML docs

* Replace langword null to code block null instead

- Because DocFX sucks at rendering langword

* Replace all langword placements with code block

* Add more IGuild docs

* Add details to SpotifyGame

* Initial proofread of the articles

* Add explanation for RunMode

* Add event docs

- MessageReceived
- ChannelUpdated/Destroyed/Created

* Fix light theme link color

* Fix xml docs error

* Add partial documentation for audit log impl

* Add documentation for some REST-based objects

* Add partial documentation for audit log objects

* Add more XML comments to quotation mark alias map stuff, including an example

* Add reference to CommandServiceConfig from the util docs'

* Add explanation that if " is removed then it wont work

* Fix missing service provider in example

* Add documentation for new INestedChannel

* Add documentation

* Add documentation for new API version & few events

* Revise guide paragraphs/samples

+ Fix various formatting.
+ Provide a more detailed walkthrough for dependency injection.
+ Add C# note at intro.

* Fix typos & formatting

* Improve group module example

* Small amount to see if I'm doing it right

* Remove/cleanup redundant variables

* Fix EnterTypingState impl for doc inheritance

* Fix Test to resolve changes made in 15b58e

* Improve precondition documentation

+ Add precondition usage sample
+ Add precondition group usage sample
+ Move precondition samples to its own sample folder

* Move samples to individual folders

* Clarify token source

* Cleanup styling of README.md for docs

* Replace InvalidPathChars for NS1.3

* InvalidPathChars does not exist in NS1.3; replaced with GetInvalidPathChars instead.

* Add a missing change for 2c7cc738

* Update LastModified to v1.1.0 & add license

* Rewrite installation page for Core 2.1

* Fix anchor link

* Bump post-processor to v1.1.1

* Add fixes to partial file & add license

* Moved theme-switcher code to scripts partial file
+ Add author's MIT license to featherlight javascript

* Remove unused bootstrap plugin

* Bump LastModified plugin

* Changed the path from 'lastmodified' to 'last-modified' for consistency

* Cleanup README & Contribution guide

* Changes to last pr

* Fix GetCategoryAsync docs

* Proofread and cleanup articles

* Change passive voice in "Get Started" to active
* Fix improper preposition in Commands Introduction page
* Fix minor grammar mistakes in "Your First Bot" (future tense -> present tense/subjunctive mood -> indicative mood/proper noun casing/incorrect noun/add missing article)
* Fix minor grammar mistakes in "Installation" (missing article)

* no hablo ingles

* Try try try again

* I'm sure you're having as much fun as I am

* Cleanup TOC & fix titles

* Improve styling

+ Change title font to Noto Sans
+ Add materialized design for commit message box

* Add DescriptionGenerator plugin

* Add nightly section for clarification

* Fix typos in Nightlies & Post-execution

* Bump DescriptionGenerator to v1.1.0

+ This build adds the functionality of generating managed references' summary into the description tag.

* Initial emoji article draft

* Add 'additional information' section for emoji article

* Add cosmetic changes to the master css

* Alter info box color
+ Add transition to article content

* Add clarification in the emoji article

* Emphasize that normal emoji string will not translate to its Unicode representation.
* Clean up or add some of the samples featured in the article.
+ Add emoji/emote declaration section for clarification.
+ Add WebSocket emote sample.
- Remove inconsistent styling ('wacky memes' proves to be too out of place).

* Improve readability for nightlies article

* Move 'Bundled Preconditions' section

* Bump LastModified to fix UTC DateTime parsing

* Add langwordMapping.yml

* Add XML docs

* Add VSC workspace rule

* The root workspace limits the ruler to 120 characters for member documentations and excludes folders such as 'samples' and 'docs'.
* The docs workspace limits the ruler to 70 characters for standard conceptual article to comply with documentation's CONTRIBUTING.md rule, and excludes temprorary folders created by DocFX.

* Update CONTRIBUTING.md

* Add documentation style rule

* Fix styling of several member documentation

* Fix ' />' caused by Agent Smith oddities
* Fix styling to be more specific about the mention of IDs

* Fix exception summary to comply with official Microsoft Docs style

* References
https://docs.microsoft.com/en-us/dotnet/api/system.argumentnullexception?view=netframework-4.7.2
https://docs.microsoft.com/en-us/dotnet/api/system.platformnotsupportedexception?view=netframework-4.7.2
https://docs.microsoft.com/en-us/dotnet/api/system.badimageformatexception?view=netframework-4.7.2

* Add XML documentations

* Shift color return docs

* Fix minor docs

* Added documentation for SocketDMChannel, SocketGuildChannel, and SocketTextChannel

* Add XML docs

* Corrections to SocketGuildChannel

* Corrections to SocketTextChannel

* Corrections to SocketDMChannel

* Swapped out 'id' for 'snowflake identifier

* Swapped out 'id' for 'snowflake identifier'

* SocketDMChannel amendments

* SocketGuildChannel amendments

* SocketTextChannel amendments

* Add XML docs & patch return types
+ Starting from this commit, all return types for tasks will use style similar to most documentations featured on docs.microsoft.com

References:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.-ctor?view=efcore-2.1
https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream.readasync?view=netcore-2.1
https://docs.microsoft.com/en-us/dotnet/api/system.io.textwriter.writelineasync?view=netcore-2.1#System_IO_TextWriter_WriteLineAsync_System_Char___
And many more other asynchronous method documentations featured in the latest BCL.

* Added documentation for many audit log data types, fixed vowel indefinite articles

* Change audit log data types to start with 'Contains' (verb) instead of an article

* Fix some documentation issues and document some more audit log data types

* Fix English posession

* Add XML doc

* Documented two more types

* Documented RoleCreateAuditLogData

* Document remaining audit log data types

* Added RestDMChannel documentation

* Added RestGuildChannel documentation

* Added RestTextChannel documentation

* Added RestVoiceChannel documentation

* Added RestUser documentation

* Added RestRole documentation

* Added RestMessage documentation

* Slightly better wording

* Contains -> Contains a piece of (describe article)

* [EN] Present perf. -> past perf.

* Add XML docs

* Fix arrow alignment

* Clarify supported nullable type

* Fixed a typo in ISnowflakeEntity

* Added RestUser Documentation

* Added RestInvite documentation

* Add XML docs & minor optimizations

* Minor optimization for doc rendering

* Rollback font optimization changes

* Amendments to RestUser

* Added SocketDMChannel documentation

* Added RestDMChannel documentation

* Added RestGuild documentation

* Adjustment to SocketDMChannel

* Added minimal descriptions from the API documentation for Integration types

* Added obsolete mention to the ReadMessages flag.

* Added remarks about 2FA requirement for guild permissions

* Added xmldoc for GuildPermission methods

* Added xml doc for ToAllowList and ToDenyList

* Added specification of how the bits of the color raw value are packed

* Added discord API documentation to IConnection interface

* I can spell :^)

* Fix whitespace in ChannelPermission

* fix spacing of values in guildpermission

* Made changes to get field descriptions from feedback, added returns tag to IConnection

* Added property get standard for IntegrationAccount

* Added property get pattern to xml docs and identical returns tag.

* Change all color class references to struct
...because it isn't a class.

* Add XML docs

* Rewrote the returns tags in IGuildIntegration, removed the ones I was unsure about.

* Rewrote the rest of the returns tags

* Amendments

* Cleanup doc for c1d78189

* Added types to <returns> tags where missing

* Added second sample for adding reactions

* Added some class summaries

* Missed a period

* Amendments

* restored the removed line break

* Removed unnecessary see tag

* Use consistent quotation marks around subscribers, the name for these users are dependant on the source of where they are integrated from (youtube or twitch), so we should not use a name that is specific to one platform

* Add <remarks> tag to the IGuildIntegration xmldocs

* Fix grammar issue

* Update DescriptionGenerator

* Cleanup of https://github.com/Still34/Discord.Net/pull/8

* Cleanup previous PR

* Fix for misleading behaviour in the emoji guide
+ Original lines stated that sending a emoji wrapped in colon will not be parsed, but that was incorrect; replaced with reactions instead of sending messages as the example

* Add strings for dictionary in DotSettings

* Add XML docs

* Fix lots of typos in comments
+ Geez, I didn't know there were so many.

* Add XML docs & rewrite GetMessagesAsync docs

This commit rewrites the remarks section of GetMessagesAsync, as well as adding examples to several methods.

* Update 'Your First Bot'
+ This commit reflects the new changes made to the Discord Application Developer Portal after its major update

* Initial optimization for DocFX render & add missing files

* Add examples in message methods

* Cleanup https://github.com/RogueException/Discord.Net/pull/1128

* Fix first bot note

* Cleanup FAQ structure

* Add XML docs

* Update docfx plugins

* Fix navbar collapsing issue

* Fix broken xref

* Cleanup FAQ section
+ Add introductory paragraphs to each FAQ section.
+ Add 'missing dependency' entry to commands FAQ.
* Split commands FAQ to 'General' and 'DI' sections.

* Cleanup https://github.com/RogueException/Discord.Net/pull/1139

* Fix missing namespace

* Add missing highlighting css for the light theme

* Add additional clarification for installing packages

* Add indentation to example for clarity

* Cleanup several articles to be more human-friendly and easier to read

* Remove RPC-related notes

* Cleanup slow-mode-related documentation strings

* Add an additional note about cross-guild emote usage

* Add CreateTextChannel sample

* Add XMLDocs
This commit is contained in:
Still Hsu
2018-10-01 05:44:33 +08:00
committed by Christopher F
parent 6b21b11f7d
commit ff0fea98a6
498 changed files with 16064 additions and 2633 deletions

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a ban.
/// </summary>
public class BanAuditLogData : IAuditLogData
{
private BanAuditLogData(IUser user)
@@ -18,6 +21,12 @@ namespace Discord.Rest
return new BanAuditLogData(RestUser.Create(discord, userInfo));
}
/// <summary>
/// Gets the user that was banned.
/// </summary>
/// <returns>
/// A user object representing the banned user.
/// </returns>
public IUser Target { get; }
}
}

View File

@@ -1,4 +1,3 @@
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
@@ -7,6 +6,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a channel creation.
/// </summary>
public class ChannelCreateAuditLogData : IAuditLogData
{
private ChannelCreateAuditLogData(ulong id, string name, ChannelType type, IReadOnlyCollection<Overwrite> overwrites)
@@ -42,9 +44,34 @@ namespace Discord.Rest
return new ChannelCreateAuditLogData(entry.TargetId.Value, name, type, overwrites.ToReadOnlyCollection());
}
/// <summary>
/// Gets the snowflake ID of the created channel.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier for the created channel.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the name of the created channel.
/// </summary>
/// <returns>
/// A string containing the name of the created channel.
/// </returns>
public string ChannelName { get; }
/// <summary>
/// Gets the type of the created channel.
/// </summary>
/// <returns>
/// The type of channel that was created.
/// </returns>
public ChannelType ChannelType { get; }
/// <summary>
/// Gets a collection of permission overwrites that was assigned to the created channel.
/// </summary>
/// <returns>
/// A collection of permission <see cref="Overwrite"/>, containing the permission overwrites that were
/// assigned to the created channel.
/// </returns>
public IReadOnlyCollection<Overwrite> Overwrites { get; }
}
}

View File

@@ -1,14 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a channel deletion.
/// </summary>
public class ChannelDeleteAuditLogData : IAuditLogData
{
private ChannelDeleteAuditLogData(ulong id, string name, ChannelType type, IReadOnlyCollection<Overwrite> overwrites)
@@ -37,9 +37,33 @@ namespace Discord.Rest
return new ChannelDeleteAuditLogData(id, name, type, overwrites.ToReadOnlyCollection());
}
/// <summary>
/// Gets the snowflake ID of the deleted channel.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier for the deleted channel.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the name of the deleted channel.
/// </summary>
/// <returns>
/// A string containing the name of the deleted channel.
/// </returns>
public string ChannelName { get; }
/// <summary>
/// Gets the type of the deleted channel.
/// </summary>
/// <returns>
/// The type of channel that was deleted.
/// </returns>
public ChannelType ChannelType { get; }
/// <summary>
/// Gets a collection of permission overwrites that was assigned to the deleted channel.
/// </summary>
/// <returns>
/// A collection of permission <see cref="Overwrite"/>.
/// </returns>
public IReadOnlyCollection<Overwrite> Overwrites { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// Represents information for a channel.
/// </summary>
public struct ChannelInfo
{
internal ChannelInfo(string name, string topic, int? bitrate, int? limit)
@@ -10,9 +13,35 @@ namespace Discord.Rest
UserLimit = limit;
}
/// <summary>
/// Gets the name of this channel.
/// </summary>
/// <returns>
/// A string containing the name of this channel.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the topic of this channel.
/// </summary>
/// <returns>
/// A string containing the topic of this channel, if any.
/// </returns>
public string Topic { get; }
/// <summary>
/// Gets the bit-rate of this channel if applicable.
/// </summary>
/// <returns>
/// An <see cref="System.Int32"/> representing the bit-rate set for the voice channel; <c>null</c> if not
/// applicable.
/// </returns>
public int? Bitrate { get; }
/// <summary>
/// Gets the number of users allowed to be in this channel if applicable.
/// </summary>
/// <returns>
/// An <see cref="System.Int32" /> representing the number of users allowed to be in this voice channel;
/// <c>null</c> if not applicable.
/// </returns>
public int? UserLimit { get; }
}
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a channel update.
/// </summary>
public class ChannelUpdateAuditLogData : IAuditLogData
{
private ChannelUpdateAuditLogData(ulong id, ChannelInfo before, ChannelInfo after)
@@ -38,8 +41,26 @@ namespace Discord.Rest
return new ChannelUpdateAuditLogData(entry.TargetId.Value, before, after);
}
/// <summary>
/// Gets the snowflake ID of the updated channel.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier for the updated channel.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the channel information before the changes.
/// </summary>
/// <returns>
/// An information object containing the original channel information before the changes were made.
/// </returns>
public ChannelInfo Before { get; }
/// <summary>
/// Gets the channel information after the changes.
/// </summary>
/// <returns>
/// An information object containing the channel information after the changes were made.
/// </returns>
public ChannelInfo After { get; }
}
}

View File

@@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an emoji creation.
/// </summary>
public class EmoteCreateAuditLogData : IAuditLogData
{
private EmoteCreateAuditLogData(ulong id, string name)
@@ -25,7 +24,19 @@ namespace Discord.Rest
return new EmoteCreateAuditLogData(entry.TargetId.Value, emoteName);
}
/// <summary>
/// Gets the snowflake ID of the created emoji.
/// </summary>
/// <returns>
/// A <see cref="System.UInt64"/> representing the snowflake identifier for the created emoji.
/// </returns>
public ulong EmoteId { get; }
/// <summary>
/// Gets the name of the created emoji.
/// </summary>
/// <returns>
/// A string containing the name of the created emoji.
/// </returns>
public string Name { get; }
}
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an emoji deletion.
/// </summary>
public class EmoteDeleteAuditLogData : IAuditLogData
{
private EmoteDeleteAuditLogData(ulong id, string name)
@@ -22,7 +25,19 @@ namespace Discord.Rest
return new EmoteDeleteAuditLogData(entry.TargetId.Value, emoteName);
}
/// <summary>
/// Gets the snowflake ID of the deleted emoji.
/// </summary>
/// <returns>
/// A <see cref="System.UInt64"/> representing the snowflake identifier for the deleted emoji.
/// </returns>
public ulong EmoteId { get; }
/// <summary>
/// Gets the name of the deleted emoji.
/// </summary>
/// <returns>
/// A string containing the name of the deleted emoji.
/// </returns>
public string Name { get; }
}
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an emoji update.
/// </summary>
public class EmoteUpdateAuditLogData : IAuditLogData
{
private EmoteUpdateAuditLogData(ulong id, string oldName, string newName)
@@ -24,8 +27,26 @@ namespace Discord.Rest
return new EmoteUpdateAuditLogData(entry.TargetId.Value, oldName, newName);
}
/// <summary>
/// Gets the snowflake ID of the updated emoji.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the updated emoji.
/// </returns>
public ulong EmoteId { get; }
/// <summary>
/// Gets the new name of the updated emoji.
/// </summary>
/// <returns>
/// A string containing the new name of the updated emoji.
/// </returns>
public string NewName { get; }
/// <summary>
/// Gets the old name of the updated emoji.
/// </summary>
/// <returns>
/// A string containing the old name of the updated emoji.
/// </returns>
public string OldName { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// Represents information for a guild.
/// </summary>
public struct GuildInfo
{
internal GuildInfo(int? afkTimeout, DefaultMessageNotifications? defaultNotifs,
@@ -18,14 +21,66 @@ namespace Discord.Rest
ContentFilterLevel = filter;
}
/// <summary>
/// Gets the amount of time (in seconds) a user must be inactive in a voice channel for until they are
/// automatically moved to the AFK voice channel.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the amount of time in seconds for a user to be marked as inactive
/// and moved into the AFK voice channel.
/// </returns>
public int? AfkTimeout { get; }
/// <summary>
/// Gets the default message notifications for users who haven't explicitly set their notification settings.
/// </summary>
public DefaultMessageNotifications? DefaultMessageNotifications { get; }
/// <summary>
/// Gets the ID of the AFK voice channel for this guild.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the AFK voice channel; <c>null</c> if
/// none is set.
/// </returns>
public ulong? AfkChannelId { get; }
/// <summary>
/// Gets the name of this guild.
/// </summary>
/// <returns>
/// A string containing the name of this guild.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the ID of the region hosting this guild's voice channels.
/// </summary>
public string RegionId { get; }
/// <summary>
/// Gets the ID of this guild's icon.
/// </summary>
/// <returns>
/// A string containing the identifier for the splash image; <c>null</c> if none is set.
/// </returns>
public string IconHash { get; }
/// <summary>
/// Gets the level of requirements a user must fulfill before being allowed to post messages in this guild.
/// </summary>
/// <returns>
/// The level of requirements.
/// </returns>
public VerificationLevel? VerificationLevel { get; }
/// <summary>
/// Gets the owner of this guild.
/// </summary>
/// <returns>
/// A user object representing the owner of this guild.
/// </returns>
public IUser Owner { get; }
/// <summary>
/// Gets the level of Multi-Factor Authentication requirements a user must fulfill before being allowed to
/// perform administrative actions in this guild.
/// </summary>
/// <returns>
/// The level of MFA requirement.
/// </returns>
public MfaLevel? MfaLevel { get; }
public int? ContentFilterLevel { get; }
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a guild update.
/// </summary>
public class GuildUpdateAuditLogData : IAuditLogData
{
private GuildUpdateAuditLogData(GuildInfo before, GuildInfo after)
@@ -73,7 +76,19 @@ namespace Discord.Rest
return new GuildUpdateAuditLogData(before, after);
}
/// <summary>
/// Gets the guild information before the changes.
/// </summary>
/// <returns>
/// An information object containing the original guild information before the changes were made.
/// </returns>
public GuildInfo Before { get; }
/// <summary>
/// Gets the guild information after the changes.
/// </summary>
/// <returns>
/// An information object containing the guild information after the changes were made.
/// </returns>
public GuildInfo After { get; }
}
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an invite creation.
/// </summary>
public class InviteCreateAuditLogData : IAuditLogData
{
private InviteCreateAuditLogData(int maxAge, string code, bool temporary, IUser inviter, ulong channelId, int uses, int maxUses)
@@ -44,12 +47,56 @@ namespace Discord.Rest
return new InviteCreateAuditLogData(maxAge, code, temporary, inviter, channelId, uses, maxUses);
}
/// <summary>
/// Gets the time (in seconds) until the invite expires.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the time in seconds until this invite expires.
/// </returns>
public int MaxAge { get; }
/// <summary>
/// Gets the unique identifier for this invite.
/// </summary>
/// <returns>
/// A string containing the invite code (e.g. <c>FTqNnyS</c>).
/// </returns>
public string Code { get; }
/// <summary>
/// Gets a value that determines whether the invite is a temporary one.
/// </summary>
/// <returns>
/// <c>true</c> if users accepting this invite will be removed from the guild when they log off; otherwise
/// <c>false</c>.
/// </returns>
public bool Temporary { get; }
/// <summary>
/// Gets the user that created this invite.
/// </summary>
/// <returns>
/// A user that created this invite.
/// </returns>
public IUser Creator { get; }
/// <summary>
/// Gets the ID of the channel this invite is linked to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the channel snowflake identifier that the invite points to.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the number of times this invite has been used.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of times this invite was used.
/// </returns>
public int Uses { get; }
/// <summary>
/// Gets the max number of uses this invite may have.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of uses this invite may be accepted until it is removed
/// from the guild; <c>null</c> if none is set.
/// </returns>
public int MaxUses { get; }
}
}

View File

@@ -1,10 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an invite removal.
/// </summary>
public class InviteDeleteAuditLogData : IAuditLogData
{
private InviteDeleteAuditLogData(int maxAge, string code, bool temporary, IUser inviter, ulong channelId, int uses, int maxUses)
@@ -44,12 +47,56 @@ namespace Discord.Rest
return new InviteDeleteAuditLogData(maxAge, code, temporary, inviter, channelId, uses, maxUses);
}
/// <summary>
/// Gets the time (in seconds) until the invite expires.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the time in seconds until this invite expires.
/// </returns>
public int MaxAge { get; }
/// <summary>
/// Gets the unique identifier for this invite.
/// </summary>
/// <returns>
/// A string containing the invite code (e.g. <c>FTqNnyS</c>).
/// </returns>
public string Code { get; }
/// <summary>
/// Gets a value that indicates whether the invite is a temporary one.
/// </summary>
/// <returns>
/// <c>true</c> if users accepting this invite will be removed from the guild when they log off; otherwise
/// <c>false</c>.
/// </returns>
public bool Temporary { get; }
/// <summary>
/// Gets the user that created this invite.
/// </summary>
/// <returns>
/// A user that created this invite.
/// </returns>
public IUser Creator { get; }
/// <summary>
/// Gets the ID of the channel this invite is linked to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the channel snowflake identifier that the invite points to.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the number of times this invite has been used.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of times this invite has been used.
/// </returns>
public int Uses { get; }
/// <summary>
/// Gets the max number of uses this invite may have.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of uses this invite may be accepted until it is removed
/// from the guild; <c>null</c> if none is set.
/// </returns>
public int MaxUses { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// Represents information for an invite.
/// </summary>
public struct InviteInfo
{
internal InviteInfo(int? maxAge, string code, bool? temporary, ulong? channelId, int? maxUses)
@@ -11,10 +14,44 @@ namespace Discord.Rest
MaxUses = maxUses;
}
/// <summary>
/// Gets the time (in seconds) until the invite expires.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the time in seconds until this invite expires; <c>null</c> if this
/// invite never expires or not specified.
/// </returns>
public int? MaxAge { get; }
/// <summary>
/// Gets the unique identifier for this invite.
/// </summary>
/// <returns>
/// A string containing the invite code (e.g. <c>FTqNnyS</c>).
/// </returns>
public string Code { get; }
/// <summary>
/// Gets a value that indicates whether the invite is a temporary one.
/// </summary>
/// <returns>
/// <c>true</c> if users accepting this invite will be removed from the guild when they log off,
/// <c>false</c> if not; <c>null</c> if not specified.
/// </returns>
public bool? Temporary { get; }
/// <summary>
/// Gets the ID of the channel this invite is linked to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the channel snowflake identifier that the invite points to;
/// <c>null</c> if not specified.
/// </returns>
public ulong? ChannelId { get; }
/// <summary>
/// Gets the max number of uses this invite may have.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of uses this invite may be accepted until it is removed
/// from the guild; <c>null</c> if none is specified.
/// </returns>
public int? MaxUses { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data relating to an invite update.
/// </summary>
public class InviteUpdateAuditLogData : IAuditLogData
{
private InviteUpdateAuditLogData(InviteInfo before, InviteInfo after)
@@ -40,7 +43,19 @@ namespace Discord.Rest
return new InviteUpdateAuditLogData(before, after);
}
/// <summary>
/// Gets the invite information before the changes.
/// </summary>
/// <returns>
/// An information object containing the original invite information before the changes were made.
/// </returns>
public InviteInfo Before { get; }
/// <summary>
/// Gets the invite information after the changes.
/// </summary>
/// <returns>
/// An information object containing the invite information after the changes were made.
/// </returns>
public InviteInfo After { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a kick.
/// </summary>
public class KickAuditLogData : IAuditLogData
{
private KickAuditLogData(RestUser user)
@@ -18,6 +21,12 @@ namespace Discord.Rest
return new KickAuditLogData(RestUser.Create(discord, userInfo));
}
/// <summary>
/// Gets the user that was kicked.
/// </summary>
/// <returns>
/// A user object representing the kicked user.
/// </returns>
public IUser Target { get; }
}
}

View File

@@ -1,4 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,6 +6,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a change in a guild member's roles.
/// </summary>
public class MemberRoleAuditLogData : IAuditLogData
{
private MemberRoleAuditLogData(IReadOnlyCollection<MemberRoleEditInfo> roles, IUser target)
@@ -30,7 +32,20 @@ namespace Discord.Rest
return new MemberRoleAuditLogData(roleInfos.ToReadOnlyCollection(), user);
}
/// <summary>
/// Gets a collection of role changes that were performed on the member.
/// </summary>
/// <returns>
/// A read-only collection of <see cref="MemberRoleEditInfo"/>, containing the roles that were changed on
/// the member.
/// </returns>
public IReadOnlyCollection<MemberRoleEditInfo> Roles { get; }
/// <summary>
/// Gets the user that the roles changes were performed on.
/// </summary>
/// <returns>
/// A user object representing the user that the role changes were performed on.
/// </returns>
public IUser Target { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// An information object representing a change in one of a guild member's roles.
/// </summary>
public struct MemberRoleEditInfo
{
internal MemberRoleEditInfo(string name, ulong roleId, bool added)
@@ -9,8 +12,26 @@ namespace Discord.Rest
Added = added;
}
/// <summary>
/// Gets the name of the role that was changed.
/// </summary>
/// <returns>
/// A string containing the name of the role that was changed.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the ID of the role that was changed.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the role that was changed.
/// </returns>
public ulong RoleId { get; }
/// <summary>
/// Gets a value that indicates whether the role was added to the user.
/// </summary>
/// <returns>
/// <c>true</c> if the role was added to the user; otherwise <c>false</c>.
/// </returns>
public bool Added { get; }
}
}

View File

@@ -1,11 +1,13 @@
using System.Linq;
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
using ChangeModel = Discord.API.AuditLogChange;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a change in a guild member.
/// </summary>
public class MemberUpdateAuditLogData : IAuditLogData
{
private MemberUpdateAuditLogData(IUser target, MemberInfo before, MemberInfo after)
@@ -42,6 +44,12 @@ namespace Discord.Rest
return new MemberUpdateAuditLogData(user, before, after);
}
/// <summary>
/// Gets the user that the changes were performed on.
/// </summary>
/// <returns>
/// A user object representing the user who the changes were performed on.
/// </returns>
public IUser Target { get; }
public MemberInfo Before { get; }
public MemberInfo After { get; }

View File

@@ -3,6 +3,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to message deletion(s).
/// </summary>
public class MessageDeleteAuditLogData : IAuditLogData
{
private MessageDeleteAuditLogData(ulong channelId, int count)
@@ -16,7 +19,20 @@ namespace Discord.Rest
return new MessageDeleteAuditLogData(entry.Options.MessageDeleteChannelId.Value, entry.Options.MessageDeleteCount.Value);
}
/// <summary>
/// Gets the number of messages that were deleted.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of messages that were deleted from the channel.
/// </returns>
public int MessageCount { get; }
/// <summary>
/// Gets the ID of the channel that the messages were deleted from.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier for the channel that the messages were
/// deleted from.
/// </returns>
public ulong ChannelId { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data for a permissions overwrite creation.
/// </summary>
public class OverwriteCreateAuditLogData : IAuditLogData
{
private OverwriteCreateAuditLogData(Overwrite overwrite)
@@ -30,6 +33,12 @@ namespace Discord.Rest
return new OverwriteCreateAuditLogData(new Overwrite(id, type, permissions));
}
/// <summary>
/// Gets the permission overwrite object that was created.
/// </summary>
/// <returns>
/// An <see cref="Overwrite"/> object representing the overwrite that was created.
/// </returns>
public Overwrite Overwrite { get; }
}
}

View File

@@ -1,16 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
using ChangeModel = Discord.API.AuditLogChange;
using OptionModel = Discord.API.AuditLogOptions;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to the deletion of a permission overwrite.
/// </summary>
public class OverwriteDeleteAuditLogData : IAuditLogData
{
private OverwriteDeleteAuditLogData(Overwrite deletedOverwrite)
@@ -35,6 +32,12 @@ namespace Discord.Rest
return new OverwriteDeleteAuditLogData(new Overwrite(id, type, new OverwritePermissions(allow, deny)));
}
/// <summary>
/// Gets the permission overwrite object that was deleted.
/// </summary>
/// <returns>
/// An <see cref="Overwrite"/> object representing the overwrite that was deleted.
/// </returns>
public Overwrite Overwrite { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to the update of a permission overwrite.
/// </summary>
public class OverwriteUpdateAuditLogData : IAuditLogData
{
private OverwriteUpdateAuditLogData(OverwritePermissions before, OverwritePermissions after, ulong targetId, PermissionTarget targetType)
@@ -35,10 +38,35 @@ namespace Discord.Rest
return new OverwriteUpdateAuditLogData(beforePermissions, afterPermissions, entry.Options.OverwriteTargetId.Value, type);
}
/// <summary>
/// Gets the overwrite permissions before the changes.
/// </summary>
/// <returns>
/// An overwrite permissions object representing the overwrite permissions that the overwrite had before
/// the changes were made.
/// </returns>
public OverwritePermissions OldPermissions { get; }
/// <summary>
/// Gets the overwrite permissions after the changes.
/// </summary>
/// <returns>
/// An overwrite permissions object representing the overwrite permissions that the overwrite had after the
/// changes.
/// </returns>
public OverwritePermissions NewPermissions { get; }
/// <summary>
/// Gets the ID of the overwrite that was updated.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the overwrite that was updated.
/// </returns>
public ulong OverwriteTargetId { get; }
/// <summary>
/// Gets the target of the updated permission overwrite.
/// </summary>
/// <returns>
/// The target of the updated permission overwrite.
/// </returns>
public PermissionTarget OverwriteType { get; }
}
}

View File

@@ -3,6 +3,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a guild prune.
/// </summary>
public class PruneAuditLogData : IAuditLogData
{
private PruneAuditLogData(int pruneDays, int membersRemoved)
@@ -16,7 +19,22 @@ namespace Discord.Rest
return new PruneAuditLogData(entry.Options.PruneDeleteMemberDays.Value, entry.Options.PruneMembersRemoved.Value);
}
/// <summary>
/// Gets the threshold for a guild member to not be kicked.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the amount of days that a member must have been seen in the server,
/// to avoid being kicked. (i.e. If a user has not been seen for more than <paramref cref="PruneDays"/>, they will be
/// kicked from the server)
/// </returns>
public int PruneDays { get; }
/// <summary>
/// Gets the number of members that were kicked during the purge.
/// </summary>
/// <returns>
/// An <see cref="int"/> representing the number of members that were removed from this guild for having
/// not been seen within <paramref cref="PruneDays"/>.
/// </returns>
public int MembersRemoved { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a role creation.
/// </summary>
public class RoleCreateAuditLogData : IAuditLogData
{
private RoleCreateAuditLogData(ulong id, RoleEditInfo props)
@@ -41,7 +44,19 @@ namespace Discord.Rest
new RoleEditInfo(color, mentionable, hoist, name, permissions));
}
/// <summary>
/// Gets the ID of the role that was created.
/// </summary>
/// <return>
/// A <see cref="ulong"/> representing the snowflake identifier to the role that was created.
/// </return>
public ulong RoleId { get; }
/// <summary>
/// Gets the role information that was created.
/// </summary>
/// <return>
/// An information object representing the properties of the role that was created.
/// </return>
public RoleEditInfo Properties { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data relating to a role deletion.
/// </summary>
public class RoleDeleteAuditLogData : IAuditLogData
{
private RoleDeleteAuditLogData(ulong id, RoleEditInfo props)
@@ -41,7 +44,19 @@ namespace Discord.Rest
new RoleEditInfo(color, mentionable, hoist, name, permissions));
}
/// <summary>
/// Gets the ID of the role that was deleted.
/// </summary>
/// <return>
/// A <see cref="ulong"/> representing the snowflake identifier to the role that was deleted.
/// </return>
public ulong RoleId { get; }
/// <summary>
/// Gets the role information that was deleted.
/// </summary>
/// <return>
/// An information object representing the properties of the role that was deleted.
/// </return>
public RoleEditInfo Properties { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// Represents information for a role edit.
/// </summary>
public struct RoleEditInfo
{
internal RoleEditInfo(Color? color, bool? mentionable, bool? hoist, string name,
@@ -12,10 +15,45 @@ namespace Discord.Rest
Permissions = permissions;
}
/// <summary>
/// Gets the color of this role.
/// </summary>
/// <returns>
/// A color object representing the color assigned to this role; <c>null</c> if this role does not have a
/// color.
/// </returns>
public Color? Color { get; }
/// <summary>
/// Gets a value that indicates whether this role is mentionable.
/// </summary>
/// <returns>
/// <c>true</c> if other members can mention this role in a text channel; otherwise <c>false</c>;
/// <c>null</c> if this is not mentioned in this entry.
/// </returns>
public bool? Mentionable { get; }
/// <summary>
/// Gets a value that indicates whether this role is hoisted (i.e. its members will appear in a separate
/// section on the user list).
/// </summary>
/// <returns>
/// <c>true</c> if this role's members will appear in a separate section in the user list; otherwise
/// <c>false</c>; <c>null</c> if this is not mentioned in this entry.
/// </returns>
public bool? Hoist { get; }
/// <summary>
/// Gets the name of this role.
/// </summary>
/// <returns>
/// A string containing the name of this role.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the permissions assigned to this role.
/// </summary>
/// <returns>
/// A guild permissions object representing the permissions that have been assigned to this role; <c>null</c>
/// if no permissions have been assigned.
/// </returns>
public GuildPermissions? Permissions { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a role update.
/// </summary>
public class RoleUpdateAuditLogData : IAuditLogData
{
private RoleUpdateAuditLogData(ulong id, RoleEditInfo oldProps, RoleEditInfo newProps)
@@ -55,8 +58,26 @@ namespace Discord.Rest
return new RoleUpdateAuditLogData(entry.TargetId.Value, oldProps, newProps);
}
/// <summary>
/// Gets the ID of the role that was changed.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the role that was changed.
/// </returns>
public ulong RoleId { get; }
/// <summary>
/// Gets the role information before the changes.
/// </summary>
/// <returns>
/// A role information object containing the role information before the changes were made.
/// </returns>
public RoleEditInfo Before { get; }
/// <summary>
/// Gets the role information after the changes.
/// </summary>
/// <returns>
/// A role information object containing the role information after the changes were made.
/// </returns>
public RoleEditInfo After { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to an unban.
/// </summary>
public class UnbanAuditLogData : IAuditLogData
{
private UnbanAuditLogData(IUser user)
@@ -18,6 +21,12 @@ namespace Discord.Rest
return new UnbanAuditLogData(RestUser.Create(discord, userInfo));
}
/// <summary>
/// Gets the user that was unbanned.
/// </summary>
/// <returns>
/// A user object representing the user that was unbanned.
/// </returns>
public IUser Target { get; }
}
}

View File

@@ -5,6 +5,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a webhook creation.
/// </summary>
public class WebhookCreateAuditLogData : IAuditLogData
{
private WebhookCreateAuditLogData(IWebhook webhook, WebhookType type, string name, ulong channelId)
@@ -33,12 +36,40 @@ namespace Discord.Rest
return new WebhookCreateAuditLogData(webhook, type, name, channelId);
}
//Corresponds to the *current* data
// Doc Note: Corresponds to the *current* data
/// <summary>
/// Gets the webhook that was created.
/// </summary>
/// <returns>
/// A webhook object representing the webhook that was created.
/// </returns>
public IWebhook Webhook { get; }
//Corresponds to the *audit log* data
// Doc Note: Corresponds to the *audit log* data
/// <summary>
/// Gets the type of webhook that was created.
/// </summary>
/// <returns>
/// The type of webhook that was created.
/// </returns>
public WebhookType Type { get; }
/// <summary>
/// Gets the name of the webhook.
/// </summary>
/// <returns>
/// A string containing the name of the webhook.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the ID of the channel that the webhook could send to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the channel that the webhook could send
/// to.
/// </returns>
public ulong ChannelId { get; }
}
}

View File

@@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a webhook deletion.
/// </summary>
public class WebhookDeleteAuditLogData : IAuditLogData
{
private WebhookDeleteAuditLogData(ulong id, ulong channel, WebhookType type, string name, string avatar)
@@ -37,10 +36,41 @@ namespace Discord.Rest
return new WebhookDeleteAuditLogData(entry.TargetId.Value, channelId, type, name, avatarHash);
}
/// <summary>
/// Gets the ID of the webhook that was deleted.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the webhook that was deleted.
/// </returns>
public ulong WebhookId { get; }
/// <summary>
/// Gets the ID of the channel that the webhook could send to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the channel that the webhook could send
/// to.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the type of the webhook that was deleted.
/// </summary>
/// <returns>
/// The type of webhook that was deleted.
/// </returns>
public WebhookType Type { get; }
/// <summary>
/// Gets the name of the webhook that was deleted.
/// </summary>
/// <returns>
/// A string containing the name of the webhook that was deleted.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the hash value of the webhook's avatar.
/// </summary>
/// <returns>
/// A string containing the hash of the webhook's avatar.
/// </returns>
public string Avatar { get; }
}
}

View File

@@ -1,5 +1,8 @@
namespace Discord.Rest
{
/// <summary>
/// Represents information for a webhook.
/// </summary>
public struct WebhookInfo
{
internal WebhookInfo(string name, ulong? channelId, string avatar)
@@ -9,8 +12,27 @@ namespace Discord.Rest
Avatar = avatar;
}
/// <summary>
/// Gets the name of this webhook.
/// </summary>
/// <returns>
/// A string containing the name of this webhook.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the ID of the channel that this webhook sends to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the channel that this webhook can send
/// to.
/// </returns>
public ulong? ChannelId { get; }
/// <summary>
/// Gets the hash value of this webhook's avatar.
/// </summary>
/// <returns>
/// A string containing the hash of this webhook's avatar.
/// </returns>
public string Avatar { get; }
}
}

View File

@@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a webhook update.
/// </summary>
public class WebhookUpdateAuditLogData : IAuditLogData
{
private WebhookUpdateAuditLogData(IWebhook webhook, WebhookInfo before, WebhookInfo after)
@@ -42,11 +41,28 @@ namespace Discord.Rest
return new WebhookUpdateAuditLogData(webhook, before, after);
}
//Again, the *current* data
/// <summary>
/// Gets the webhook that was updated.
/// </summary>
/// <returns>
/// A webhook object representing the webhook that was updated.
/// </returns>
public IWebhook Webhook { get; }
//And the *audit log* data
/// <summary>
/// Gets the webhook information before the changes.
/// </summary>
/// <returns>
/// A webhook information object representing the webhook before the changes were made.
/// </returns>
public WebhookInfo Before { get; }
/// <summary>
/// Gets the webhook information after the changes.
/// </summary>
/// <returns>
/// A webhook information object representing the webhook after the changes were made.
/// </returns>
public WebhookInfo After { get; }
}
}

View File

@@ -6,6 +6,9 @@ using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based audit log entry.
/// </summary>
public class RestAuditLogEntry : RestEntity<ulong>, IAuditLogEntry
{
private RestAuditLogEntry(BaseDiscordClient discord, Model fullLog, EntryModel model, IUser user)

View File

@@ -7,7 +7,6 @@ using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
using UserModel = Discord.API.User;
using WebhookModel = Discord.API.Webhook;
namespace Discord.Rest
{
@@ -78,14 +77,8 @@ namespace Discord.Rest
int? maxAge, int? maxUses, bool isTemporary, bool isUnique, RequestOptions options)
{
var args = new CreateChannelInviteParams { IsTemporary = isTemporary, IsUnique = isUnique };
if (maxAge.HasValue)
args.MaxAge = maxAge.Value;
else
args.MaxAge = 0;
if (maxUses.HasValue)
args.MaxUses = maxUses.Value;
else
args.MaxUses = 0;
args.MaxAge = maxAge.GetValueOrDefault(0);
args.MaxUses = maxUses.GetValueOrDefault(0);
var model = await client.ApiClient.CreateChannelInviteAsync(channel.Id, args, options).ConfigureAwait(false);
return RestInviteMetadata.Create(client, null, channel, model);
}
@@ -161,6 +154,7 @@ namespace Discord.Rest
return builder.ToImmutable();
}
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public static async Task<RestUserMessage> SendMessageAsync(IMessageChannel channel, BaseDiscordClient client,
string text, bool isTTS, Embed embed, RequestOptions options)
{
@@ -169,6 +163,30 @@ namespace Discord.Rest
return RestUserMessage.Create(client, channel, client.CurrentUser, model);
}
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client,
string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
{
@@ -177,6 +195,7 @@ namespace Discord.Rest
return await SendFileAsync(channel, client, file, filename, text, isTTS, embed, options).ConfigureAwait(false);
}
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client,
Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
{
@@ -241,6 +260,7 @@ namespace Discord.Rest
}
//Users
/// <exception cref="InvalidOperationException">Resolving permissions requires the parent guild to be downloaded.</exception>
public static async Task<RestGuildUser> GetUserAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client,
ulong id, RequestOptions options)
{
@@ -253,6 +273,7 @@ namespace Discord.Rest
return user;
}
/// <exception cref="InvalidOperationException">Resolving permissions requires the parent guild to be downloaded.</exception>
public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client,
ulong? fromUserId, int? limit, RequestOptions options)
{
@@ -292,7 +313,7 @@ namespace Discord.Rest
}
public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client,
RequestOptions options)
=> new TypingNotifier(client, channel, options);
=> new TypingNotifier(channel, options);
//Webhooks
public static async Task<RestWebhook> CreateWebhookAsync(ITextChannel channel, BaseDiscordClient client, string name, Stream avatar, RequestOptions options)

View File

@@ -4,25 +4,193 @@ using System.Threading.Tasks;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based channel that can send and receive messages.
/// </summary>
public interface IRestMessageChannel : IMessageChannel
{
/// <summary> Sends a message to this message channel. </summary>
/// <summary>
/// Sends a message to this message channel.
/// </summary>
/// <param name="text">The message to be sent.</param>
/// <param name="isTTS">Determines whether the message should be read aloud by Discord or not.</param>
/// <param name="embed">The <see cref="Discord.EmbedType.Rich"/> <see cref="Embed"/> to be sent.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents an asynchronous send operation for delivering the message. The task result
/// contains the sent message.
/// </returns>
new Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null);
/// <summary> Sends a file to this text channel, with an optional caption. </summary>
/// <summary>
/// Sends a file to this message channel with an optional caption.
/// </summary>
/// <remarks>
/// This method sends a file as if you are uploading an attachment directly from your Discord client.
/// <note>
/// If you wish to upload an image and have it embedded in a <see cref="Discord.EmbedType.Rich"/>embed,
/// you may upload the file and refer to the file with "attachment://filename.ext" in the
/// <see cref="Discord.EmbedBuilder.ImageUrl"/>.
/// </note>
/// </remarks>
/// <param name="filePath">The file path of the file.</param>
/// <param name="text">The message to be sent.</param>
/// <param name="isTTS">Whether the message should be read aloud by Discord or not.</param>
/// <param name="embed">The <see cref="Discord.EmbedType.Rich" /> <see cref="Embed" /> to be sent.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents an asynchronous send operation for delivering the message. The task result
/// contains the sent message.
/// </returns>
new Task<RestUserMessage> SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null);
/// <summary> Sends a file to this text channel, with an optional caption. </summary>
/// <summary>
/// Sends a file to this message channel with an optional caption.
/// </summary>
/// <remarks>
/// This method sends a file as if you are uploading an attachment directly from your Discord client.
/// <note>
/// If you wish to upload an image and have it embedded in a <see cref="Discord.EmbedType.Rich"/>embed,
/// you may upload the file and refer to the file with "attachment://filename.ext" in the
/// <see cref="Discord.EmbedBuilder.ImageUrl"/>.
/// </note>
/// </remarks>
/// <param name="stream">The <see cref="Stream" /> of the file to be sent.</param>
/// <param name="filename">The name of the attachment.</param>
/// <param name="text">The message to be sent.</param>
/// <param name="isTTS">Whether the message should be read aloud by Discord or not.</param>
/// <param name="embed">The <see cref="Discord.EmbedType.Rich"/> <see cref="Embed"/> to be sent.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents an asynchronous send operation for delivering the message. The task result
/// contains the sent message.
/// </returns>
new Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null);
/// <summary> Gets a message from this message channel with the given id, or null if not found. </summary>
/// <summary>
/// Gets a message from this message channel.
/// </summary>
/// <param name="id">The snowflake identifier of the message.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents an asynchronous get operation for retrieving the message. The task result contains
/// the retrieved message; <c>null</c> if no message is found with the specified identifier.
/// </returns>
Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null);
/// <summary> Gets the last N messages from this message channel. </summary>
/// <summary>
/// Gets the last N messages from this message channel.
/// </summary>
/// <remarks>
/// <note type="important">
/// The returned collection is an asynchronous enumerable object; one must call
/// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a
/// collection.
/// </note>
/// <note type="warning">
/// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual
/// rate limit, causing your bot to freeze!
/// </note>
/// This method will attempt to fetch the number of messages specified under <paramref name="limit"/>. The
/// library will attempt to split up the requests according to your <paramref name="limit"/> and
/// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages,
/// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will
/// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need
/// of flattening.
/// </remarks>
/// <example>
/// The following example downloads 300 messages and gets messages that belong to the user
/// <c>53905483156684800</c>.
/// <code lang="cs">
/// var messages = await messageChannel.GetMessagesAsync(300).FlattenAsync();
/// var userMessages = messages.Where(x =&gt; x.Author.Id == 53905483156684800);
/// </code>
/// </example>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null);
/// <summary> Gets a collection of messages in this channel. </summary>
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// <note type="important">
/// The returned collection is an asynchronous enumerable object; one must call
/// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a
/// collection.
/// </note>
/// <note type="warning">
/// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual
/// rate limit, causing your bot to freeze!
/// </note>
/// This method will attempt to fetch the number of messages specified under <paramref name="limit"/> around
/// the message <paramref name="fromMessageId"/> depending on the <paramref name="dir"/>. The library will
/// attempt to split up the requests according to your <paramref name="limit"/> and
/// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages,
/// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will
/// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need
/// of flattening.
/// </remarks>
/// <example>
/// The following example gets 5 message prior to the message identifier <c>442012544660537354</c>.
/// <code lang="cs">
/// var messages = await channel.GetMessagesAsync(442012544660537354, Direction.Before, 5).FlattenAsync();
/// </code>
/// </example>
/// <param name="fromMessageId">The ID of the starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from
/// cache.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null);
/// <summary> Gets a collection of messages in this channel. </summary>
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// <note type="important">
/// The returned collection is an asynchronous enumerable object; one must call
/// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a
/// collection.
/// </note>
/// <note type="warning">
/// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual
/// rate limit, causing your bot to freeze!
/// </note>
/// This method will attempt to fetch the number of messages specified under <paramref name="limit"/> around
/// the message <paramref name="fromMessage"/> depending on the <paramref name="dir"/>. The library will
/// attempt to split up the requests according to your <paramref name="limit"/> and
/// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages,
/// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will
/// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need
/// of flattening.
/// </remarks>
/// <example>
/// The following example gets 5 message prior to a specific message, <c>oldMessage</c>.
/// <code lang="cs">
/// var messages = await channel.GetMessagesAsync(oldMessage, Direction.Before, 5).FlattenAsync();
/// </code>
/// </example>
/// <param name="fromMessage">The starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from
/// cache.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null);
/// <summary> Gets a collection of pinned messages in this channel. </summary>
/// <summary>
/// Gets a collection of pinned messages in this channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation for retrieving pinned messages in this channel.
/// The task result contains a collection of messages found in the pinned messages.
/// </returns>
new Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null);
}
}

View File

@@ -1,9 +1,15 @@
using System.Collections.Generic;
using System.Collections.Generic;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based channel that is private to select recipients.
/// </summary>
public interface IRestPrivateChannel : IPrivateChannel
{
/// <summary>
/// Users that can access this channel.
/// </summary>
new IReadOnlyCollection<RestUser> Recipients { get; }
}
}

View File

@@ -1,13 +1,14 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based category channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestCategoryChannel : RestGuildChannel, ICategoryChannel
{
@@ -25,14 +26,22 @@ namespace Discord.Rest
private string DebuggerDisplay => $"{Name} ({Id}, Category)";
// IGuildChannel
/// <inheritdoc />
/// <exception cref="NotSupportedException">This method is not supported with category channels.</exception>
Task<IInviteMetadata> IGuildChannel.CreateInviteAsync(int? maxAge, int? maxUses, bool isTemporary, bool isUnique, RequestOptions options)
=> throw new NotSupportedException();
/// <inheritdoc />
/// <exception cref="NotSupportedException">This method is not supported with category channels.</exception>
Task<IReadOnlyCollection<IInviteMetadata>> IGuildChannel.GetInvitesAsync(RequestOptions options)
=> throw new NotSupportedException();
//IChannel
/// <inheritdoc />
/// <exception cref="NotSupportedException">This method is not supported with category channels.</exception>
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> throw new NotSupportedException();
/// <inheritdoc />
/// <exception cref="NotSupportedException">This method is not supported with category channels.</exception>
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> throw new NotSupportedException();
}

View File

@@ -6,14 +6,19 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a generic REST-based channel.
/// </summary>
public class RestChannel : RestEntity<ulong>, IChannel, IUpdateable
{
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
internal RestChannel(BaseDiscordClient discord, ulong id)
: base(discord, id)
{
}
/// <exception cref="InvalidOperationException">Unexpected channel type.</exception>
internal static RestChannel Create(BaseDiscordClient discord, Model model)
{
switch (model.Type)
@@ -30,6 +35,7 @@ namespace Discord.Rest
return new RestChannel(discord, model.Id);
}
}
/// <exception cref="InvalidOperationException">Unexpected channel type.</exception>
internal static IRestPrivateChannel CreatePrivate(BaseDiscordClient discord, Model model)
{
switch (model.Type)
@@ -44,13 +50,17 @@ namespace Discord.Rest
}
internal virtual void Update(Model model) { }
/// <inheritdoc />
public virtual Task UpdateAsync(RequestOptions options = null) => Task.Delay(0);
//IChannel
/// <inheritdoc />
string IChannel.Name => null;
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(null); //Overridden
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IUser>>(); //Overridden
}

View File

@@ -9,12 +9,25 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based direct-message channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestDMChannel : RestChannel, IDMChannel, IRestPrivateChannel, IRestMessageChannel
{
public RestUser CurrentUser { get; private set; }
public RestUser Recipient { get; private set; }
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public RestUser CurrentUser { get; }
/// <summary>
/// Gets the recipient of the channel.
/// </summary>
public RestUser Recipient { get; }
/// <summary>
/// Gets a collection that is the current logged-in user and the recipient.
/// </summary>
public IReadOnlyCollection<RestUser> Users => ImmutableArray.Create(CurrentUser, Recipient);
internal RestDMChannel(BaseDiscordClient discord, ulong id, ulong recipientId)
@@ -34,14 +47,24 @@ namespace Discord.Rest
Recipient.Update(model.Recipients.Value[0]);
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task CloseAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets a user in this channel from the provided <paramref name="id"/>.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A <see cref="RestUser"/> object that is a recipient of this channel; otherwise <c>null</c>.
/// </returns>
public RestUser GetUser(ulong id)
{
if (id == Recipient.Id)
@@ -52,49 +75,96 @@ namespace Discord.Rest
return null;
}
/// <inheritdoc />
public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetMessageAsync(this, Discord, id, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
/// <summary>
/// Gets a string that represents the Username#Discriminator of the recipient.
/// </summary>
/// <returns>
/// A string that resolves to the Recipient of this channel.
/// </returns>
public override string ToString() => $"@{Recipient}";
private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)";
//IDMChannel
//IDMChannel
/// <inheritdoc />
IUser IDMChannel.Recipient => Recipient;
//IRestPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<RestUser> IRestPrivateChannel.Recipients => ImmutableArray.Create(Recipient);
//IPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => ImmutableArray.Create<IUser>(Recipient);
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -102,6 +172,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -109,6 +180,7 @@ namespace Discord.Rest
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -116,6 +188,7 @@ namespace Discord.Rest
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -123,24 +196,27 @@ namespace Discord.Rest
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
IDisposable IMessageChannel.EnterTypingState(RequestOptions options)
=> EnterTypingState(options);
//IChannel
/// <inheritdoc />
string IChannel.Name => $"@{Recipient}";
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
}

View File

@@ -10,12 +10,16 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based group-message channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestGroupChannel : RestChannel, IGroupChannel, IRestPrivateChannel, IRestMessageChannel, IRestAudioChannel
{
private string _iconId;
private ImmutableDictionary<ulong, RestGroupUser> _users;
/// <inheritdoc />
public string Name { get; private set; }
public IReadOnlyCollection<RestGroupUser> Users => _users.ToReadOnlyCollection();
@@ -49,12 +53,13 @@ namespace Discord.Rest
users[models[i].Id] = RestGroupUser.Create(Discord, models[i]);
_users = users.ToImmutable();
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task LeaveAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
@@ -65,33 +70,70 @@ namespace Discord.Rest
return null;
}
/// <inheritdoc />
public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetMessageAsync(this, Discord, id, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
@@ -143,10 +185,10 @@ namespace Discord.Rest
=> await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
IDisposable IMessageChannel.EnterTypingState(RequestOptions options)
=> EnterTypingState(options);
//IAudioChannel
/// <inheritdoc />
/// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception>
Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); }
Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); }

View File

@@ -7,15 +7,22 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a private REST-based group channel.
/// </summary>
public class RestGuildChannel : RestChannel, IGuildChannel
{
private ImmutableArray<Overwrite> _overwrites;
/// <inheritdoc />
public IReadOnlyCollection<Overwrite> PermissionOverwrites => _overwrites;
internal IGuild Guild { get; }
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public int Position { get; private set; }
/// <inheritdoc />
public ulong GuildId => Guild.Id;
internal RestGuildChannel(BaseDiscordClient discord, IGuild guild, ulong id)
@@ -49,19 +56,29 @@ namespace Discord.Rest
_overwrites = newOverwrites.ToImmutable();
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(GuildId, Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public async Task ModifyAsync(Action<GuildChannelProperties> func, RequestOptions options = null)
{
var model = await ChannelHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets the permission overwrite for a specific user.
/// </summary>
/// <param name="user">The user to get the overwrite from.</param>
/// <returns>
/// An overwrite object for the targeted user; <c>null</c> if none is set.
/// </returns>
public OverwritePermissions? GetPermissionOverwrite(IUser user)
{
for (int i = 0; i < _overwrites.Length; i++)
@@ -71,6 +88,14 @@ namespace Discord.Rest
}
return null;
}
/// <summary>
/// Gets the permission overwrite for a specific role.
/// </summary>
/// <param name="role">The role to get the overwrite from.</param>
/// <returns>
/// An overwrite object for the targeted role; <c>null</c> if none is set.
/// </returns>
public OverwritePermissions? GetPermissionOverwrite(IRole role)
{
for (int i = 0; i < _overwrites.Length; i++)
@@ -80,16 +105,44 @@ namespace Discord.Rest
}
return null;
}
public async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions perms, RequestOptions options = null)
/// <summary>
/// Adds or updates the permission overwrite for the given user.
/// </summary>
/// <param name="user">The user to add the overwrite to.</param>
/// <param name="permissions">The overwrite to add to the user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns>
public async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null)
{
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, perms, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(user.Id, PermissionTarget.User, new OverwritePermissions(perms.AllowValue, perms.DenyValue)));
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(user.Id, PermissionTarget.User, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue)));
}
public async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions perms, RequestOptions options = null)
/// <summary>
/// Adds or updates the permission overwrite for the given role.
/// </summary>
/// <param name="role">The role to add the overwrite to.</param>
/// <param name="permissions">The overwrite to add to the role.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns>
public async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null)
{
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, perms, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(role.Id, PermissionTarget.Role, new OverwritePermissions(perms.AllowValue, perms.DenyValue)));
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(role.Id, PermissionTarget.Role, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue)));
}
/// <summary>
/// Removes the permission overwrite for the given user, if one exists.
/// </summary>
/// <param name="user">The user to remove the overwrite from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns>
public async Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null)
{
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options).ConfigureAwait(false);
@@ -103,6 +156,14 @@ namespace Discord.Rest
}
}
}
/// <summary>
/// Removes the permission overwrite for the given role, if one exists.
/// </summary>
/// <param name="role">The role to remove the overwrite from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns>
public async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null)
{
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options).ConfigureAwait(false);
@@ -117,14 +178,42 @@ namespace Discord.Rest
}
}
/// <summary>
/// Gets a collection of all invites to this channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of invite metadata that are created for this channel.
/// </returns>
public async Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
=> await ChannelHelper.GetInvitesAsync(this, Discord, options).ConfigureAwait(false);
/// <summary>
/// Creates a new invite to this channel.
/// </summary>
/// <param name="maxAge">The time (in seconds) until the invite expires. Set to <c>null</c> to never expire.</param>
/// <param name="maxUses">The max amount of times this invite may be used. Set to <c>null</c> to have unlimited uses.</param>
/// <param name="isTemporary">If <c>true</c>, the user accepting this invite will be kicked from the guild after closing their client.</param>
/// <param name="isUnique">If <c>true</c>, don't try to reuse a similar invite (useful for creating many unique one time use invites).</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous invite creation operation. The task result contains an invite
/// metadata object containing information for the created invite.
/// </returns>
public async Task<RestInviteMetadata> CreateInviteAsync(int? maxAge = 86400, int? maxUses = null, bool isTemporary = false, bool isUnique = false, RequestOptions options = null)
=> await ChannelHelper.CreateInviteAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, options).ConfigureAwait(false);
/// <summary>
/// Gets the name of this channel.
/// </summary>
/// <returns>
/// A string that is the name of this channel.
/// </returns>
public override string ToString() => Name;
//IGuildChannel
/// <inheritdoc />
IGuild IGuildChannel.Guild
{
get
@@ -135,32 +224,44 @@ namespace Discord.Rest
}
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IInviteMetadata>> IGuildChannel.GetInvitesAsync(RequestOptions options)
=> await GetInvitesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IInviteMetadata> IGuildChannel.CreateInviteAsync(int? maxAge, int? maxUses, bool isTemporary, bool isUnique, RequestOptions options)
=> await CreateInviteAsync(maxAge, maxUses, isTemporary, isUnique, options).ConfigureAwait(false);
/// <inheritdoc />
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IRole role)
=> GetPermissionOverwrite(role);
/// <inheritdoc />
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user)
=> GetPermissionOverwrite(user);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IGuildUser>>(); //Overridden //Overridden in Text/Voice
/// <inheritdoc />
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(null); //Overridden in Text/Voice
//IChannel
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IUser>>(); //Overridden in Text/Voice
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(null); //Overridden in Text/Voice
}

View File

@@ -8,17 +8,22 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based channel in a guild that can send and receive messages.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestTextChannel : RestGuildChannel, IRestMessageChannel, ITextChannel
{
/// <inheritdoc />
public string Topic { get; private set; }
public int SlowModeInterval { get; private set; }
/// <inheritdoc />
public ulong? CategoryId { get; private set; }
/// <inheritdoc />
public string Mention => MentionUtils.MentionChannel(Id);
private bool _nsfw;
public bool IsNsfw => _nsfw;
/// <inheritdoc />
public bool IsNsfw { get; private set; }
internal RestTextChannel(BaseDiscordClient discord, IGuild guild, ulong id)
: base(discord, guild, id)
@@ -30,82 +35,188 @@ namespace Discord.Rest
entity.Update(model);
return entity;
}
/// <inheritdoc />
internal override void Update(Model model)
{
base.Update(model);
CategoryId = model.CategoryId;
Topic = model.Topic.Value;
SlowModeInterval = model.SlowMode.Value;
_nsfw = model.Nsfw.GetValueOrDefault();
IsNsfw = model.Nsfw.GetValueOrDefault();
}
/// <inheritdoc />
public async Task ModifyAsync(Action<TextChannelProperties> func, RequestOptions options = null)
{
var model = await ChannelHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <summary>
/// Gets a user in this channel.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="InvalidOperationException">
/// Resolving permissions requires the parent guild to be downloaded.
/// </exception>
/// <returns>
/// A task representing the asynchronous get operation. The task result contains a guild user object that
/// represents the user; <c>null</c> if none is found.
/// </returns>
public Task<RestGuildUser> GetUserAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetUserAsync(this, Guild, Discord, id, options);
/// <summary>
/// Gets a collection of users that are able to view the channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="InvalidOperationException">
/// Resolving permissions requires the parent guild to be downloaded.
/// </exception>
/// <returns>
/// A paged collection containing a collection of guild users that can access this channel. Flattening the
/// paginated response into a collection of users with
/// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> is required if you wish to access the users.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(RequestOptions options = null)
=> ChannelHelper.GetUsersAsync(this, Guild, Discord, null, null, options);
/// <inheritdoc />
public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetMessageAsync(this, Discord, id, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task DeleteMessagesAsync(IEnumerable<IMessage> messages, RequestOptions options = null)
=> ChannelHelper.DeleteMessagesAsync(this, Discord, messages.Select(x => x.Id), options);
/// <inheritdoc />
public Task DeleteMessagesAsync(IEnumerable<ulong> messageIds, RequestOptions options = null)
=> ChannelHelper.DeleteMessagesAsync(this, Discord, messageIds, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
/// <summary>
/// Creates a webhook in this text channel.
/// </summary>
/// <param name="name">The name of the webhook.</param>
/// <param name="avatar">The avatar of the webhook.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// webhook.
/// </returns>
public Task<RestWebhook> CreateWebhookAsync(string name, Stream avatar = null, RequestOptions options = null)
=> ChannelHelper.CreateWebhookAsync(this, Discord, name, avatar, options);
/// <summary>
/// Gets a webhook available in this text channel.
/// </summary>
/// <param name="id">The identifier of the webhook.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a webhook associated
/// with the identifier; <c>null</c> if the webhook is not found.
/// </returns>
public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetWebhookAsync(this, Discord, id, options);
/// <summary>
/// Gets the webhooks available in this text channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of webhooks that is available in this channel.
/// </returns>
public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null)
=> ChannelHelper.GetWebhooksAsync(this, Discord, options);
/// <summary>
/// Gets the parent (category) channel of this channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the category channel
/// representing the parent of this channel; <c>null</c> if none is set.
/// </returns>
public Task<ICategoryChannel> GetCategoryAsync(RequestOptions options = null)
=> ChannelHelper.GetCategoryAsync(this, Discord, options);
private string DebuggerDisplay => $"{Name} ({Id}, Text)";
//ITextChannel
/// <inheritdoc />
async Task<IWebhook> ITextChannel.CreateWebhookAsync(string name, Stream avatar, RequestOptions options)
=> await CreateWebhookAsync(name, avatar, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IWebhook> ITextChannel.GetWebhookAsync(ulong id, RequestOptions options)
=> await GetWebhookAsync(id, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IWebhook>> ITextChannel.GetWebhooksAsync(RequestOptions options)
=> await GetWebhooksAsync(options).ConfigureAwait(false);
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -113,6 +224,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -121,6 +233,7 @@ namespace Discord.Rest
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -128,6 +241,7 @@ namespace Discord.Rest
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -135,20 +249,23 @@ namespace Discord.Rest
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
IDisposable IMessageChannel.EnterTypingState(RequestOptions options)
=> EnterTypingState(options);
//IGuildChannel
/// <inheritdoc />
async Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -156,6 +273,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -165,6 +283,7 @@ namespace Discord.Rest
}
//IChannel
/// <inheritdoc />
async Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -172,6 +291,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -181,6 +301,7 @@ namespace Discord.Rest
}
// INestedChannel
/// <inheritdoc />
async Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options)
{
if (CategoryId.HasValue && mode == CacheMode.AllowDownload)

View File

@@ -8,11 +8,17 @@ using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based voice channel in a guild.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestVoiceChannel : RestGuildChannel, IVoiceChannel, IRestAudioChannel
{
/// <inheritdoc />
public int Bitrate { get; private set; }
/// <inheritdoc />
public int? UserLimit { get; private set; }
/// <inheritdoc />
public ulong? CategoryId { get; private set; }
internal RestVoiceChannel(BaseDiscordClient discord, IGuild guild, ulong id)
@@ -25,6 +31,7 @@ namespace Discord.Rest
entity.Update(model);
return entity;
}
/// <inheritdoc />
internal override void Update(Model model)
{
base.Update(model);
@@ -33,24 +40,37 @@ namespace Discord.Rest
UserLimit = model.UserLimit.Value != 0 ? model.UserLimit.Value : (int?)null;
}
/// <inheritdoc />
public async Task ModifyAsync(Action<VoiceChannelProperties> func, RequestOptions options = null)
{
var model = await ChannelHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <summary>
/// Gets the parent (category) channel of this channel.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the category channel
/// representing the parent of this channel; <c>null</c> if none is set.
/// </returns>
public Task<ICategoryChannel> GetCategoryAsync(RequestOptions options = null)
=> ChannelHelper.GetCategoryAsync(this, Discord, options);
private string DebuggerDisplay => $"{Name} ({Id}, Voice)";
//IAudioChannel
/// <inheritdoc />
/// <exception cref="NotSupportedException">Connecting to a REST-based channel is not supported.</exception>
Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); }
Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); }
//IGuildChannel
/// <inheritdoc />
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(null);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IGuildUser>>();

View File

@@ -41,13 +41,17 @@ namespace Discord.Rest
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
@@ -57,7 +61,7 @@ namespace Discord.Rest
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options);
return await GetMessageAsync(id, options).ConfigureAwait(false);
else
return null;
}
@@ -83,27 +87,24 @@ namespace Discord.Rest
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options);
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(filePath, text, isTTS, embed, options);
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options);
=> await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options);
IDisposable IMessageChannel.EnterTypingState(RequestOptions options)
=> EnterTypingState(options);
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
//IChannel
string IChannel.Name { get { throw new NotSupportedException(); } }
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
{
string IChannel.Name =>
throw new NotSupportedException();
}
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
{
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) =>
throw new NotSupportedException();
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) =>
throw new NotSupportedException();
}
}
}

View File

@@ -14,10 +14,11 @@ namespace Discord.Rest
internal static class GuildHelper
{
//General
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public static async Task<Model> ModifyAsync(IGuild guild, BaseDiscordClient client,
Action<GuildProperties> func, RequestOptions options)
{
if (func == null) throw new NullReferenceException(nameof(func));
if (func == null) throw new ArgumentNullException(nameof(func));
var args = new GuildProperties();
func(args);
@@ -31,7 +32,6 @@ namespace Discord.Rest
Icon = args.Icon.IsSpecified ? args.Icon.Value?.ToModel() : Optional.Create<ImageModel?>(),
Name = args.Name,
Splash = args.Splash.IsSpecified ? args.Splash.Value?.ToModel() : Optional.Create<ImageModel?>(),
Username = args.Username,
VerificationLevel = args.VerificationLevel
};
@@ -62,10 +62,11 @@ namespace Discord.Rest
return await client.ApiClient.ModifyGuildAsync(guild.Id, apiArgs, options).ConfigureAwait(false);
}
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public static async Task<EmbedModel> ModifyEmbedAsync(IGuild guild, BaseDiscordClient client,
Action<GuildEmbedProperties> func, RequestOptions options)
{
if (func == null) throw new NullReferenceException(nameof(func));
if (func == null) throw new ArgumentNullException(nameof(func));
var args = new GuildEmbedProperties();
func(args);
@@ -144,6 +145,7 @@ namespace Discord.Rest
var models = await client.ApiClient.GetGuildChannelsAsync(guild.Id, options).ConfigureAwait(false);
return models.Select(x => RestGuildChannel.Create(client, guild, x)).ToImmutableArray();
}
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
public static async Task<RestTextChannel> CreateTextChannelAsync(IGuild guild, BaseDiscordClient client,
string name, RequestOptions options, Action<TextChannelProperties> func = null)
{
@@ -161,6 +163,7 @@ namespace Discord.Rest
var model = await client.ApiClient.CreateGuildChannelAsync(guild.Id, args, options).ConfigureAwait(false);
return RestTextChannel.Create(client, guild, model);
}
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
public static async Task<RestVoiceChannel> CreateVoiceChannelAsync(IGuild guild, BaseDiscordClient client,
string name, RequestOptions options, Action<VoiceChannelProperties> func = null)
{
@@ -178,6 +181,7 @@ namespace Discord.Rest
var model = await client.ApiClient.CreateGuildChannelAsync(guild.Id, args, options).ConfigureAwait(false);
return RestVoiceChannel.Create(client, guild, model);
}
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
public static async Task<RestCategoryChannel> CreateCategoryChannelAsync(IGuild guild, BaseDiscordClient client,
string name, RequestOptions options)
{
@@ -220,6 +224,7 @@ namespace Discord.Rest
}
//Roles
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
public static async Task<RestRole> CreateRoleAsync(IGuild guild, BaseDiscordClient client,
string name, GuildPermissions? permissions, Color? color, bool isHoisted, RequestOptions options)
{
@@ -266,7 +271,7 @@ namespace Discord.Rest
};
if (info.Position != null)
args.AfterUserId = info.Position.Value;
var models = await client.ApiClient.GetGuildMembersAsync(guild.Id, args, options);
var models = await client.ApiClient.GetGuildMembersAsync(guild.Id, args, options).ConfigureAwait(false);
return models.Select(x => RestGuildUser.Create(client, guild, x)).ToImmutableArray();
},
nextPage: (info, lastPage) =>
@@ -338,7 +343,7 @@ namespace Discord.Rest
//Emotes
public static async Task<GuildEmote> GetEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options)
{
var emote = await client.ApiClient.GetGuildEmoteAsync(guild.Id, id, options);
var emote = await client.ApiClient.GetGuildEmoteAsync(guild.Id, id, options).ConfigureAwait(false);
return emote.ToEntity();
}
public static async Task<GuildEmote> CreateEmoteAsync(IGuild guild, BaseDiscordClient client, string name, Image image, Optional<IEnumerable<IRole>> roles,
@@ -350,11 +355,12 @@ namespace Discord.Rest
Image = image.ToModel()
};
if (roles.IsSpecified)
apiargs.RoleIds = roles.Value?.Select(xr => xr.Id)?.ToArray();
apiargs.RoleIds = roles.Value?.Select(xr => xr.Id).ToArray();
var emote = await client.ApiClient.CreateGuildEmoteAsync(guild.Id, apiargs, options);
var emote = await client.ApiClient.CreateGuildEmoteAsync(guild.Id, apiargs, options).ConfigureAwait(false);
return emote.ToEntity();
}
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public static async Task<GuildEmote> ModifyEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, Action<EmoteProperties> func,
RequestOptions options)
{
@@ -368,9 +374,9 @@ namespace Discord.Rest
Name = props.Name
};
if (props.Roles.IsSpecified)
apiargs.RoleIds = props.Roles.Value?.Select(xr => xr.Id)?.ToArray();
apiargs.RoleIds = props.Roles.Value?.Select(xr => xr.Id).ToArray();
var emote = await client.ApiClient.ModifyGuildEmoteAsync(guild.Id, id, apiargs, options);
var emote = await client.ApiClient.ModifyGuildEmoteAsync(guild.Id, id, apiargs, options).ConfigureAwait(false);
return emote.ToEntity();
}
public static Task DeleteEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options)

View File

@@ -1,12 +1,22 @@
using System.Diagnostics;
using System.Diagnostics;
using Model = Discord.API.Ban;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based ban object.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestBan : IBan
{
/// <summary>
/// Gets the banned user.
/// </summary>
/// <returns>
/// A generic <see cref="RestUser"/> object that was banned.
/// </returns>
public RestUser User { get; }
/// <inheritdoc />
public string Reason { get; }
internal RestBan(RestUser user, string reason)
@@ -19,10 +29,17 @@ namespace Discord.Rest
return new RestBan(RestUser.Create(client, model.User), model.Reason);
}
/// <summary>
/// Gets the name of the banned user.
/// </summary>
/// <returns>
/// A string containing the name of the user that was banned.
/// </returns>
public override string ToString() => User.ToString();
private string DebuggerDisplay => $"{User}: {Reason}";
//IBan
/// <inheritdoc />
IUser IBan.User => User;
}
}

View File

@@ -10,6 +10,9 @@ using Model = Discord.API.Guild;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based guild/server.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestGuild : RestEntity<ulong>, IGuild, IUpdateable
{
@@ -17,32 +20,57 @@ namespace Discord.Rest
private ImmutableArray<GuildEmote> _emotes;
private ImmutableArray<string> _features;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public int AFKTimeout { get; private set; }
/// <inheritdoc />
public bool IsEmbeddable { get; private set; }
/// <inheritdoc />
public VerificationLevel VerificationLevel { get; private set; }
/// <inheritdoc />
public MfaLevel MfaLevel { get; private set; }
/// <inheritdoc />
public DefaultMessageNotifications DefaultMessageNotifications { get; private set; }
/// <inheritdoc />
public ulong? AFKChannelId { get; private set; }
/// <inheritdoc />
public ulong? EmbedChannelId { get; private set; }
/// <inheritdoc />
public ulong? SystemChannelId { get; private set; }
/// <inheritdoc />
public ulong OwnerId { get; private set; }
/// <inheritdoc />
public string VoiceRegionId { get; private set; }
/// <inheritdoc />
public string IconId { get; private set; }
/// <inheritdoc />
public string SplashId { get; private set; }
internal bool Available { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
[Obsolete("DefaultChannelId is deprecated, use GetDefaultChannelAsync")]
public ulong DefaultChannelId => Id;
/// <inheritdoc />
public string IconUrl => CDN.GetGuildIconUrl(Id, IconId);
/// <inheritdoc />
public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId);
/// <summary>
/// Gets the built-in role containing all users in this guild.
/// </summary>
public RestRole EveryoneRole => GetRole(Id);
/// <summary>
/// Gets a collection of all roles in this guild.
/// </summary>
public IReadOnlyCollection<RestRole> Roles => _roles.ToReadOnlyCollection();
/// <inheritdoc />
public IReadOnlyCollection<GuildEmote> Emotes => _emotes;
/// <inheritdoc />
public IReadOnlyCollection<string> Features => _features;
internal RestGuild(BaseDiscordClient client, ulong id)
@@ -103,89 +131,206 @@ namespace Discord.Rest
}
//General
/// <inheritdoc />
public async Task UpdateAsync(RequestOptions options = null)
=> Update(await Discord.ApiClient.GetGuildAsync(Id, options).ConfigureAwait(false));
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> GuildHelper.DeleteAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public async Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null)
{
var model = await GuildHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public async Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null)
{
var model = await GuildHelper.ModifyEmbedAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="args" /> is <c>null</c>.</exception>
public async Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
{
var arr = args.ToArray();
await GuildHelper.ReorderChannelsAsync(this, Discord, arr, options);
await GuildHelper.ReorderChannelsAsync(this, Discord, arr, options).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
{
var models = await GuildHelper.ReorderRolesAsync(this, Discord, args, options).ConfigureAwait(false);
foreach (var model in models)
{
var role = GetRole(model.Id);
if (role != null)
role.Update(model);
role?.Update(model);
}
}
/// <inheritdoc />
public Task LeaveAsync(RequestOptions options = null)
=> GuildHelper.LeaveAsync(this, Discord, options);
//Bans
//Bans
/// <summary>
/// Gets a collection of all users banned in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// ban objects that this guild currently possesses, with each object containing the user banned and reason
/// behind the ban.
/// </returns>
public Task<IReadOnlyCollection<RestBan>> GetBansAsync(RequestOptions options = null)
=> GuildHelper.GetBansAsync(this, Discord, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="user">The banned user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, user.Id, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="userId">The snowflake identifier for the banned user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, userId, options);
/// <inheritdoc />
public Task AddBanAsync(IUser user, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, user.Id, pruneDays, reason, options);
/// <inheritdoc />
public Task AddBanAsync(ulong userId, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, userId, pruneDays, reason, options);
/// <inheritdoc />
public Task RemoveBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, user.Id, options);
/// <inheritdoc />
public Task RemoveBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, userId, options);
//Channels
/// <summary>
/// Gets a collection of all channels in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// generic channels found within this guild.
/// </returns>
public Task<IReadOnlyCollection<RestGuildChannel>> GetChannelsAsync(RequestOptions options = null)
=> GuildHelper.GetChannelsAsync(this, Discord, options);
/// <summary>
/// Gets a channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the channel.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the generic channel
/// associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public Task<RestGuildChannel> GetChannelAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetChannelAsync(this, Discord, id, options);
/// <summary>
/// Gets a text channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the text channel.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the text channel
/// associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public async Task<RestTextChannel> GetTextChannelAsync(ulong id, RequestOptions options = null)
{
var channel = await GuildHelper.GetChannelAsync(this, Discord, id, options).ConfigureAwait(false);
return channel as RestTextChannel;
}
/// <summary>
/// Gets a collection of all text channels in this guild.
/// </summary>
/// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from cache.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// message channels found within this guild.
/// </returns>
public async Task<IReadOnlyCollection<RestTextChannel>> GetTextChannelsAsync(RequestOptions options = null)
{
var channels = await GuildHelper.GetChannelsAsync(this, Discord, options).ConfigureAwait(false);
return channels.OfType<RestTextChannel>().ToImmutableArray();
}
/// <summary>
/// Gets a voice channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the voice channel.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the voice channel associated
/// with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public async Task<RestVoiceChannel> GetVoiceChannelAsync(ulong id, RequestOptions options = null)
{
var channel = await GuildHelper.GetChannelAsync(this, Discord, id, options).ConfigureAwait(false);
return channel as RestVoiceChannel;
}
/// <summary>
/// Gets a collection of all voice channels in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// voice channels found within this guild.
/// </returns>
public async Task<IReadOnlyCollection<RestVoiceChannel>> GetVoiceChannelsAsync(RequestOptions options = null)
{
var channels = await GuildHelper.GetChannelsAsync(this, Discord, options).ConfigureAwait(false);
return channels.OfType<RestVoiceChannel>().ToImmutableArray();
}
/// <summary>
/// Gets a collection of all category channels in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// category channels found within this guild.
/// </returns>
public async Task<IReadOnlyCollection<RestCategoryChannel>> GetCategoryChannelsAsync(RequestOptions options = null)
{
var channels = await GuildHelper.GetChannelsAsync(this, Discord, options).ConfigureAwait(false);
return channels.OfType<RestCategoryChannel>().ToImmutableArray();
}
/// <summary>
/// Gets the AFK voice channel in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the voice channel that the
/// AFK users will be moved to after they have idled for too long; <c>null</c> if none is set.
/// </returns>
public async Task<RestVoiceChannel> GetAFKChannelAsync(RequestOptions options = null)
{
var afkId = AFKChannelId;
@@ -196,6 +341,15 @@ namespace Discord.Rest
}
return null;
}
/// <summary>
/// Gets the first viewable text channel in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the first viewable text
/// channel in this guild; <c>null</c> if none is found.
/// </returns>
public async Task<RestTextChannel> GetDefaultChannelAsync(RequestOptions options = null)
{
var channels = await GetTextChannelsAsync(options).ConfigureAwait(false);
@@ -205,6 +359,15 @@ namespace Discord.Rest
.OrderBy(c => c.Position)
.FirstOrDefault();
}
/// <summary>
/// Gets the embed channel (i.e. the channel set in the guild's widget settings) in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the embed channel set
/// within the server's widget settings; <c>null</c> if none is set.
/// </returns>
public async Task<RestGuildChannel> GetEmbedChannelAsync(RequestOptions options = null)
{
var embedId = EmbedChannelId;
@@ -212,6 +375,15 @@ namespace Discord.Rest
return await GuildHelper.GetChannelAsync(this, Discord, embedId.Value, options).ConfigureAwait(false);
return null;
}
/// <summary>
/// Gets the first viewable text channel in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the first viewable text
/// channel in this guild; <c>null</c> if none is found.
/// </returns>
public async Task<RestTextChannel> GetSystemChannelAsync(RequestOptions options = null)
{
var systemId = SystemChannelId;
@@ -222,10 +394,52 @@ namespace Discord.Rest
}
return null;
}
/// <summary>
/// Creates a new text channel in this guild.
/// </summary>
/// <example>
/// The following example creates a new text channel under an existing category named <c>Wumpus</c> with a set topic.
/// <code lang="cs">
/// var categories = await guild.GetCategoriesAsync();
/// var targetCategory = categories.FirstOrDefault(x => x.Name == "wumpus");
/// if (targetCategory == null) return;
/// await Context.Guild.CreateTextChannelAsync(name, x =>
/// {
/// x.CategoryId = targetCategory.Id;
/// x.Topic = $"This channel was created at {DateTimeOffset.UtcNow} by {user}.";
/// });
/// </code>
/// </example>
/// <param name="name">The new name for the text channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// text channel.
/// </returns>
public Task<RestTextChannel> CreateTextChannelAsync(string name, Action<TextChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateTextChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a voice channel with the provided name.
/// </summary>
/// <param name="name">The name of the new channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name" /> is <c>null</c>.</exception>
/// <returns>
/// The created voice channel.
/// </returns>
public Task<RestVoiceChannel> CreateVoiceChannelAsync(string name, Action<VoiceChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateVoiceChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a category channel with the provided name.
/// </summary>
/// <param name="name">The name of the new channel.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name" /> is <c>null</c>.</exception>
/// <returns>
/// The created category channel.
/// </returns>
public Task<RestCategoryChannel> CreateCategoryChannelAsync(string name, RequestOptions options = null)
=> GuildHelper.CreateCategoryChannelAsync(this, Discord, name, options);
@@ -236,6 +450,14 @@ namespace Discord.Rest
=> GuildHelper.CreateIntegrationAsync(this, Discord, id, type, options);
//Invites
/// <summary>
/// Gets a collection of all invites in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// invite metadata, each representing information for an invite found within this guild.
/// </returns>
public Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
=> GuildHelper.GetInvitesAsync(this, Discord, options);
/// <summary>
@@ -249,6 +471,13 @@ namespace Discord.Rest
=> GuildHelper.GetVanityInviteAsync(this, Discord, options);
//Roles
/// <summary>
/// Gets a role in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the role.</param>
/// <returns>
/// A role that is associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public RestRole GetRole(ulong id)
{
if (_roles.TryGetValue(id, out RestRole value))
@@ -256,6 +485,18 @@ namespace Discord.Rest
return null;
}
/// <summary>
/// Creates a new role with the provided name.
/// </summary>
/// <param name="name">The new name for the role.</param>
/// <param name="permissions">The guild permission that the role should possess.</param>
/// <param name="color">The color of the role.</param>
/// <param name="isHoisted">Whether the role is separated from others on the sidebar.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// role.
/// </returns>
public async Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
bool isHoisted = false, RequestOptions options = null)
{
@@ -265,47 +506,151 @@ namespace Discord.Rest
}
//Users
/// <summary>
/// Gets a collection of all users in this guild.
/// </summary>
/// <remarks>
/// This method retrieves all users found within this guild.
/// </remarks>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a collection of guild
/// users found within this guild.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(RequestOptions options = null)
=> GuildHelper.GetUsersAsync(this, Discord, null, null, options);
/// <summary>
/// Gets a user from this guild.
/// </summary>
/// <remarks>
/// This method retrieves a user found within this guild.
/// </remarks>
/// <param name="id">The snowflake identifier of the user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the guild user
/// associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public Task<RestGuildUser> GetUserAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetUserAsync(this, Discord, id, options);
/// <summary>
/// Gets the current user for this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the currently logged-in
/// user within this guild.
/// </returns>
public Task<RestGuildUser> GetCurrentUserAsync(RequestOptions options = null)
=> GuildHelper.GetUserAsync(this, Discord, Discord.CurrentUser.Id, options);
/// <summary>
/// Gets the owner of this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the owner of this guild.
/// </returns>
public Task<RestGuildUser> GetOwnerAsync(RequestOptions options = null)
=> GuildHelper.GetUserAsync(this, Discord, OwnerId, options);
/// <inheritdoc />
/// <summary>
/// Prunes inactive users.
/// </summary>
/// <remarks>
/// <para>
/// This method removes all users that have not logged on in the provided number of <paramref name="days"/>.
/// </para>
/// <para>
/// If <paramref name="simulate" /> is <c>true</c>, this method will only return the number of users that
/// would be removed without kicking the users.
/// </para>
/// </remarks>
/// <param name="days">The number of days required for the users to be kicked.</param>
/// <param name="simulate">Whether this prune action is a simulation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous prune operation. The task result contains the number of users to
/// be or has been removed from this guild.
/// </returns>
public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null)
=> GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options);
//Audit logs
/// <summary>
/// Gets the specified number of audit log entries for this guild.
/// </summary>
/// <param name="limit">The number of audit log entries to fetch.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of the requested audit log entries.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestAuditLogEntry>> GetAuditLogsAsync(int limit, RequestOptions options = null)
=> GuildHelper.GetAuditLogsAsync(this, Discord, null, limit, options);
//Webhooks
/// <summary>
/// Gets a webhook found within this guild.
/// </summary>
/// <param name="id">The identifier for the webhook.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the webhook with the
/// specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetWebhookAsync(this, Discord, id, options);
/// <summary>
/// Gets a collection of all webhook from this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of webhooks found within the guild.
/// </returns>
public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null)
=> GuildHelper.GetWebhooksAsync(this, Discord, options);
/// <summary>
/// Returns the name of the guild.
/// </summary>
/// <returns>
/// The name of the guild.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id})";
//Emotes
/// <inheritdoc />
public Task<GuildEmote> GetEmoteAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetEmoteAsync(this, Discord, id, options);
/// <inheritdoc />
public Task<GuildEmote> CreateEmoteAsync(string name, Image image, Optional<IEnumerable<IRole>> roles = default(Optional<IEnumerable<IRole>>), RequestOptions options = null)
=> GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task<GuildEmote> ModifyEmoteAsync(GuildEmote emote, Action<EmoteProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options);
/// <inheritdoc />
public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null)
=> GuildHelper.DeleteEmoteAsync(this, Discord, emote.Id, options);
//IGuild
/// <inheritdoc />
bool IGuild.Available => Available;
/// <inheritdoc />
IAudioClient IGuild.AudioClient => null;
/// <inheritdoc />
IRole IGuild.EveryoneRole => EveryoneRole;
/// <inheritdoc />
IReadOnlyCollection<IRole> IGuild.Roles => Roles;
/// <inheritdoc />
async Task<IReadOnlyCollection<IBan>> IGuild.GetBansAsync(RequestOptions options)
=> await GetBansAsync(options).ConfigureAwait(false);
/// <inheritdoc/>
@@ -315,6 +660,7 @@ namespace Discord.Rest
async Task<IBan> IGuild.GetBanAsync(ulong userId, RequestOptions options)
=> await GetBanAsync(userId, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IGuildChannel>> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -322,6 +668,7 @@ namespace Discord.Rest
else
return ImmutableArray.Create<IGuildChannel>();
}
/// <inheritdoc />
async Task<IGuildChannel> IGuild.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -329,6 +676,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IReadOnlyCollection<ITextChannel>> IGuild.GetTextChannelsAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -336,6 +684,7 @@ namespace Discord.Rest
else
return ImmutableArray.Create<ITextChannel>();
}
/// <inheritdoc />
async Task<ITextChannel> IGuild.GetTextChannelAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -343,6 +692,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IVoiceChannel>> IGuild.GetVoiceChannelsAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -350,6 +700,7 @@ namespace Discord.Rest
else
return ImmutableArray.Create<IVoiceChannel>();
}
/// <inheritdoc />
async Task<IReadOnlyCollection<ICategoryChannel>> IGuild.GetCategoriesAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -357,6 +708,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IVoiceChannel> IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -364,6 +716,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IVoiceChannel> IGuild.GetAFKChannelAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -371,6 +724,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<ITextChannel> IGuild.GetDefaultChannelAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -378,6 +732,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IGuildChannel> IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -385,6 +740,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<ITextChannel> IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -392,29 +748,38 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<ITextChannel> IGuild.CreateTextChannelAsync(string name, Action<TextChannelProperties> func, RequestOptions options)
=> await CreateTextChannelAsync(name, func, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IVoiceChannel> IGuild.CreateVoiceChannelAsync(string name, Action<VoiceChannelProperties> func, RequestOptions options)
=> await CreateVoiceChannelAsync(name, func, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<ICategoryChannel> IGuild.CreateCategoryAsync(string name, RequestOptions options)
=> await CreateCategoryChannelAsync(name, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IGuildIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options)
=> await GetIntegrationsAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IGuildIntegration> IGuild.CreateIntegrationAsync(ulong id, string type, RequestOptions options)
=> await CreateIntegrationAsync(id, type, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options)
=> await GetInvitesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IInviteMetadata> IGuild.GetVanityInviteAsync(RequestOptions options)
=> await GetVanityInviteAsync(options).ConfigureAwait(false);
/// <inheritdoc />
IRole IGuild.GetRole(ulong id)
=> GetRole(id);
/// <inheritdoc />
async Task<IRole> IGuild.CreateRoleAsync(string name, GuildPermissions? permissions, Color? color, bool isHoisted, RequestOptions options)
=> await CreateRoleAsync(name, permissions, color, isHoisted, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -422,6 +787,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IGuildUser> IGuild.GetCurrentUserAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -429,6 +795,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IGuildUser> IGuild.GetOwnerAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -436,6 +803,7 @@ namespace Discord.Rest
else
return null;
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IGuildUser>> IGuild.GetUsersAsync(CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
@@ -443,7 +811,10 @@ namespace Discord.Rest
else
return ImmutableArray.Create<IGuildUser>();
}
Task IGuild.DownloadUsersAsync() { throw new NotSupportedException(); }
/// <inheritdoc />
/// <exception cref="NotSupportedException">Downloading users is not supported for a REST-based guild.</exception>
Task IGuild.DownloadUsersAsync() =>
throw new NotSupportedException();
async Task<IReadOnlyCollection<IAuditLogEntry>> IGuild.GetAuditLogsAsync(int limit, CacheMode cacheMode, RequestOptions options)
{
@@ -453,9 +824,11 @@ namespace Discord.Rest
return ImmutableArray.Create<IAuditLogEntry>();
}
/// <inheritdoc />
async Task<IWebhook> IGuild.GetWebhookAsync(ulong id, RequestOptions options)
=> await GetWebhookAsync(id, options);
=> await GetWebhookAsync(id, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IWebhook>> IGuild.GetWebhooksAsync(RequestOptions options)
=> await GetWebhooksAsync(options);
=> await GetWebhooksAsync(options).ConfigureAwait(false);
}
}

View File

@@ -1,4 +1,4 @@
using System.Diagnostics;
using System.Diagnostics;
using Model = Discord.API.GuildEmbed;
namespace Discord
@@ -19,7 +19,7 @@ namespace Discord
return new RestGuildEmbed(model.Enabled, model.ChannelId);
}
public override string ToString() => ChannelId?.ToString();
public override string ToString() => ChannelId?.ToString() ?? "Unknown";
private string DebuggerDisplay => $"{ChannelId} ({(IsEnabled ? "Enabled" : "Disabled")})";
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.Integration;
@@ -10,18 +10,28 @@ namespace Discord.Rest
{
private long _syncedAtTicks;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public string Type { get; private set; }
/// <inheritdoc />
public bool IsEnabled { get; private set; }
/// <inheritdoc />
public bool IsSyncing { get; private set; }
/// <inheritdoc />
public ulong ExpireBehavior { get; private set; }
/// <inheritdoc />
public ulong ExpireGracePeriod { get; private set; }
/// <inheritdoc />
public ulong GuildId { get; private set; }
/// <inheritdoc />
public ulong RoleId { get; private set; }
public RestUser User { get; private set; }
/// <inheritdoc />
public IntegrationAccount Account { get; private set; }
internal IGuild Guild { get; private set; }
/// <inheritdoc />
public DateTimeOffset SyncedAt => DateTimeUtils.FromTicks(_syncedAtTicks);
internal RestGuildIntegration(BaseDiscordClient discord, IGuild guild, ulong id)
@@ -78,6 +88,7 @@ namespace Discord.Rest
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}{(IsEnabled ? ", Enabled" : "")})";
/// <inheritdoc />
IGuild IGuildIntegration.Guild
{
get
@@ -87,6 +98,7 @@ namespace Discord.Rest
throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
}
}
/// <inheritdoc />
IUser IGuildIntegration.User => User;
}
}

View File

@@ -9,12 +9,17 @@ namespace Discord.Rest
public class RestUserGuild : RestEntity<ulong>, IUserGuild
{
private string _iconId;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public bool IsOwner { get; private set; }
/// <inheritdoc />
public GuildPermissions Permissions { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public string IconUrl => CDN.GetGuildIconUrl(Id, _iconId);
internal RestUserGuild(BaseDiscordClient discord, ulong id)
@@ -40,6 +45,7 @@ namespace Discord.Rest
{
await Discord.ApiClient.LeaveGuildAsync(Id, options).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task DeleteAsync(RequestOptions options = null)
{
await Discord.ApiClient.DeleteGuildAsync(Id, options).ConfigureAwait(false);

View File

@@ -4,6 +4,9 @@ using Model = Discord.API.VoiceRegion;
namespace Discord
{
/// <summary>
/// Represents a REST-based voice region.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class RestVoiceRegion : RestEntity<string>, IVoiceRegion
{

View File

@@ -9,16 +9,24 @@ namespace Discord.Rest
public class RestInvite : RestEntity<string>, IInvite, IUpdateable
{
public ChannelType ChannelType { get; private set; }
/// <inheritdoc />
public string ChannelName { get; private set; }
/// <inheritdoc />
public string GuildName { get; private set; }
/// <inheritdoc />
public int? PresenceCount { get; private set; }
/// <inheritdoc />
public int? MemberCount { get; private set; }
/// <inheritdoc />
public ulong ChannelId { get; private set; }
/// <inheritdoc />
public ulong? GuildId { get; private set; }
internal IChannel Channel { get; }
internal IGuild Guild { get; }
/// <inheritdoc />
public string Code => Id;
/// <inheritdoc />
public string Url => $"{DiscordConfig.InviteUrl}{Code}";
internal RestInvite(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
@@ -43,18 +51,27 @@ namespace Discord.Rest
PresenceCount = model.PresenceCount.IsSpecified ? model.PresenceCount.Value : null;
ChannelType = (ChannelType)model.Channel.Type;
}
/// <inheritdoc />
public async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetInviteAsync(Code, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> InviteHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets the URL of the invite.
/// </summary>
/// <returns>
/// A string that resolves to the Url of the invite.
/// </returns>
public override string ToString() => Url;
private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName})";
/// <inheritdoc />
IGuild IInvite.Guild
{
get
@@ -66,6 +83,7 @@ namespace Discord.Rest
throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
}
}
/// <inheritdoc />
IChannel IInvite.Channel
{
get

View File

@@ -3,17 +3,27 @@ using Model = Discord.API.InviteMetadata;
namespace Discord.Rest
{
/// <summary> Represents additional information regarding the REST-based invite object. </summary>
public class RestInviteMetadata : RestInvite, IInviteMetadata
{
private long? _createdAtTicks;
/// <inheritdoc />
public bool IsRevoked { get; private set; }
/// <inheritdoc />
public bool IsTemporary { get; private set; }
/// <inheritdoc />
public int? MaxAge { get; private set; }
/// <inheritdoc />
public int? MaxUses { get; private set; }
/// <inheritdoc />
public int? Uses { get; private set; }
/// <summary>
/// Gets the user that created this invite.
/// </summary>
public RestUser Inviter { get; private set; }
/// <inheritdoc />
public DateTimeOffset? CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks);
internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
@@ -38,6 +48,7 @@ namespace Discord.Rest
_createdAtTicks = model.CreatedAt.IsSpecified ? model.CreatedAt.Value.UtcTicks : (long?)null;
}
/// <inheritdoc />
IUser IInviteMetadata.Inviter => Inviter;
}
}

View File

@@ -1,17 +1,27 @@
using System.Diagnostics;
using System.Diagnostics;
using Model = Discord.API.Attachment;
namespace Discord
{
/// <summary>
/// An attachment file seen in a <see cref="IUserMessage"/>.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class Attachment : IAttachment
{
/// <inheritdoc />
public ulong Id { get; }
/// <inheritdoc />
public string Filename { get; }
/// <inheritdoc />
public string Url { get; }
/// <inheritdoc />
public string ProxyUrl { get; }
/// <inheritdoc />
public int Size { get; }
/// <inheritdoc />
public int? Height { get; }
/// <inheritdoc />
public int? Width { get; }
internal Attachment(ulong id, string filename, string url, string proxyUrl, int size, int? height, int? width)
@@ -31,6 +41,12 @@ namespace Discord
model.Width.IsSpecified ? model.Width.Value : (int?)null);
}
/// <summary>
/// Returns the filename of this attachment.
/// </summary>
/// <returns>
/// A string containing the filename of this attachment.
/// </returns>
public override string ToString() => Filename;
private string DebuggerDisplay => $"{Filename} ({Size} bytes)";
}

View File

@@ -10,11 +10,13 @@ namespace Discord.Rest
{
internal static class MessageHelper
{
/// <exception cref="InvalidOperationException">Only the author of a message may modify the message.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public static async Task<Model> ModifyAsync(IMessage msg, BaseDiscordClient client, Action<MessageProperties> func,
RequestOptions options)
{
if (msg.Author.Id != client.CurrentUser.Id)
throw new InvalidOperationException("Only the author of a message may change it.");
throw new InvalidOperationException("Only the author of a message may modify the message.");
var args = new MessageProperties();
func(args);
@@ -45,7 +47,7 @@ namespace Discord.Rest
public static async Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options);
await client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IMessage msg, IEmote emote,

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
@@ -7,27 +7,53 @@ using Model = Discord.API.Message;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based message.
/// </summary>
public abstract class RestMessage : RestEntity<ulong>, IMessage, IUpdateable
{
private long _timestampTicks;
/// <inheritdoc />
public IMessageChannel Channel { get; }
/// <summary>
/// Gets the Author of the message.
/// </summary>
public IUser Author { get; }
/// <inheritdoc />
public MessageSource Source { get; }
/// <inheritdoc />
public string Content { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public virtual bool IsTTS => false;
/// <inheritdoc />
public virtual bool IsPinned => false;
/// <inheritdoc />
public virtual DateTimeOffset? EditedTimestamp => null;
/// <summary>
/// Gets a collection of the <see cref="Attachment"/>'s on the message.
/// </summary>
public virtual IReadOnlyCollection<Attachment> Attachments => ImmutableArray.Create<Attachment>();
/// <summary>
/// Gets a collection of the <see cref="Embed"/>'s on the message.
/// </summary>
public virtual IReadOnlyCollection<Embed> Embeds => ImmutableArray.Create<Embed>();
/// <inheritdoc />
public virtual IReadOnlyCollection<ulong> MentionedChannelIds => ImmutableArray.Create<ulong>();
/// <inheritdoc />
public virtual IReadOnlyCollection<ulong> MentionedRoleIds => ImmutableArray.Create<ulong>();
/// <summary>
/// Gets a collection of the mentioned users in the message.
/// </summary>
public virtual IReadOnlyCollection<RestUser> MentionedUsers => ImmutableArray.Create<RestUser>();
/// <inheritdoc />
public virtual IReadOnlyCollection<ITag> Tags => ImmutableArray.Create<ITag>();
/// <inheritdoc />
public DateTimeOffset Timestamp => DateTimeUtils.FromTicks(_timestampTicks);
internal RestMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author, MessageSource source)
@@ -53,20 +79,32 @@ namespace Discord.Rest
Content = model.Content.Value;
}
/// <inheritdoc />
public async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelMessageAsync(Channel.Id, Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> MessageHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets the <see cref="Content"/> of the message.
/// </summary>
/// <returns>
/// A string that is the <see cref="Content"/> of the message.
/// </returns>
public override string ToString() => Content;
/// <inheritdoc />
MessageType IMessage.Type => MessageType.Default;
IUser IMessage.Author => Author;
/// <inheritdoc />
IReadOnlyCollection<IAttachment> IMessage.Attachments => Attachments;
/// <inheritdoc />
IReadOnlyCollection<IEmbed> IMessage.Embeds => Embeds;
/// <inheritdoc />
IReadOnlyCollection<ulong> IMessage.MentionedUserIds => MentionedUsers.Select(x => x.Id).ToImmutableArray();
}
}

View File

@@ -1,11 +1,21 @@
using Model = Discord.API.Reaction;
using Model = Discord.API.Reaction;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST reaction object.
/// </summary>
public class RestReaction : IReaction
{
/// <inheritdoc />
public IEmote Emote { get; }
/// <summary>
/// Gets the number of reactions added.
/// </summary>
public int Count { get; }
/// <summary>
/// Gets whether the reactions is added by the user.
/// </summary>
public bool Me { get; }
internal RestReaction(IEmote emote, int count, bool me)

View File

@@ -1,11 +1,15 @@
using System.Diagnostics;
using System.Diagnostics;
using Model = Discord.API.Message;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based system message.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestSystemMessage : RestMessage, ISystemMessage
{
/// <inheritdoc />
public MessageType Type { get; private set; }
internal RestSystemMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author)

View File

@@ -8,6 +8,9 @@ using Model = Discord.API.Message;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based message sent by a user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestUserMessage : RestMessage, IUserMessage
{
@@ -17,23 +20,33 @@ namespace Discord.Rest
private ImmutableArray<Embed> _embeds;
private ImmutableArray<ITag> _tags;
private ImmutableArray<RestReaction> _reactions;
/// <inheritdoc />
public override bool IsTTS => _isTTS;
/// <inheritdoc />
public override bool IsPinned => _isPinned;
/// <inheritdoc />
public override DateTimeOffset? EditedTimestamp => DateTimeUtils.FromTicks(_editedTimestampTicks);
/// <inheritdoc />
public override IReadOnlyCollection<Attachment> Attachments => _attachments;
/// <inheritdoc />
public override IReadOnlyCollection<Embed> Embeds => _embeds;
/// <inheritdoc />
public override IReadOnlyCollection<ulong> MentionedChannelIds => MessageHelper.FilterTagsByKey(TagType.ChannelMention, _tags);
/// <inheritdoc />
public override IReadOnlyCollection<ulong> MentionedRoleIds => MessageHelper.FilterTagsByKey(TagType.RoleMention, _tags);
/// <inheritdoc />
public override IReadOnlyCollection<RestUser> MentionedUsers => MessageHelper.FilterTagsByValue<RestUser>(TagType.UserMention, _tags);
/// <inheritdoc />
public override IReadOnlyCollection<ITag> Tags => _tags;
/// <inheritdoc />
public IReadOnlyDictionary<IEmote, ReactionMetadata> Reactions => _reactions.ToDictionary(x => x.Emote, x => new ReactionMetadata { ReactionCount = x.Count, IsMe = x.Me });
internal RestUserMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author, MessageSource source)
: base(discord, id, channel, author, source)
{
}
internal static new RestUserMessage Create(BaseDiscordClient discord, IMessageChannel channel, IUser author, Model model)
internal new static RestUserMessage Create(BaseDiscordClient discord, IMessageChannel channel, IUser author, Model model)
{
var entity = new RestUserMessage(discord, model.Id, channel, author, MessageHelper.GetSource(model));
entity.Update(model);
@@ -124,30 +137,37 @@ namespace Discord.Rest
}
}
/// <inheritdoc />
public async Task ModifyAsync(Action<MessageProperties> func, RequestOptions options = null)
{
var model = await MessageHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task AddReactionAsync(IEmote emote, RequestOptions options = null)
=> MessageHelper.AddReactionAsync(this, emote, Discord, options);
/// <inheritdoc />
public Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions options = null)
=> MessageHelper.RemoveReactionAsync(this, user, emote, Discord, options);
/// <inheritdoc />
public Task RemoveAllReactionsAsync(RequestOptions options = null)
=> MessageHelper.RemoveAllReactionsAsync(this, Discord, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IEmote emote, int limit, RequestOptions options = null)
=> MessageHelper.GetReactionUsersAsync(this, emote, limit, Discord, options);
/// <inheritdoc />
public Task PinAsync(RequestOptions options = null)
=> MessageHelper.PinAsync(this, Discord, options);
/// <inheritdoc />
public Task UnpinAsync(RequestOptions options = null)
=> MessageHelper.UnpinAsync(this, Discord, options);
public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name,
TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name)
=> MentionUtils.Resolve(this, startIndex, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);
/// <inheritdoc />
public string Resolve(TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name,
TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name)
=> MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);

View File

@@ -1,23 +1,33 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.Application;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based entity that contains information about a Discord application created via the developer portal.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestApplication : RestEntity<ulong>, IApplication
{
protected string _iconId;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public string Description { get; private set; }
/// <inheritdoc />
public string[] RPCOrigins { get; private set; }
/// <inheritdoc />
public ulong Flags { get; private set; }
/// <inheritdoc />
public IUser Owner { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public string IconUrl => CDN.GetApplicationIconUrl(Id, _iconId);
internal RestApplication(BaseDiscordClient discord, ulong id)
@@ -43,6 +53,7 @@ namespace Discord.Rest
Owner = RestUser.Create(Discord, model.Owner.Value);
}
/// <exception cref="InvalidOperationException">Unable to update this object from a different application token.</exception>
public async Task UpdateAsync()
{
var response = await Discord.ApiClient.GetMyApplicationAsync().ConfigureAwait(false);
@@ -51,6 +62,12 @@ namespace Discord.Rest
Update(response);
}
/// <summary>
/// Gets the name of the application.
/// </summary>
/// <returns>
/// Name of the application.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id})";
}

View File

@@ -1,24 +1,39 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.Role;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based role.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestRole : RestEntity<ulong>, IRole
{
internal IGuild Guild { get; }
/// <inheritdoc />
public Color Color { get; private set; }
/// <inheritdoc />
public bool IsHoisted { get; private set; }
/// <inheritdoc />
public bool IsManaged { get; private set; }
/// <inheritdoc />
public bool IsMentionable { get; private set; }
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public GuildPermissions Permissions { get; private set; }
/// <inheritdoc />
public int Position { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <summary>
/// Gets if this role is the @everyone role of the guild or not.
/// </summary>
public bool IsEveryone => Id == Guild.Id;
/// <inheritdoc />
public string Mention => IsEveryone ? "@everyone" : MentionUtils.MentionRole(Id);
internal RestRole(BaseDiscordClient discord, IGuild guild, ulong id)
@@ -43,20 +58,30 @@ namespace Discord.Rest
Permissions = new GuildPermissions(model.Permissions);
}
/// <inheritdoc />
public async Task ModifyAsync(Action<RoleProperties> func, RequestOptions options = null)
{
var model = await RoleHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> RoleHelper.DeleteAsync(this, Discord, options);
/// <inheritdoc />
public int CompareTo(IRole role) => RoleUtils.Compare(this, role);
/// <summary>
/// Gets the name of the role.
/// </summary>
/// <returns>
/// A string that is the name of the role.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id})";
//IRole
/// <inheritdoc />
IGuild IRole.Guild
{
get

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Model = Discord.API.Connection;
@@ -8,10 +8,15 @@ namespace Discord
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestConnection : IConnection
{
/// <inheritdoc />
public string Id { get; }
/// <inheritdoc />
public string Type { get; }
/// <inheritdoc />
public string Name { get; }
/// <inheritdoc />
public bool IsRevoked { get; }
/// <inheritdoc />
public IReadOnlyCollection<ulong> IntegrationIds { get; }
internal RestConnection(string id, string type, string name, bool isRevoked, IReadOnlyCollection<ulong> integrationIds)
@@ -28,6 +33,12 @@ namespace Discord
return new RestConnection(model.Id, model.Type, model.Name, model.Revoked, model.Integrations.ToImmutableArray());
}
/// <summary>
/// Gets the name of the connection.
/// </summary>
/// <returns>
/// Name of the connection.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}, {Type}{(IsRevoked ? ", Revoked" : "")})";
}

View File

@@ -1,8 +1,11 @@
using System.Diagnostics;
using System.Diagnostics;
using Model = Discord.API.User;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based group user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestGroupUser : RestUser, IGroupUser
{
@@ -16,14 +19,21 @@ namespace Discord.Rest
entity.Update(model);
return entity;
}
//IVoiceState
/// <inheritdoc />
bool IVoiceState.IsDeafened => false;
/// <inheritdoc />
bool IVoiceState.IsMuted => false;
/// <inheritdoc />
bool IVoiceState.IsSelfDeafened => false;
/// <inheritdoc />
bool IVoiceState.IsSelfMuted => false;
/// <inheritdoc />
bool IVoiceState.IsSuppressed => false;
/// <inheritdoc />
IVoiceChannel IVoiceState.VoiceChannel => null;
/// <inheritdoc />
string IVoiceState.VoiceSessionId => null;
}
}

View File

@@ -8,18 +8,28 @@ using Model = Discord.API.GuildMember;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based guild user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestGuildUser : RestUser, IGuildUser
{
private long? _joinedAtTicks;
private ImmutableArray<ulong> _roleIds;
/// <inheritdoc />
public string Nickname { get; private set; }
internal IGuild Guild { get; private set; }
/// <inheritdoc />
public bool IsDeafened { get; private set; }
/// <inheritdoc />
public bool IsMuted { get; private set; }
/// <inheritdoc />
public ulong GuildId => Guild.Id;
/// <inheritdoc />
/// <exception cref="InvalidOperationException" accessor="get">Resolving permissions requires the parent guild to be downloaded.</exception>
public GuildPermissions GuildPermissions
{
get
@@ -29,8 +39,10 @@ namespace Discord.Rest
return new GuildPermissions(Permissions.ResolveGuild(Guild, this));
}
}
/// <inheritdoc />
public IReadOnlyCollection<ulong> RoleIds => _roleIds;
/// <inheritdoc />
public DateTimeOffset? JoinedAt => DateTimeUtils.FromTicks(_joinedAtTicks);
internal RestGuildUser(BaseDiscordClient discord, IGuild guild, ulong id)
@@ -67,11 +79,13 @@ namespace Discord.Rest
_roleIds = roles.ToImmutable();
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetGuildMemberAsync(GuildId, Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public async Task ModifyAsync(Action<GuildUserProperties> func, RequestOptions options = null)
{
var args = await UserHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
@@ -86,6 +100,7 @@ namespace Discord.Rest
else if (args.RoleIds.IsSpecified)
UpdateRoles(args.RoleIds.Value.ToArray());
}
/// <inheritdoc />
public Task KickAsync(string reason = null, RequestOptions options = null)
=> UserHelper.KickAsync(this, Discord, reason, options);
/// <inheritdoc />
@@ -101,6 +116,8 @@ namespace Discord.Rest
public Task RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null)
=> UserHelper.RemoveRolesAsync(this, Discord, roles, options);
/// <inheritdoc />
/// <exception cref="InvalidOperationException">Resolving permissions requires the parent guild to be downloaded.</exception>
public ChannelPermissions GetPermissions(IGuildChannel channel)
{
var guildPerms = GuildPermissions;
@@ -108,6 +125,7 @@ namespace Discord.Rest
}
//IGuildUser
/// <inheritdoc />
IGuild IGuildUser.Guild
{
get
@@ -119,10 +137,15 @@ namespace Discord.Rest
}
//IVoiceState
/// <inheritdoc />
bool IVoiceState.IsSelfDeafened => false;
/// <inheritdoc />
bool IVoiceState.IsSelfMuted => false;
/// <inheritdoc />
bool IVoiceState.IsSuppressed => false;
/// <inheritdoc />
IVoiceChannel IVoiceState.VoiceChannel => null;
/// <inheritdoc />
string IVoiceState.VoiceSessionId => null;
}
}

View File

@@ -1,15 +1,21 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.User;
namespace Discord.Rest
{
/// <summary>
/// Represents the logged-in REST-based user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestSelfUser : RestUser, ISelfUser
{
/// <inheritdoc />
public string Email { get; private set; }
/// <inheritdoc />
public bool IsVerified { get; private set; }
/// <inheritdoc />
public bool IsMfaEnabled { get; private set; }
internal RestSelfUser(BaseDiscordClient discord, ulong id)
@@ -22,6 +28,7 @@ namespace Discord.Rest
entity.Update(model);
return entity;
}
/// <inheritdoc />
internal override void Update(Model model)
{
base.Update(model);
@@ -34,6 +41,8 @@ namespace Discord.Rest
IsMfaEnabled = model.MfaEnabled.Value;
}
/// <inheritdoc />
/// <exception cref="InvalidOperationException">Unable to update this object using a different token.</exception>
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetMyUserAsync(options).ConfigureAwait(false);
@@ -42,6 +51,8 @@ namespace Discord.Rest
Update(model);
}
/// <inheritdoc />
/// <exception cref="InvalidOperationException">Unable to modify this object using a different token.</exception>
public async Task ModifyAsync(Action<SelfUserProperties> func, RequestOptions options = null)
{
if (Id != Discord.CurrentUser.Id)

View File

@@ -5,19 +5,32 @@ using Model = Discord.API.User;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestUser : RestEntity<ulong>, IUser, IUpdateable
{
/// <inheritdoc />
public bool IsBot { get; private set; }
/// <inheritdoc />
public string Username { get; private set; }
/// <inheritdoc />
public ushort DiscriminatorValue { get; private set; }
/// <inheritdoc />
public string AvatarId { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public string Discriminator => DiscriminatorValue.ToString("D4");
/// <inheritdoc />
public string Mention => MentionUtils.MentionUser(Id);
/// <inheritdoc />
public virtual IActivity Activity => null;
/// <inheritdoc />
public virtual UserStatus Status => UserStatus.Offline;
/// <inheritdoc />
public virtual bool IsWebhook => false;
internal RestUser(BaseDiscordClient discord, ulong id)
@@ -48,26 +61,43 @@ namespace Discord.Rest
Username = model.Username.Value;
}
/// <inheritdoc />
public virtual async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetUserAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <summary>
/// Returns a direct message channel to this user, or create one if it does not already exist.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a rest DM channel where the user is the recipient.
/// </returns>
public Task<RestDMChannel> GetOrCreateDMChannelAsync(RequestOptions options = null)
=> UserHelper.CreateDMChannelAsync(this, Discord, options);
/// <inheritdoc />
public string GetAvatarUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128)
=> CDN.GetUserAvatarUrl(Id, AvatarId, size, format);
/// <inheritdoc />
public string GetDefaultAvatarUrl()
=> CDN.GetDefaultUserAvatarUrl(DiscriminatorValue);
/// <summary>
/// Gets the Username#Discriminator of the user.
/// </summary>
/// <returns>
/// A string that resolves to Username#Discriminator of the user.
/// </returns>
public override string ToString() => $"{Username}#{Discriminator}";
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")})";
//IUser
/// <inheritdoc />
async Task<IDMChannel> IUser.GetOrCreateDMChannelAsync(RequestOptions options)
=> await GetOrCreateDMChannelAsync(options);
=> await GetOrCreateDMChannelAsync(options).ConfigureAwait(false);
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
@@ -10,10 +10,13 @@ namespace Discord.Rest
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestWebhookUser : RestUser, IWebhookUser
{
/// <inheritdoc />
public ulong WebhookId { get; }
internal IGuild Guild { get; }
/// <inheritdoc />
public override bool IsWebhook => true;
/// <inheritdoc />
public ulong GuildId => Guild.Id;
internal RestWebhookUser(BaseDiscordClient discord, IGuild guild, ulong id, ulong webhookId)
@@ -28,8 +31,9 @@ namespace Discord.Rest
entity.Update(model);
return entity;
}
//IGuildUser
/// <inheritdoc />
IGuild IGuildUser.Guild
{
get
@@ -39,45 +43,55 @@ namespace Discord.Rest
throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
}
}
/// <inheritdoc />
IReadOnlyCollection<ulong> IGuildUser.RoleIds => ImmutableArray.Create<ulong>();
/// <inheritdoc />
DateTimeOffset? IGuildUser.JoinedAt => null;
/// <inheritdoc />
string IGuildUser.Nickname => null;
/// <inheritdoc />
GuildPermissions IGuildUser.GuildPermissions => GuildPermissions.Webhook;
/// <inheritdoc />
ChannelPermissions IGuildUser.GetPermissions(IGuildChannel channel) => Permissions.ToChannelPerms(channel, GuildPermissions.Webhook.RawValue);
Task IGuildUser.KickAsync(string reason, RequestOptions options)
{
/// <inheritdoc />
Task IGuildUser.KickAsync(string reason, RequestOptions options) =>
throw new NotSupportedException("Webhook users cannot be kicked.");
}
Task IGuildUser.ModifyAsync(Action<GuildUserProperties> func, RequestOptions options)
{
throw new NotSupportedException("Webhook users cannot be modified.");
}
Task IGuildUser.AddRoleAsync(IRole role, RequestOptions options)
{
/// <inheritdoc />
Task IGuildUser.ModifyAsync(Action<GuildUserProperties> func, RequestOptions options) =>
throw new NotSupportedException("Webhook users cannot be modified.");
/// <inheritdoc />
Task IGuildUser.AddRoleAsync(IRole role, RequestOptions options) =>
throw new NotSupportedException("Roles are not supported on webhook users.");
}
Task IGuildUser.AddRolesAsync(IEnumerable<IRole> roles, RequestOptions options)
{
/// <inheritdoc />
Task IGuildUser.AddRolesAsync(IEnumerable<IRole> roles, RequestOptions options) =>
throw new NotSupportedException("Roles are not supported on webhook users.");
}
Task IGuildUser.RemoveRoleAsync(IRole role, RequestOptions options)
{
/// <inheritdoc />
Task IGuildUser.RemoveRoleAsync(IRole role, RequestOptions options) =>
throw new NotSupportedException("Roles are not supported on webhook users.");
}
Task IGuildUser.RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options)
{
/// <inheritdoc />
Task IGuildUser.RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options) =>
throw new NotSupportedException("Roles are not supported on webhook users.");
}
//IVoiceState
/// <inheritdoc />
bool IVoiceState.IsDeafened => false;
/// <inheritdoc />
bool IVoiceState.IsMuted => false;
/// <inheritdoc />
bool IVoiceState.IsSelfDeafened => false;
/// <inheritdoc />
bool IVoiceState.IsSelfMuted => false;
/// <inheritdoc />
bool IVoiceState.IsSuppressed => false;
/// <inheritdoc />
IVoiceChannel IVoiceState.VoiceChannel => null;
/// <inheritdoc />
string IVoiceState.VoiceSessionId => null;
}
}

View File

@@ -76,13 +76,13 @@ namespace Discord.Rest
public static async Task AddRolesAsync(IGuildUser user, BaseDiscordClient client, IEnumerable<IRole> roles, RequestOptions options)
{
foreach (var role in roles)
await client.ApiClient.AddRoleAsync(user.Guild.Id, user.Id, role.Id, options);
await client.ApiClient.AddRoleAsync(user.Guild.Id, user.Id, role.Id, options).ConfigureAwait(false);
}
public static async Task RemoveRolesAsync(IGuildUser user, BaseDiscordClient client, IEnumerable<IRole> roles, RequestOptions options)
{
foreach (var role in roles)
await client.ApiClient.RemoveRoleAsync(user.Guild.Id, user.Id, role.Id, options);
await client.ApiClient.RemoveRoleAsync(user.Guild.Id, user.Id, role.Id, options).ConfigureAwait(false);
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.Webhook;
@@ -11,14 +11,21 @@ namespace Discord.Rest
internal IGuild Guild { get; private set; }
internal ITextChannel Channel { get; private set; }
/// <inheritdoc />
public ulong ChannelId { get; }
/// <inheritdoc />
public string Token { get; }
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public string AvatarId { get; private set; }
/// <inheritdoc />
public ulong? GuildId { get; private set; }
/// <inheritdoc />
public IUser Creator { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
internal RestWebhook(BaseDiscordClient discord, IGuild guild, ulong id, string token, ulong channelId)
@@ -59,12 +66,14 @@ namespace Discord.Rest
Name = model.Name.Value;
}
/// <inheritdoc />
public async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetWebhookAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public string GetAvatarUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128)
=> CDN.GetUserAvatarUrl(Id, AvatarId, size, format);
@@ -74,6 +83,7 @@ namespace Discord.Rest
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> WebhookHelper.DeleteAsync(this, Discord, options);
@@ -81,10 +91,13 @@ namespace Discord.Rest
private string DebuggerDisplay => $"Webhook: {Name} ({Id})";
//IWebhook
/// <inheritdoc />
IGuild IWebhook.Guild
=> Guild ?? throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
/// <inheritdoc />
ITextChannel IWebhook.Channel
=> Channel ?? throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
/// <inheritdoc />
Task IWebhook.ModifyAsync(Action<WebhookProperties> func, RequestOptions options)
=> ModifyAsync(func, options);
}