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:
@@ -420,7 +420,6 @@ namespace Discord.Audio
|
||||
}
|
||||
private async Task RunKeepaliveAsync(int intervalMillis, CancellationToken cancelToken)
|
||||
{
|
||||
var packet = new byte[8];
|
||||
try
|
||||
{
|
||||
await _audioLogger.DebugAsync("Keepalive Started").ConfigureAwait(false);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -22,19 +22,22 @@ namespace Discord.Audio.Streams
|
||||
_decoder = new OpusDecoder();
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidOperationException">Header received with no payload.</exception>
|
||||
public override void WriteHeader(ushort seq, uint timestamp, bool missed)
|
||||
{
|
||||
if (_hasHeader)
|
||||
throw new InvalidOperationException("Header received with no payload");
|
||||
throw new InvalidOperationException("Header received with no payload.");
|
||||
_hasHeader = true;
|
||||
|
||||
_nextMissed = missed;
|
||||
_next.WriteHeader(seq, timestamp, missed);
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidOperationException">Received payload without an RTP header.</exception>
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
|
||||
{
|
||||
if (!_hasHeader)
|
||||
throw new InvalidOperationException("Received payload without an RTP header");
|
||||
throw new InvalidOperationException("Received payload without an RTP header.");
|
||||
_hasHeader = false;
|
||||
|
||||
if (!_nextMissed)
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace Discord.Audio.Streams
|
||||
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
|
||||
{
|
||||
//Assume threadsafe
|
||||
//Assume thread-safe
|
||||
while (count > 0)
|
||||
{
|
||||
if (_partialFramePos == 0 && count >= OpusConverter.FrameBytes)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Threading;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Discord.Audio.Streams
|
||||
@@ -20,6 +21,8 @@ namespace Discord.Audio.Streams
|
||||
_nonce = new byte[24];
|
||||
}
|
||||
|
||||
/// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception>
|
||||
/// <exception cref="ObjectDisposedException">The associated <see cref="T:System.Threading.CancellationTokenSource" /> has been disposed.</exception>
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
|
||||
{
|
||||
cancelToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -4,7 +4,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace Discord.Audio.Streams
|
||||
{
|
||||
///<summary> Decrypts an RTP frame using libsodium </summary>
|
||||
/// <summary>
|
||||
/// Decrypts an RTP frame using libsodium.
|
||||
/// </summary>
|
||||
public class SodiumDecryptStream : AudioOutStream
|
||||
{
|
||||
private readonly AudioClient _client;
|
||||
|
||||
@@ -4,7 +4,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace Discord.Audio.Streams
|
||||
{
|
||||
///<summary> Encrypts an RTP frame using libsodium </summary>
|
||||
/// <summary>
|
||||
/// Encrypts an RTP frame using libsodium.
|
||||
/// </summary>
|
||||
public class SodiumEncryptStream : AudioOutStream
|
||||
{
|
||||
private readonly AudioClient _client;
|
||||
@@ -20,21 +22,25 @@ namespace Discord.Audio.Streams
|
||||
_client = (AudioClient)client;
|
||||
_nonce = new byte[24];
|
||||
}
|
||||
|
||||
|
||||
/// <exception cref="InvalidOperationException">Header received with no payload.</exception>
|
||||
public override void WriteHeader(ushort seq, uint timestamp, bool missed)
|
||||
{
|
||||
if (_hasHeader)
|
||||
throw new InvalidOperationException("Header received with no payload");
|
||||
throw new InvalidOperationException("Header received with no payload.");
|
||||
|
||||
_nextSeq = seq;
|
||||
_nextTimestamp = timestamp;
|
||||
_hasHeader = true;
|
||||
}
|
||||
/// <exception cref="InvalidOperationException">Received payload without an RTP header.</exception>
|
||||
/// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception>
|
||||
/// <exception cref="ObjectDisposedException">The associated <see cref="T:System.Threading.CancellationTokenSource" /> has been disposed.</exception>
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
|
||||
{
|
||||
cancelToken.ThrowIfCancellationRequested();
|
||||
if (!_hasHeader)
|
||||
throw new InvalidOperationException("Received payload without an RTP header");
|
||||
throw new InvalidOperationException("Received payload without an RTP header.");
|
||||
_hasHeader = false;
|
||||
|
||||
if (_client.SecretKey == null)
|
||||
|
||||
@@ -7,6 +7,17 @@ namespace Discord.WebSocket
|
||||
{
|
||||
//Channels
|
||||
/// <summary> Fired when a channel is created. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a generic channel has been created. The event handler must return a
|
||||
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The newly created channel is passed into the event handler parameter. The given channel type may
|
||||
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
|
||||
/// see the derived classes of <see cref="SocketChannel"/> for more details.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<SocketChannel, Task> ChannelCreated
|
||||
{
|
||||
add { _channelCreatedEvent.Add(value); }
|
||||
@@ -14,12 +25,35 @@ namespace Discord.WebSocket
|
||||
}
|
||||
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelCreatedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
|
||||
/// <summary> Fired when a channel is destroyed. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a generic channel has been destroyed. The event handler must return a
|
||||
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The destroyed channel is passed into the event handler parameter. The given channel type may
|
||||
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
|
||||
/// see the derived classes of <see cref="SocketChannel"/> for more details.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<SocketChannel, Task> ChannelDestroyed {
|
||||
add { _channelDestroyedEvent.Add(value); }
|
||||
remove { _channelDestroyedEvent.Remove(value); }
|
||||
}
|
||||
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelDestroyedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
|
||||
/// <summary> Fired when a channel is updated. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a generic channel has been destroyed. The event handler must return a
|
||||
/// <see cref="Task"/> and accept 2 <see cref="SocketChannel"/> as its parameters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The original (prior to update) channel is passed into the first <see cref="SocketChannel"/>, while
|
||||
/// the updated channel is passed into the second. The given channel type may include, but not limited
|
||||
/// to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); see the derived classes of
|
||||
/// <see cref="SocketChannel"/> for more details.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated {
|
||||
add { _channelUpdatedEvent.Add(value); }
|
||||
remove { _channelUpdatedEvent.Remove(value); }
|
||||
@@ -28,18 +62,72 @@ namespace Discord.WebSocket
|
||||
|
||||
//Messages
|
||||
/// <summary> Fired when a message is received. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a message is received. The event handler must return a
|
||||
/// <see cref="Task"/> and accept a <see cref="SocketMessage"/> as its parameter.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The message that is sent to the client is passed into the event handler parameter as
|
||||
/// <see cref="SocketMessage"/>. This message may be a system message (i.e.
|
||||
/// <see cref="SocketSystemMessage"/>) or a user message (i.e. <see cref="SocketUserMessage"/>. See the
|
||||
/// derived classes of <see cref="SocketMessage"/> for more details.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<SocketMessage, Task> MessageReceived {
|
||||
add { _messageReceivedEvent.Add(value); }
|
||||
remove { _messageReceivedEvent.Remove(value); }
|
||||
}
|
||||
internal readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>();
|
||||
/// <summary> Fired when a message is deleted. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a message is deleted. The event handler must return a
|
||||
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/> and
|
||||
/// <see cref="ISocketMessageChannel"/> as its parameters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <note type="important">
|
||||
/// It is not possible to retrieve the message via
|
||||
/// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord
|
||||
/// after the message has been deleted.
|
||||
/// </note>
|
||||
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
|
||||
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event
|
||||
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
|
||||
/// <see cref="ulong"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The source channel of the removed message will be passed into the
|
||||
/// <see cref="ISocketMessageChannel"/> parameter.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task> MessageDeleted {
|
||||
add { _messageDeletedEvent.Add(value); }
|
||||
remove { _messageDeletedEvent.Remove(value); }
|
||||
}
|
||||
internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>> _messageDeletedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>>();
|
||||
/// <summary> Fired when a message is updated. </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This event is fired when a message is updated. The event handler must return a
|
||||
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, <see cref="SocketMessage"/>,
|
||||
/// and <see cref="ISocketMessageChannel"/> as its parameters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
|
||||
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event
|
||||
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
|
||||
/// <see cref="ulong"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The updated message will be passed into the <see cref="SocketMessage"/> parameter.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The source channel of the updated message will be passed into the
|
||||
/// <see cref="ISocketMessageChannel"/> parameter.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public event Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task> MessageUpdated {
|
||||
add { _messageUpdatedEvent.Add(value); }
|
||||
remove { _messageUpdatedEvent.Remove(value); }
|
||||
|
||||
@@ -6,88 +6,288 @@ using Discord.Rest;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the base of a WebSocket-based Discord client.
|
||||
/// </summary>
|
||||
public abstract partial class BaseSocketClient : BaseDiscordClient, IDiscordClient
|
||||
{
|
||||
protected readonly DiscordSocketConfig _baseconfig;
|
||||
protected readonly DiscordSocketConfig BaseConfig;
|
||||
|
||||
/// <summary> Gets the estimated round-trip latency, in milliseconds, to the gateway server. </summary>
|
||||
/// <summary>
|
||||
/// Gets the estimated round-trip latency, in milliseconds, to the gateway server.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An <see cref="int"/> that represents the round-trip latency to the WebSocket server. Please
|
||||
/// note that this value does not represent a "true" latency for operations such as sending a message.
|
||||
/// </returns>
|
||||
public abstract int Latency { get; protected set; }
|
||||
public abstract UserStatus Status { get; protected set; }
|
||||
/// <summary>
|
||||
/// Gets the status for the logged-in user.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A status object that represents the user's online presence status.
|
||||
/// </returns>
|
||||
public abstract UserStatus Status { get; protected set; }
|
||||
/// <summary>
|
||||
/// Gets the activity for the logged-in user.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An activity object that represents the user's current activity.
|
||||
/// </returns>
|
||||
public abstract IActivity Activity { get; protected set; }
|
||||
|
||||
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current logged-in user.
|
||||
/// </summary>
|
||||
public new SocketSelfUser CurrentUser { get => base.CurrentUser as SocketSelfUser; protected set => base.CurrentUser = value; }
|
||||
/// <summary>
|
||||
/// Gets a collection of guilds that the user is currently in.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of guilds that the current user is in.
|
||||
/// </returns>
|
||||
public abstract IReadOnlyCollection<SocketGuild> Guilds { get; }
|
||||
/// <summary>
|
||||
/// Gets a collection of private channels opened in this session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method will retrieve all private channels (including direct-message, group channel and such) that
|
||||
/// are currently opened in this session.
|
||||
/// <note type="warning">
|
||||
/// This method will not return previously opened private channels outside of the current session! If
|
||||
/// you have just started the client, this may return an empty collection.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A read-only collection of private channels that the user currently partakes in.
|
||||
/// </returns>
|
||||
public abstract IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels { get; }
|
||||
/// <summary>
|
||||
/// Gets a collection of available voice regions.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of voice regions that the user has access to.
|
||||
/// </returns>
|
||||
public abstract IReadOnlyCollection<RestVoiceRegion> VoiceRegions { get; }
|
||||
|
||||
internal BaseSocketClient(DiscordSocketConfig config, DiscordRestApiClient client)
|
||||
: base(config, client) => _baseconfig = config;
|
||||
: base(config, client) => BaseConfig = config;
|
||||
private static DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
|
||||
=> new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent);
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets a Discord application information for the logged-in user.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method reflects your application information you submitted when creating a Discord application via
|
||||
/// the Developer Portal.
|
||||
/// </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 the application
|
||||
/// information.
|
||||
/// </returns>
|
||||
public abstract Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets a generic user.
|
||||
/// </summary>
|
||||
/// <param name="id">The user snowflake ID.</param>
|
||||
/// <remarks>
|
||||
/// This method gets the user present in the WebSocket cache with the given condition.
|
||||
/// <note type="warning">
|
||||
/// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large
|
||||
/// guilds (i.e. guild with 100+ members) actively. To download users on startup, consider enabling
|
||||
/// <see cref="DiscordSocketConfig.AlwaysDownloadUsers"/>.
|
||||
/// </note>
|
||||
/// <note>
|
||||
/// This method does not attempt to fetch users that the logged-in user does not have access to (i.e.
|
||||
/// users who don't share mutual guild(s) with the current user).
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A generic WebSocket-based user; <c>null</c> when the user cannot be found.
|
||||
/// </returns>
|
||||
public abstract SocketUser GetUser(ulong id);
|
||||
/// <inheritdoc />
|
||||
|
||||
/// <summary>
|
||||
/// Gets a user.
|
||||
/// </summary>
|
||||
/// <param name="username">The name of the user.</param>
|
||||
/// <param name="discriminator">The discriminator value of the user.</param>
|
||||
/// <remarks>
|
||||
/// This method gets the user present in the WebSocket cache with the given condition.
|
||||
/// <note type="warning">
|
||||
/// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large
|
||||
/// guilds (i.e. guild with 100+ members) actively. To download users on startup, consider enabling
|
||||
/// <see cref="DiscordSocketConfig.AlwaysDownloadUsers"/>.
|
||||
/// </note>
|
||||
/// <note>
|
||||
/// This method does not attempt to fetch users that the logged-in user does not have access to (i.e.
|
||||
/// users who don't share mutual guild(s) with the current user).
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A generic WebSocket-based user; <c>null</c> when the user cannot be found.
|
||||
/// </returns>
|
||||
public abstract SocketUser GetUser(string username, string discriminator);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets a channel.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier of the channel (e.g. `381889909113225237`).</param>
|
||||
/// <returns>
|
||||
/// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier;
|
||||
/// <c>null</c> when the channel cannot be found.
|
||||
/// </returns>
|
||||
public abstract SocketChannel GetChannel(ulong id);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets a guild.
|
||||
/// </summary>
|
||||
/// <param name="id">The guild snowflake identifier.</param>
|
||||
/// <returns>
|
||||
/// A WebSocket-based guild associated with the snowflake identifier; <c>null</c> when the guild cannot be
|
||||
/// found.
|
||||
/// </returns>
|
||||
public abstract SocketGuild GetGuild(ulong id);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets a voice region.
|
||||
/// </summary>
|
||||
/// <param name="id">The identifier of the voice region (e.g. <c>eu-central</c> ).</param>
|
||||
/// <returns>
|
||||
/// A REST-based voice region associated with the identifier; <c>null</c> if the voice region is not
|
||||
/// found.
|
||||
/// </returns>
|
||||
public abstract RestVoiceRegion GetVoiceRegion(string id);
|
||||
/// <inheritdoc />
|
||||
public abstract Task StartAsync();
|
||||
/// <inheritdoc />
|
||||
public abstract Task StopAsync();
|
||||
/// <summary>
|
||||
/// Sets the current status of the user (e.g. Online, Do not Disturb).
|
||||
/// </summary>
|
||||
/// <param name="status">The new status to be set.</param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous set operation.
|
||||
/// </returns>
|
||||
public abstract Task SetStatusAsync(UserStatus status);
|
||||
/// <summary>
|
||||
/// Sets the game of the user.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the game.</param>
|
||||
/// <param name="streamUrl">If streaming, the URL of the stream. Must be a valid Twitch URL.</param>
|
||||
/// <param name="type">The type of the game.</param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous set operation.
|
||||
/// </returns>
|
||||
public abstract Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing);
|
||||
/// <summary>
|
||||
/// Sets the <paramref name="activity"/> of the logged-in user.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method sets the <paramref name="activity"/> of the user.
|
||||
/// <note type="note">
|
||||
/// Discord will only accept setting of name and the type of activity.
|
||||
/// </note>
|
||||
/// <note type="warning">
|
||||
/// Rich Presence cannot be set via this method or client. Rich Presence is strictly limited to RPC
|
||||
/// clients only.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <param name="activity">The activity to be set.</param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous set operation.
|
||||
/// </returns>
|
||||
public abstract Task SetActivityAsync(IActivity activity);
|
||||
public abstract Task DownloadUsersAsync(IEnumerable<IGuild> guilds);
|
||||
/// <summary>
|
||||
/// Attempts to download users into the user cache for the selected guilds.
|
||||
/// </summary>
|
||||
/// <param name="guilds">The guilds to download the members from.</param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous download operation.
|
||||
/// </returns>
|
||||
public abstract Task DownloadUsersAsync(IEnumerable<IGuild> guilds);
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Creates a guild for the logged-in user who is in less than 10 active guilds.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method creates a new guild on behalf of the logged-in user.
|
||||
/// <note type="warning">
|
||||
/// Due to Discord's limitation, this method will only work for users that are in less than 10 guilds.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <param name="name">The name of the new guild.</param>
|
||||
/// <param name="region">The voice region to create the guild with.</param>
|
||||
/// <param name="jpegIcon">The icon of the guild.</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 created guild.
|
||||
/// </returns>
|
||||
public Task<RestGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null)
|
||||
=> ClientHelper.CreateGuildAsync(this, name, region, jpegIcon, options ?? RequestOptions.Default);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets the connections that the user has set up.
|
||||
/// </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 connections.
|
||||
/// </returns>
|
||||
public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(RequestOptions options = null)
|
||||
=> ClientHelper.GetConnectionsAsync(this, options ?? RequestOptions.Default);
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets an invite.
|
||||
/// </summary>
|
||||
/// <param name="inviteId">The invitation identifier.</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 invite information.
|
||||
/// </returns>
|
||||
public Task<RestInviteMetadata> GetInviteAsync(string inviteId, RequestOptions options = null)
|
||||
=> ClientHelper.GetInviteAsync(this, inviteId, options ?? RequestOptions.Default);
|
||||
|
||||
// IDiscordClient
|
||||
/// <inheritdoc />
|
||||
async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
|
||||
=> await GetApplicationInfoAsync(options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IChannel>(GetChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
|
||||
=> await GetConnectionsAsync(options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
|
||||
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuild>(GetGuild(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
|
||||
=> await CreateGuildAsync(name, region, jpegIcon, options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(username, discriminator));
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
|
||||
=> Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ namespace Discord.WebSocket
|
||||
case SocketDMChannel dmChannel:
|
||||
_dmChannels.TryRemove(dmChannel.Recipient.Id, out _);
|
||||
break;
|
||||
case SocketGroupChannel groupChannel:
|
||||
case SocketGroupChannel _:
|
||||
_groupChannels.TryRemove(id);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using Discord.WebSocket;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace Discord.Commands
|
||||
{
|
||||
/// <summary> The sharded variant of <see cref="ICommandContext"/>, which may contain the client, user, guild, channel, and message. </summary>
|
||||
public class ShardedCommandContext : SocketCommandContext, ICommandContext
|
||||
{
|
||||
/// <summary> Gets the <see cref="DiscordShardedClient"/> that the command is executed with. </summary>
|
||||
public new DiscordShardedClient Client { get; }
|
||||
|
||||
public ShardedCommandContext(DiscordShardedClient client, SocketUserMessage msg)
|
||||
@@ -12,10 +14,12 @@ namespace Discord.Commands
|
||||
Client = client;
|
||||
}
|
||||
|
||||
/// <summary> Gets the shard ID of the command context. </summary>
|
||||
private static int GetShardId(DiscordShardedClient client, IGuild guild)
|
||||
=> guild == null ? 0 : client.GetShardIdFor(guild);
|
||||
|
||||
//ICommandContext
|
||||
/// <inheritdoc />
|
||||
IDiscordClient ICommandContext.Client => Client;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,43 @@
|
||||
using Discord.WebSocket;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace Discord.Commands
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based context of a command. This may include the client, guild, channel, user, and message.
|
||||
/// </summary>
|
||||
public class SocketCommandContext : ICommandContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="DiscordSocketClient" /> that the command is executed with.
|
||||
/// </summary>
|
||||
public DiscordSocketClient Client { get; }
|
||||
/// <summary>
|
||||
/// Gets the <see cref="SocketGuild" /> that the command is executed in.
|
||||
/// </summary>
|
||||
public SocketGuild Guild { get; }
|
||||
/// <summary>
|
||||
/// Gets the <see cref="ISocketMessageChannel" /> that the command is executed in.
|
||||
/// </summary>
|
||||
public ISocketMessageChannel Channel { get; }
|
||||
/// <summary>
|
||||
/// Gets the <see cref="SocketUser" /> who executed the command.
|
||||
/// </summary>
|
||||
public SocketUser User { get; }
|
||||
/// <summary>
|
||||
/// Gets the <see cref="SocketUserMessage" /> that the command is interpreted from.
|
||||
/// </summary>
|
||||
public SocketUserMessage Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the channel that the command is executed in is a private channel.
|
||||
/// </summary>
|
||||
public bool IsPrivate => Channel is IPrivateChannel;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="SocketCommandContext" /> class with the provided client and message.
|
||||
/// </summary>
|
||||
/// <param name="client">The underlying client.</param>
|
||||
/// <param name="msg">The underlying message.</param>
|
||||
public SocketCommandContext(DiscordSocketClient client, SocketUserMessage msg)
|
||||
{
|
||||
Client = client;
|
||||
@@ -22,10 +48,15 @@ namespace Discord.Commands
|
||||
}
|
||||
|
||||
//ICommandContext
|
||||
/// <inheritdoc/>
|
||||
IDiscordClient ICommandContext.Client => Client;
|
||||
/// <inheritdoc/>
|
||||
IGuild ICommandContext.Guild => Guild;
|
||||
/// <inheritdoc/>
|
||||
IMessageChannel ICommandContext.Channel => Channel;
|
||||
/// <inheritdoc/>
|
||||
IUser ICommandContext.User => User;
|
||||
/// <inheritdoc/>
|
||||
IUserMessage ICommandContext.Message => Message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,24 +19,29 @@ namespace Discord.WebSocket
|
||||
private DiscordSocketClient[] _shards;
|
||||
private int _totalShards;
|
||||
|
||||
/// <summary> Gets the estimated round-trip latency, in milliseconds, to the gateway server. </summary>
|
||||
/// <inheritdoc />
|
||||
public override int Latency { get => GetLatency(); protected set { } }
|
||||
/// <inheritdoc />
|
||||
public override UserStatus Status { get => _shards[0].Status; protected set { } }
|
||||
/// <inheritdoc />
|
||||
public override IActivity Activity { get => _shards[0].Activity; protected set { } }
|
||||
|
||||
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuild> Guilds => GetGuilds().ToReadOnlyCollection(GetGuildCount);
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(GetPrivateChannelCount);
|
||||
public IReadOnlyCollection<DiscordSocketClient> Shards => _shards;
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _shards[0].VoiceRegions;
|
||||
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
|
||||
public DiscordShardedClient() : this(null, new DiscordSocketConfig()) { }
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
|
||||
public DiscordShardedClient(DiscordSocketConfig config) : this(null, config, CreateApiClient(config)) { }
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
|
||||
public DiscordShardedClient(int[] ids) : this(ids, new DiscordSocketConfig()) { }
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
|
||||
public DiscordShardedClient(int[] ids, DiscordSocketConfig config) : this(ids, config, CreateApiClient(config)) { }
|
||||
private DiscordShardedClient(int[] ids, DiscordSocketConfig config, API.DiscordSocketApiClient client)
|
||||
: base(config, client)
|
||||
@@ -90,13 +95,13 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
//Assume threadsafe: already in a connection lock
|
||||
//Assume thread safe: already in a connection lock
|
||||
for (int i = 0; i < _shards.Length; i++)
|
||||
await _shards[i].LoginAsync(tokenType, token, false);
|
||||
await _shards[i].LoginAsync(tokenType, token);
|
||||
}
|
||||
internal override async Task OnLogoutAsync()
|
||||
{
|
||||
//Assume threadsafe: already in a connection lock
|
||||
//Assume thread safe: already in a connection lock
|
||||
if (_shards != null)
|
||||
{
|
||||
for (int i = 0; i < _shards.Length; i++)
|
||||
@@ -213,9 +218,11 @@ namespace Discord.WebSocket
|
||||
public override RestVoiceRegion GetVoiceRegion(string id)
|
||||
=> _shards[0].GetVoiceRegion(id);
|
||||
|
||||
/// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary>
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="ArgumentNullException"><paramref name="guilds"/> is <see langword="null"/></exception>
|
||||
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
|
||||
{
|
||||
if (guilds == null) throw new ArgumentNullException(nameof(guilds));
|
||||
for (int i = 0; i < _shards.Length; i++)
|
||||
{
|
||||
int id = _shardIds[i];
|
||||
@@ -233,11 +240,13 @@ namespace Discord.WebSocket
|
||||
return (int)Math.Round(total / (double)_shards.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task SetStatusAsync(UserStatus status)
|
||||
{
|
||||
for (int i = 0; i < _shards.Length; i++)
|
||||
await _shards[i].SetStatusAsync(status).ConfigureAwait(false);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
|
||||
{
|
||||
IActivity activity = null;
|
||||
@@ -247,6 +256,7 @@ namespace Discord.WebSocket
|
||||
activity = new Game(name, type);
|
||||
await SetActivityAsync(activity).ConfigureAwait(false);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public override async Task SetActivityAsync(IActivity activity)
|
||||
{
|
||||
for (int i = 0; i < _shards.Length; i++)
|
||||
@@ -317,34 +327,46 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//IDiscordClient
|
||||
/// <inheritdoc />
|
||||
async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
|
||||
=> await GetApplicationInfoAsync().ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IChannel>(GetChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
|
||||
=> await GetConnectionsAsync().ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
|
||||
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuild>(GetGuild(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
|
||||
/// <inheritdoc />
|
||||
async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
|
||||
=> await CreateGuildAsync(name, region, jpegIcon).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(username, discriminator));
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
|
||||
/// <inheritdoc />
|
||||
Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
|
||||
=> Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma warning disable CS1591
|
||||
using Discord.API.Gateway;
|
||||
using Discord.API.Rest;
|
||||
using Discord.Net.Queue;
|
||||
using Discord.Net.Rest;
|
||||
using Discord.Net.WebSockets;
|
||||
@@ -120,12 +119,14 @@ namespace Discord.API
|
||||
}
|
||||
finally { _stateLock.Release(); }
|
||||
}
|
||||
/// <exception cref="InvalidOperationException">The client must be logged in before connecting.</exception>
|
||||
/// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
|
||||
internal override async Task ConnectInternalAsync()
|
||||
{
|
||||
if (LoginState != LoginState.LoggedIn)
|
||||
throw new InvalidOperationException("You must log in before connecting.");
|
||||
throw new InvalidOperationException("The client must be logged in before connecting.");
|
||||
if (WebSocketClient == null)
|
||||
throw new NotSupportedException("This client is not configured with websocket support.");
|
||||
throw new NotSupportedException("This client is not configured with WebSocket support.");
|
||||
|
||||
//Re-create streams to reset the zlib state
|
||||
_compressed?.Dispose();
|
||||
@@ -176,10 +177,11 @@ namespace Discord.API
|
||||
}
|
||||
finally { _stateLock.Release(); }
|
||||
}
|
||||
/// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
|
||||
internal override async Task DisconnectInternalAsync()
|
||||
{
|
||||
if (WebSocketClient == null)
|
||||
throw new NotSupportedException("This client is not configured with websocket support.");
|
||||
throw new NotSupportedException("This client is not configured with WebSocket support.");
|
||||
|
||||
if (ConnectionState == ConnectionState.Disconnected) return;
|
||||
ConnectionState = ConnectionState.Disconnecting;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.API;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
{
|
||||
public partial class DiscordSocketClient
|
||||
{
|
||||
//General
|
||||
@@ -34,5 +35,9 @@ namespace Discord.WebSocket
|
||||
remove { _latencyUpdatedEvent.Remove(value); }
|
||||
}
|
||||
private readonly AsyncEvent<Func<int, int, Task>> _latencyUpdatedEvent = new AsyncEvent<Func<int, int, Task>>();
|
||||
|
||||
internal DiscordSocketClient(DiscordSocketConfig config, DiscordRestApiClient client) : base(config, client)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ using GameModel = Discord.API.Game;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based Discord client.
|
||||
/// </summary>
|
||||
public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
|
||||
{
|
||||
private readonly ConcurrentQueue<ulong> _largeGuilds;
|
||||
@@ -46,7 +49,9 @@ namespace Discord.WebSocket
|
||||
public ConnectionState ConnectionState => _connection.State;
|
||||
/// <inheritdoc />
|
||||
public override int Latency { get; protected set; }
|
||||
/// <inheritdoc />
|
||||
public override UserStatus Status { get; protected set; } = UserStatus.Online;
|
||||
/// <inheritdoc />
|
||||
public override IActivity Activity { get; protected set; }
|
||||
|
||||
//From DiscordSocketConfig
|
||||
@@ -58,19 +63,53 @@ namespace Discord.WebSocket
|
||||
internal WebSocketProvider WebSocketProvider { get; private set; }
|
||||
internal bool AlwaysDownloadUsers { get; private set; }
|
||||
internal int? HandlerTimeout { get; private set; }
|
||||
|
||||
|
||||
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels;
|
||||
/// <summary>
|
||||
/// Gets a collection of direct message channels opened in this session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method returns a collection of currently opened direct message channels.
|
||||
/// <note type="warning">
|
||||
/// This method will not return previously opened DM channels outside of the current session! If you
|
||||
/// have just started the client, this may return an empty collection.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// An collection of DM channels that have been opened in this session.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketDMChannel> DMChannels
|
||||
=> State.PrivateChannels.OfType<SocketDMChannel>().ToImmutableArray();
|
||||
/// <summary>
|
||||
/// Gets a collection of group channels opened in this session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method returns a collection of currently opened group channels.
|
||||
/// <note type="warning">
|
||||
/// This method will not return previously opened group channels outside of the current session! If you
|
||||
/// have just started the client, this may return an empty collection.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// An collection of group channels that have been opened in this session.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
|
||||
=> State.PrivateChannels.OfType<SocketGroupChannel>().ToImmutableArray();
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection();
|
||||
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary>
|
||||
/// Initializes a new REST/WebSocket-based Discord client.
|
||||
/// </summary>
|
||||
public DiscordSocketClient() : this(new DiscordSocketConfig()) { }
|
||||
/// <summary> Creates a new REST/WebSocket discord client. </summary>
|
||||
/// <summary>
|
||||
/// Initializes a new REST/WebSocket-based Discord client with the provided configuration.
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to be used with the client.</param>
|
||||
public DiscordSocketClient(DiscordSocketConfig config) : this(config, CreateApiClient(config), null, null) { }
|
||||
internal DiscordSocketClient(DiscordSocketConfig config, SemaphoreSlim groupLock, DiscordSocketClient parentClient) : this(config, CreateApiClient(config), groupLock, parentClient) { }
|
||||
private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client, SemaphoreSlim groupLock, DiscordSocketClient parentClient)
|
||||
@@ -128,6 +167,7 @@ namespace Discord.WebSocket
|
||||
}
|
||||
private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
|
||||
=> new API.DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost);
|
||||
/// <inheritdoc />
|
||||
internal override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
@@ -137,6 +177,7 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
internal override async Task OnLoginAsync(TokenType tokenType, string token)
|
||||
{
|
||||
if (_parentClient == null)
|
||||
@@ -147,6 +188,7 @@ namespace Discord.WebSocket
|
||||
else
|
||||
_voiceRegions = _parentClient._voiceRegions;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
internal override async Task OnLogoutAsync()
|
||||
{
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
@@ -154,9 +196,11 @@ namespace Discord.WebSocket
|
||||
_voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>();
|
||||
}
|
||||
|
||||
public override async Task StartAsync()
|
||||
/// <inheritdoc />
|
||||
public override async Task StartAsync()
|
||||
=> await _connection.StartAsync().ConfigureAwait(false);
|
||||
public override async Task StopAsync()
|
||||
/// <inheritdoc />
|
||||
public override async Task StopAsync()
|
||||
=> await _connection.StopAsync().ConfigureAwait(false);
|
||||
|
||||
private async Task OnConnectingAsync()
|
||||
@@ -277,7 +321,7 @@ namespace Discord.WebSocket
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary>
|
||||
/// <inheritdoc />
|
||||
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
|
||||
{
|
||||
if (ConnectionState == ConnectionState.Connected)
|
||||
@@ -316,6 +360,13 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <example>
|
||||
/// The following example sets the status of the current user to Do Not Disturb.
|
||||
/// <code language="cs">
|
||||
/// await client.SetStatusAsync(UserStatus.DoNotDisturb);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public override async Task SetStatusAsync(UserStatus status)
|
||||
{
|
||||
Status = status;
|
||||
@@ -325,6 +376,21 @@ namespace Discord.WebSocket
|
||||
_statusSince = null;
|
||||
await SendStatusAsync().ConfigureAwait(false);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
/// <example>
|
||||
/// <para>
|
||||
/// The following example sets the activity of the current user to the specified game name.
|
||||
/// <code language="cs">
|
||||
/// await client.SetGameAsync("A Strange Game");
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The following example sets the activity of the current user to a streaming status.
|
||||
/// <code language="cs">
|
||||
/// await client.SetGameAsync("Great Stream 10/10", "https://twitch.tv/MyAmazingStream1337", ActivityType.Streaming);
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </example>
|
||||
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(streamUrl))
|
||||
@@ -335,6 +401,7 @@ namespace Discord.WebSocket
|
||||
Activity = null;
|
||||
await SendStatusAsync().ConfigureAwait(false);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public override async Task SetActivityAsync(IActivity activity)
|
||||
{
|
||||
Activity = activity;
|
||||
@@ -352,7 +419,7 @@ namespace Discord.WebSocket
|
||||
var gameModel = new GameModel();
|
||||
// Discord only accepts rich presence over RPC, don't even bother building a payload
|
||||
if (Activity is RichGame)
|
||||
throw new NotSupportedException("Outgoing Rich Presences are not supported");
|
||||
throw new NotSupportedException("Outgoing Rich Presences are not supported via WebSocket.");
|
||||
|
||||
if (Activity != null)
|
||||
{
|
||||
@@ -1148,7 +1215,7 @@ namespace Discord.WebSocket
|
||||
|
||||
after = SocketMessage.Create(this, State, author, channel, data);
|
||||
}
|
||||
var cacheableBefore = new Cacheable<IMessage, ulong>(before, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id));
|
||||
var cacheableBefore = new Cacheable<IMessage, ulong>(before, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id).ConfigureAwait(false));
|
||||
|
||||
await TimedInvokeAsync(_messageUpdatedEvent, nameof(MessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false);
|
||||
}
|
||||
@@ -1175,7 +1242,7 @@ namespace Discord.WebSocket
|
||||
|
||||
var msg = SocketChannelHelper.RemoveMessage(channel, this, data.Id);
|
||||
bool isCached = msg != null;
|
||||
var cacheable = new Cacheable<IMessage, ulong>(msg, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id));
|
||||
var cacheable = new Cacheable<IMessage, ulong>(msg, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id).ConfigureAwait(false));
|
||||
|
||||
await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheable, channel).ConfigureAwait(false);
|
||||
}
|
||||
@@ -1195,9 +1262,9 @@ namespace Discord.WebSocket
|
||||
{
|
||||
var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
|
||||
bool isCached = cachedMsg != null;
|
||||
var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly);
|
||||
var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false);
|
||||
var reaction = SocketReaction.Create(data, channel, cachedMsg, Optional.Create(user));
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage);
|
||||
|
||||
cachedMsg?.AddReaction(reaction);
|
||||
|
||||
@@ -1219,9 +1286,9 @@ namespace Discord.WebSocket
|
||||
{
|
||||
var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
|
||||
bool isCached = cachedMsg != null;
|
||||
var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly);
|
||||
var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false);
|
||||
var reaction = SocketReaction.Create(data, channel, cachedMsg, Optional.Create(user));
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage);
|
||||
|
||||
cachedMsg?.RemoveReaction(reaction);
|
||||
|
||||
@@ -1243,7 +1310,7 @@ namespace Discord.WebSocket
|
||||
{
|
||||
var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
|
||||
bool isCached = cachedMsg != null;
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
|
||||
var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => (await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)) as IUserMessage);
|
||||
|
||||
cachedMsg?.ClearReactions();
|
||||
|
||||
@@ -1274,7 +1341,7 @@ namespace Discord.WebSocket
|
||||
{
|
||||
var msg = SocketChannelHelper.RemoveMessage(channel, this, id);
|
||||
bool isCached = msg != null;
|
||||
var cacheable = new Cacheable<IMessage, ulong>(msg, id, isCached, async () => await channel.GetMessageAsync(id));
|
||||
var cacheable = new Cacheable<IMessage, ulong>(msg, id, isCached, async () => await channel.GetMessageAsync(id).ConfigureAwait(false));
|
||||
await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheable, channel).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1634,6 +1701,7 @@ namespace Discord.WebSocket
|
||||
return guild;
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidOperationException">Unexpected channel type is created.</exception>
|
||||
internal ISocketPrivateChannel AddPrivateChannel(API.Channel model, ClientState state)
|
||||
{
|
||||
var channel = SocketChannel.CreatePrivate(this, state, model);
|
||||
@@ -1806,43 +1874,59 @@ namespace Discord.WebSocket
|
||||
internal int GetAudioId() => _nextAudioId++;
|
||||
|
||||
//IDiscordClient
|
||||
/// <inheritdoc />
|
||||
async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
|
||||
=> await GetApplicationInfoAsync().ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IChannel>(GetChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IDMChannel>> IDiscordClient.GetDMChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IDMChannel>>(DMChannels);
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IGroupChannel>> IDiscordClient.GetGroupChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGroupChannel>>(GroupChannels);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
|
||||
=> await GetConnectionsAsync().ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
|
||||
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuild>(GetGuild(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
|
||||
/// <inheritdoc />
|
||||
async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
|
||||
=> await CreateGuildAsync(name, region, jpegIcon).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(username, discriminator));
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
|
||||
/// <inheritdoc />
|
||||
Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
|
||||
=> Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task IDiscordClient.StartAsync()
|
||||
=> await StartAsync().ConfigureAwait(false);
|
||||
/// <inheritdoc />
|
||||
async Task IDiscordClient.StopAsync()
|
||||
=> await StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -1,41 +1,72 @@
|
||||
using Discord.Net.Udp;
|
||||
using Discord.Net.Udp;
|
||||
using Discord.Net.WebSockets;
|
||||
using Discord.Rest;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a configuration class for <see cref="DiscordSocketClient"/>.
|
||||
/// </summary>
|
||||
public class DiscordSocketConfig : DiscordRestConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the encoding gateway should use.
|
||||
/// </summary>
|
||||
public const string GatewayEncoding = "json";
|
||||
|
||||
/// <summary> Gets or sets the websocket host to connect to. If null, the client will use the /gateway endpoint. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the WebSocket host to connect to. If <c>null</c>, the client will use the
|
||||
/// /gateway endpoint.
|
||||
/// </summary>
|
||||
public string GatewayHost { get; set; } = null;
|
||||
|
||||
/// <summary> Gets or sets the time, in milliseconds, to wait for a connection to complete before aborting. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the time, in milliseconds, to wait for a connection to complete before aborting.
|
||||
/// </summary>
|
||||
public int ConnectionTimeout { get; set; } = 30000;
|
||||
|
||||
/// <summary> Gets or sets the id for this shard. Must be less than TotalShards. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the ID for this shard. Must be less than <see cref="TotalShards"/>.
|
||||
/// </summary>
|
||||
public int? ShardId { get; set; } = null;
|
||||
/// <summary> Gets or sets the total number of shards for this application. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of shards for this application.
|
||||
/// </summary>
|
||||
public int? TotalShards { get; set; } = null;
|
||||
|
||||
/// <summary> Gets or sets the number of messages per channel that should be kept in cache. Setting this to zero disables the message cache entirely. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the number of messages per channel that should be kept in cache. Setting this to zero
|
||||
/// disables the message cache entirely.
|
||||
/// </summary>
|
||||
public int MessageCacheSize { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// Gets or sets the max number of users a guild may have for offline users to be included in the READY packet. Max is 250.
|
||||
/// <summary>
|
||||
/// Gets or sets the max number of users a guild may have for offline users to be included in the READY
|
||||
/// packet. Max is 250.
|
||||
/// </summary>
|
||||
public int LargeThreshold { get; set; } = 250;
|
||||
|
||||
/// <summary> Gets or sets the provider used to generate new websocket connections. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the provider used to generate new WebSocket connections.
|
||||
/// </summary>
|
||||
public WebSocketProvider WebSocketProvider { get; set; }
|
||||
/// <summary> Gets or sets the provider used to generate new udp sockets. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the provider used to generate new UDP sockets.
|
||||
/// </summary>
|
||||
public UdpSocketProvider UdpSocketProvider { get; set; }
|
||||
|
||||
/// <summary> Gets or sets whether or not all users should be downloaded as guilds come available. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets whether or not all users should be downloaded as guilds come available.
|
||||
/// </summary>
|
||||
public bool AlwaysDownloadUsers { get; set; } = false;
|
||||
/// <summary> Gets or sets the timeout for event handlers, in milliseconds, after which a warning will be logged. Null disables this check. </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the timeout for event handlers, in milliseconds, after which a warning will be logged. Null
|
||||
/// disables this check.
|
||||
/// </summary>
|
||||
public int? HandlerTimeout { get; set; } = 3000;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a default configuration.
|
||||
/// </summary>
|
||||
public DiscordSocketConfig()
|
||||
{
|
||||
WebSocketProvider = DefaultWebSocketProvider.Instance;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
namespace Discord.WebSocket
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a generic WebSocket-based audio channel.
|
||||
/// </summary>
|
||||
public interface ISocketAudioChannel : IAudioChannel
|
||||
{
|
||||
}
|
||||
|
||||
@@ -5,27 +5,120 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a generic WebSocket-based channel that can send and receive messages.
|
||||
/// </summary>
|
||||
public interface ISocketMessageChannel : IMessageChannel
|
||||
{
|
||||
/// <summary> Gets all messages in this channel's cache. </summary>
|
||||
/// <summary>
|
||||
/// Gets all messages in this channel's cache.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of WebSocket-based messages.
|
||||
/// </returns>
|
||||
IReadOnlyCollection<SocketMessage> CachedMessages { get; }
|
||||
|
||||
/// <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 the cached message if one exists.
|
||||
/// </summary>
|
||||
/// <param name="id">The ID of the message.</param>
|
||||
/// <returns>
|
||||
/// Cached message object; <c>null</c> if it doesn't exist in the cache.
|
||||
/// </returns>
|
||||
SocketMessage GetCachedMessage(ulong id);
|
||||
/// <summary> Gets the last N messages from this message channel. </summary>
|
||||
/// <summary>
|
||||
/// Gets the last N messages from this message channel.
|
||||
/// </summary>
|
||||
/// <param name="limit">The number of messages to get.</param>
|
||||
/// <returns>
|
||||
/// A read-only collection of WebSocket-based messages.
|
||||
/// </returns>
|
||||
IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch);
|
||||
/// <summary> Gets a collection of messages in this channel. </summary>
|
||||
|
||||
/// <summary>
|
||||
/// Gets a collection of messages in this channel.
|
||||
/// </summary>
|
||||
/// <param name="fromMessageId">The message ID to start the fetching from.</param>
|
||||
/// <param name="dir">The direction of which the message should be gotten from.</param>
|
||||
/// <param name="limit">The number of messages to get.</param>
|
||||
/// <returns>
|
||||
/// A read-only collection of WebSocket-based messages.
|
||||
/// </returns>
|
||||
IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch);
|
||||
/// <summary> Gets a collection of messages in this channel. </summary>
|
||||
/// <summary>
|
||||
/// Gets a collection of messages in this channel.
|
||||
/// </summary>
|
||||
/// <param name="fromMessage">The message to start the fetching from.</param>
|
||||
/// <param name="dir">The direction of which the message should be gotten from.</param>
|
||||
/// <param name="limit">The number of messages to get.</param>
|
||||
/// <returns>
|
||||
/// A read-only collection of WebSocket-based messages.
|
||||
/// </returns>
|
||||
IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch);
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a generic WebSocket-based channel that is private to select recipients.
|
||||
/// </summary>
|
||||
public interface ISocketPrivateChannel : IPrivateChannel
|
||||
{
|
||||
new IReadOnlyCollection<SocketUser> Recipients { get; }
|
||||
|
||||
@@ -3,22 +3,31 @@ using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.Audio;
|
||||
using Discord.Rest;
|
||||
using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based category channel.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketCategoryChannel : SocketGuildChannel, ICategoryChannel
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuildUser> Users
|
||||
=> Guild.Users.Where(x => Permissions.GetValue(
|
||||
Permissions.ResolveChannel(Guild, x, this, Permissions.ResolveGuild(Guild, x)),
|
||||
ChannelPermission.ViewChannel)).ToImmutableArray();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the child channels of this category.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of <see cref="SocketGuildChannel" /> whose
|
||||
/// <see cref="Discord.INestedChannel.CategoryId" /> matches the snowflake identifier of this category
|
||||
/// channel.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketGuildChannel> Channels
|
||||
=> Guild.Channels.Where(x => x is INestedChannel nestedChannel && nestedChannel.CategoryId == Id).ToImmutableArray();
|
||||
|
||||
@@ -34,6 +43,7 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//Users
|
||||
/// <inheritdoc />
|
||||
public override SocketGuildUser GetUser(ulong id)
|
||||
{
|
||||
var user = Guild.GetUser(id);
|
||||
@@ -51,18 +61,26 @@ namespace Discord.WebSocket
|
||||
internal new SocketCategoryChannel Clone() => MemberwiseClone() as SocketCategoryChannel;
|
||||
|
||||
// IGuildChannel
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable();
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(GetUser(id));
|
||||
/// <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 />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(id));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -8,16 +7,27 @@ using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based channel.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public abstract class SocketChannel : SocketEntity<ulong>, IChannel
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets when the channel is created.
|
||||
/// </summary>
|
||||
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
|
||||
/// <summary>
|
||||
/// Gets a collection of users from the WebSocket cache.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<SocketUser> Users => GetUsersInternal();
|
||||
|
||||
internal SocketChannel(DiscordSocketClient discord, ulong id)
|
||||
: base(discord, id)
|
||||
{
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidOperationException">Unexpected channel type is created.</exception>
|
||||
internal static ISocketPrivateChannel CreatePrivate(DiscordSocketClient discord, ClientState state, Model model)
|
||||
{
|
||||
switch (model.Type)
|
||||
@@ -33,17 +43,28 @@ namespace Discord.WebSocket
|
||||
internal abstract void Update(ClientState state, Model model);
|
||||
|
||||
//User
|
||||
/// <summary>
|
||||
/// Gets a generic user from this channel.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier of the user.</param>
|
||||
/// <returns>
|
||||
/// A generic WebSocket-based user associated with the snowflake identifier.
|
||||
/// </returns>
|
||||
public SocketUser GetUser(ulong id) => GetUserInternal(id);
|
||||
internal abstract SocketUser GetUserInternal(ulong id);
|
||||
internal abstract IReadOnlyCollection<SocketUser> GetUsersInternal();
|
||||
|
||||
private string DebuggerDisplay => $"Unknown ({Id}, Channel)";
|
||||
internal SocketChannel Clone() => MemberwiseClone() as SocketChannel;
|
||||
|
||||
//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
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Discord.Rest;
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
@@ -57,7 +57,7 @@ namespace Discord.WebSocket
|
||||
else
|
||||
return ImmutableArray.Create<SocketMessage>();
|
||||
}
|
||||
|
||||
/// <exception cref="NotSupportedException">Unexpected <see cref="ISocketMessageChannel"/> type.</exception>
|
||||
public static void AddMessage(ISocketMessageChannel channel, DiscordSocketClient discord,
|
||||
SocketMessage msg)
|
||||
{
|
||||
@@ -66,9 +66,10 @@ namespace Discord.WebSocket
|
||||
case SocketDMChannel dmChannel: dmChannel.AddMessage(msg); break;
|
||||
case SocketGroupChannel groupChannel: groupChannel.AddMessage(msg); break;
|
||||
case SocketTextChannel textChannel: textChannel.AddMessage(msg); break;
|
||||
default: throw new NotSupportedException("Unexpected ISocketMessageChannel type");
|
||||
default: throw new NotSupportedException($"Unexpected {nameof(ISocketMessageChannel)} type.");
|
||||
}
|
||||
}
|
||||
/// <exception cref="NotSupportedException">Unexpected <see cref="ISocketMessageChannel"/> type.</exception>
|
||||
public static SocketMessage RemoveMessage(ISocketMessageChannel channel, DiscordSocketClient discord,
|
||||
ulong id)
|
||||
{
|
||||
@@ -77,7 +78,7 @@ namespace Discord.WebSocket
|
||||
case SocketDMChannel dmChannel: return dmChannel.RemoveMessage(id);
|
||||
case SocketGroupChannel groupChannel: return groupChannel.RemoveMessage(id);
|
||||
case SocketTextChannel textChannel: return textChannel.RemoveMessage(id);
|
||||
default: throw new NotSupportedException("Unexpected ISocketMessageChannel type");
|
||||
default: throw new NotSupportedException($"Unexpected {nameof(ISocketMessageChannel)} type.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,25 @@ using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based direct-message channel.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, ISocketMessageChannel
|
||||
{
|
||||
private readonly MessageCache _messages;
|
||||
|
||||
public SocketUser Recipient { get; private set; }
|
||||
/// <summary>
|
||||
/// Gets the recipient of the channel.
|
||||
/// </summary>
|
||||
public SocketUser Recipient { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a collection that is the current logged-in user and the recipient.
|
||||
/// </summary>
|
||||
public new IReadOnlyCollection<SocketUser> Users => ImmutableArray.Create(Discord.CurrentUser, Recipient);
|
||||
|
||||
internal SocketDMChannel(DiscordSocketClient discord, ulong id, SocketGlobalUser recipient)
|
||||
@@ -26,7 +37,7 @@ namespace Discord.WebSocket
|
||||
Recipient = recipient;
|
||||
recipient.GlobalUser.AddRef();
|
||||
if (Discord.MessageCacheSize > 0)
|
||||
_messages = new MessageCache(Discord, this);
|
||||
_messages = new MessageCache(Discord);
|
||||
}
|
||||
internal static SocketDMChannel Create(DiscordSocketClient discord, ClientState state, Model model)
|
||||
{
|
||||
@@ -39,12 +50,22 @@ namespace Discord.WebSocket
|
||||
Recipient.Update(state, model.Recipients.Value[0]);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task CloseAsync(RequestOptions options = null)
|
||||
=> ChannelHelper.DeleteAsync(this, Discord, options);
|
||||
|
||||
//Messages
|
||||
/// <inheritdoc />
|
||||
public SocketMessage GetCachedMessage(ulong id)
|
||||
=> _messages?.Get(id);
|
||||
/// <summary>
|
||||
/// Gets the message associated with the given <paramref name="id"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">TThe ID of the message.</param>
|
||||
/// <param name="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// The message gotten from either the cache or the download, or <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
|
||||
{
|
||||
IMessage msg = _messages?.Get(id);
|
||||
@@ -52,37 +73,150 @@ namespace Discord.WebSocket
|
||||
msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false);
|
||||
return msg;
|
||||
}
|
||||
|
||||
/// <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 => 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>
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options);
|
||||
/// <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="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// Paged collection of messages.
|
||||
/// </returns>
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
|
||||
/// <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="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// Paged collection of messages.
|
||||
/// </returns>
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
|
||||
/// <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 />
|
||||
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);
|
||||
|
||||
@@ -92,6 +226,13 @@ namespace Discord.WebSocket
|
||||
=> _messages?.Remove(id);
|
||||
|
||||
//Users
|
||||
/// <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="SocketUser"/> object that is a recipient of this channel; otherwise <c>null</c>.
|
||||
/// </returns>
|
||||
public new SocketUser GetUser(ulong id)
|
||||
{
|
||||
if (id == Recipient.Id)
|
||||
@@ -102,24 +243,33 @@ namespace Discord.WebSocket
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the recipient user.
|
||||
/// </summary>
|
||||
public override string ToString() => $"@{Recipient}";
|
||||
private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)";
|
||||
internal new SocketDMChannel Clone() => MemberwiseClone() as SocketDMChannel;
|
||||
|
||||
//SocketChannel
|
||||
/// <inheritdoc />
|
||||
internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
|
||||
/// <inheritdoc />
|
||||
internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
|
||||
|
||||
//IDMChannel
|
||||
//IDMChannel
|
||||
/// <inheritdoc />
|
||||
IUser IDMChannel.Recipient => Recipient;
|
||||
|
||||
//ISocketPrivateChannel
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<SocketUser> ISocketPrivateChannel.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)
|
||||
@@ -127,28 +277,36 @@ namespace Discord.WebSocket
|
||||
else
|
||||
return GetCachedMessage(id);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
|
||||
/// <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
|
||||
//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();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ using VoiceStateModel = Discord.API.VoiceState;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based private group channel.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketGroupChannel : SocketChannel, IGroupChannel, ISocketPrivateChannel, ISocketMessageChannel, ISocketAudioChannel
|
||||
{
|
||||
@@ -23,8 +26,10 @@ namespace Discord.WebSocket
|
||||
private string _iconId;
|
||||
private ConcurrentDictionary<ulong, SocketGroupUser> _users;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
|
||||
public new IReadOnlyCollection<SocketGroupUser> Users => _users.ToReadOnlyCollection();
|
||||
public IReadOnlyCollection<SocketGroupUser> Recipients
|
||||
@@ -34,7 +39,7 @@ namespace Discord.WebSocket
|
||||
: base(discord, id)
|
||||
{
|
||||
if (Discord.MessageCacheSize > 0)
|
||||
_messages = new MessageCache(Discord, this);
|
||||
_messages = new MessageCache(Discord);
|
||||
_voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
|
||||
_users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
|
||||
}
|
||||
@@ -62,15 +67,18 @@ namespace Discord.WebSocket
|
||||
_users = users;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task LeaveAsync(RequestOptions options = null)
|
||||
=> ChannelHelper.DeleteAsync(this, Discord, options);
|
||||
|
||||
/// <exception cref="NotSupportedException">Voice is not yet supported for group channels.</exception>
|
||||
public Task<IAudioClient> ConnectAsync()
|
||||
{
|
||||
throw new NotSupportedException("Voice is not yet supported for group channels.");
|
||||
}
|
||||
|
||||
//Messages
|
||||
/// <inheritdoc />
|
||||
public SocketMessage GetCachedMessage(ulong id)
|
||||
=> _messages?.Get(id);
|
||||
public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
|
||||
@@ -86,31 +94,42 @@ namespace Discord.WebSocket
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
|
||||
/// <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 />
|
||||
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 />
|
||||
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);
|
||||
|
||||
@@ -120,6 +139,13 @@ namespace Discord.WebSocket
|
||||
=> _messages?.Remove(id);
|
||||
|
||||
//Users
|
||||
/// <summary>
|
||||
/// Gets a user from this group.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier of the user.</param>
|
||||
/// <returns>
|
||||
/// A WebSocket-based group user associated with the snowflake identifier.
|
||||
/// </returns>
|
||||
public new SocketGroupUser GetUser(ulong id)
|
||||
{
|
||||
if (_users.TryGetValue(id, out SocketGroupUser user))
|
||||
@@ -169,21 +195,29 @@ namespace Discord.WebSocket
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the name of the group.
|
||||
/// </summary>
|
||||
public override string ToString() => Name;
|
||||
private string DebuggerDisplay => $"{Name} ({Id}, Group)";
|
||||
internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel;
|
||||
|
||||
//SocketChannel
|
||||
/// <inheritdoc />
|
||||
internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
|
||||
/// <inheritdoc />
|
||||
internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
|
||||
|
||||
//ISocketPrivateChannel
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients;
|
||||
|
||||
//IPrivateChannel
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients;
|
||||
|
||||
//IMessageChannel
|
||||
/// <inheritdoc />
|
||||
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
{
|
||||
if (mode == CacheMode.AllowDownload)
|
||||
@@ -191,32 +225,40 @@ namespace Discord.WebSocket
|
||||
else
|
||||
return GetCachedMessage(id);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
|
||||
/// <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);
|
||||
|
||||
//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(); }
|
||||
|
||||
//IChannel
|
||||
/// <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();
|
||||
}
|
||||
|
||||
@@ -9,16 +9,34 @@ using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based guild channel.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketGuildChannel : SocketChannel, IGuildChannel
|
||||
{
|
||||
private ImmutableArray<Overwrite> _overwrites;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the guild associated with this channel.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A guild object that this channel belongs to.
|
||||
/// </returns>
|
||||
public SocketGuild Guild { get; }
|
||||
/// <inheritdoc />
|
||||
public string Name { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public int Position { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<Overwrite> PermissionOverwrites => _overwrites;
|
||||
/// <summary>
|
||||
/// Gets a collection of users that are able to view the channel.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of users that can access the channel (i.e. the users seen in the user list).
|
||||
/// </returns>
|
||||
public new virtual IReadOnlyCollection<SocketGuildUser> Users => ImmutableArray.Create<SocketGuildUser>();
|
||||
|
||||
internal SocketGuildChannel(DiscordSocketClient discord, ulong id, SocketGuild guild)
|
||||
@@ -41,6 +59,7 @@ namespace Discord.WebSocket
|
||||
return new SocketGuildChannel(guild.Discord, model.Id, guild);
|
||||
}
|
||||
}
|
||||
/// <inheritdoc />
|
||||
internal override void Update(ClientState state, Model model)
|
||||
{
|
||||
Name = model.Name.Value;
|
||||
@@ -53,11 +72,20 @@ namespace Discord.WebSocket
|
||||
_overwrites = newOverwrites.ToImmutable();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<GuildChannelProperties> func, RequestOptions options = null)
|
||||
=> ChannelHelper.ModifyAsync(this, Discord, func, options);
|
||||
/// <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++)
|
||||
@@ -67,6 +95,13 @@ namespace Discord.WebSocket
|
||||
}
|
||||
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++)
|
||||
@@ -76,16 +111,44 @@ namespace Discord.WebSocket
|
||||
}
|
||||
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);
|
||||
@@ -99,6 +162,14 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <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);
|
||||
@@ -113,50 +184,93 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns 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);
|
||||
|
||||
public new virtual SocketGuildUser GetUser(ulong id) => null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the channel.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A string that resolves to <see cref="SocketGuildChannel.Name"/>.
|
||||
/// </returns>
|
||||
public override string ToString() => Name;
|
||||
private string DebuggerDisplay => $"{Name} ({Id}, Guild)";
|
||||
internal new SocketGuildChannel Clone() => MemberwiseClone() as SocketGuildChannel;
|
||||
|
||||
//SocketChannel
|
||||
/// <inheritdoc />
|
||||
internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
|
||||
/// <inheritdoc />
|
||||
internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
|
||||
|
||||
//IGuildChannel
|
||||
/// <inheritdoc />
|
||||
IGuild IGuildChannel.Guild => Guild;
|
||||
/// <inheritdoc />
|
||||
ulong IGuildChannel.GuildId => Guild.Id;
|
||||
|
||||
/// <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)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable();
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(GetUser(id));
|
||||
|
||||
//IChannel
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable(); //Overridden in Text/Voice
|
||||
/// <inheritdoc />
|
||||
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IUser>(GetUser(id)); //Overridden in Text/Voice
|
||||
}
|
||||
|
||||
@@ -10,22 +10,37 @@ using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based channel in a guild that can send and receive messages.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessageChannel
|
||||
{
|
||||
private readonly MessageCache _messages;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Topic { get; private set; }
|
||||
public int SlowModeInterval { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public ulong? CategoryId { get; private set; }
|
||||
/// <summary>
|
||||
/// Gets the parent (category) of this channel in the guild's channel list.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An <see cref="ICategoryChannel"/> representing the parent of this channel; <c>null</c> if none is set.
|
||||
/// </returns>
|
||||
public ICategoryChannel Category
|
||||
=> CategoryId.HasValue ? Guild.GetChannel(CategoryId.Value) as ICategoryChannel : null;
|
||||
|
||||
private bool _nsfw;
|
||||
/// <inheritdoc />
|
||||
public bool IsNsfw => _nsfw;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Mention => MentionUtils.MentionChannel(Id);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuildUser> Users
|
||||
=> Guild.Users.Where(x => Permissions.GetValue(
|
||||
Permissions.ResolveChannel(Guild, x, this, Permissions.ResolveGuild(Guild, x)),
|
||||
@@ -35,7 +50,7 @@ namespace Discord.WebSocket
|
||||
: base(discord, id, guild)
|
||||
{
|
||||
if (Discord.MessageCacheSize > 0)
|
||||
_messages = new MessageCache(Discord, this);
|
||||
_messages = new MessageCache(Discord);
|
||||
}
|
||||
internal new static SocketTextChannel Create(SocketGuild guild, ClientState state, Model model)
|
||||
{
|
||||
@@ -52,12 +67,23 @@ namespace Discord.WebSocket
|
||||
_nsfw = model.Nsfw.GetValueOrDefault();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<TextChannelProperties> func, RequestOptions options = null)
|
||||
=> ChannelHelper.ModifyAsync(this, Discord, func, options);
|
||||
|
||||
//Messages
|
||||
/// <inheritdoc />
|
||||
public SocketMessage GetCachedMessage(ulong id)
|
||||
=> _messages?.Get(id);
|
||||
/// <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>
|
||||
public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
|
||||
{
|
||||
IMessage msg = _messages?.Get(id);
|
||||
@@ -65,42 +91,159 @@ namespace Discord.WebSocket
|
||||
msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false);
|
||||
return msg;
|
||||
}
|
||||
/// <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 => 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>
|
||||
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options);
|
||||
/// <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="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// Paged collection of messages.
|
||||
/// </returns>
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
|
||||
/// <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="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// Paged collection of messages.
|
||||
/// </returns>
|
||||
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
|
||||
/// <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 />
|
||||
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 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 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);
|
||||
|
||||
@@ -110,6 +253,7 @@ namespace Discord.WebSocket
|
||||
=> _messages?.Remove(id);
|
||||
|
||||
//Users
|
||||
/// <inheritdoc />
|
||||
public override SocketGuildUser GetUser(ulong id)
|
||||
{
|
||||
var user = Guild.GetUser(id);
|
||||
@@ -124,10 +268,37 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//Webhooks
|
||||
/// <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);
|
||||
|
||||
@@ -135,20 +306,26 @@ namespace Discord.WebSocket
|
||||
internal new SocketTextChannel Clone() => MemberwiseClone() as SocketTextChannel;
|
||||
|
||||
//ITextChannel
|
||||
/// <inheritdoc />
|
||||
async Task<IWebhook> ITextChannel.CreateWebhookAsync(string name, Stream avatar, RequestOptions options)
|
||||
=> await CreateWebhookAsync(name, avatar, options);
|
||||
=> await CreateWebhookAsync(name, avatar, options).ConfigureAwait(false);
|
||||
/// <inheritdoc />
|
||||
async Task<IWebhook> ITextChannel.GetWebhookAsync(ulong id, RequestOptions options)
|
||||
=> await GetWebhookAsync(id, options);
|
||||
=> await GetWebhookAsync(id, options).ConfigureAwait(false);
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyCollection<IWebhook>> ITextChannel.GetWebhooksAsync(RequestOptions options)
|
||||
=> await GetWebhooksAsync(options);
|
||||
=> await GetWebhooksAsync(options).ConfigureAwait(false);
|
||||
|
||||
//IGuildChannel
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable();
|
||||
|
||||
//IMessageChannel
|
||||
/// <inheritdoc />
|
||||
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
{
|
||||
if (mode == CacheMode.AllowDownload)
|
||||
@@ -156,26 +333,31 @@ namespace Discord.WebSocket
|
||||
else
|
||||
return GetCachedMessage(id);
|
||||
}
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
|
||||
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
|
||||
/// <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);
|
||||
|
||||
// INestedChannel
|
||||
/// <inheritdoc />
|
||||
Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult(Category);
|
||||
}
|
||||
|
||||
@@ -10,15 +10,28 @@ using Model = Discord.API.Channel;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based voice channel in a guild.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketVoiceChannel : SocketGuildChannel, IVoiceChannel, ISocketAudioChannel
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public int Bitrate { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public int? UserLimit { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public ulong? CategoryId { get; private set; }
|
||||
/// <summary>
|
||||
/// Gets the parent (category) channel of this channel.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A category channel representing the parent of this channel; <c>null</c> if none is set.
|
||||
/// </returns>
|
||||
public ICategoryChannel Category
|
||||
=> CategoryId.HasValue ? Guild.GetChannel(CategoryId.Value) as ICategoryChannel : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuildUser> Users
|
||||
=> Guild.Users.Where(x => x.VoiceChannel?.Id == Id).ToImmutableArray();
|
||||
|
||||
@@ -32,6 +45,7 @@ namespace Discord.WebSocket
|
||||
entity.Update(state, model);
|
||||
return entity;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
internal override void Update(ClientState state, Model model)
|
||||
{
|
||||
base.Update(state, model);
|
||||
@@ -40,17 +54,21 @@ namespace Discord.WebSocket
|
||||
UserLimit = model.UserLimit.Value != 0 ? model.UserLimit.Value : (int?)null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<VoiceChannelProperties> func, RequestOptions options = null)
|
||||
=> ChannelHelper.ModifyAsync(this, Discord, func, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false)
|
||||
{
|
||||
return await Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DisconnectAsync()
|
||||
=> await Guild.DisconnectAudioAsync();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override SocketGuildUser GetUser(ulong id)
|
||||
{
|
||||
var user = Guild.GetUser(id);
|
||||
@@ -63,12 +81,15 @@ namespace Discord.WebSocket
|
||||
internal new SocketVoiceChannel Clone() => MemberwiseClone() as SocketVoiceChannel;
|
||||
|
||||
//IGuildChannel
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable();
|
||||
|
||||
// INestedChannel
|
||||
/// <inheritdoc />
|
||||
Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult(Category);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ using VoiceStateModel = Discord.API.VoiceState;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based guild object.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketGuild : SocketEntity<ulong>, IGuild
|
||||
{
|
||||
private readonly SemaphoreSlim _audioLock;
|
||||
@@ -34,38 +38,96 @@ namespace Discord.WebSocket
|
||||
private ImmutableArray<string> _features;
|
||||
private AudioClient _audioClient;
|
||||
|
||||
/// <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; }
|
||||
/// <summary>
|
||||
/// Gets the number of members.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property retrieves the number of members returned by Discord.
|
||||
/// <note type="tip">
|
||||
/// <para>
|
||||
/// Due to how this property is returned by Discord instead of relying on the WebSocket cache, the
|
||||
/// number here is the most accurate in terms of counting the number of users within this guild.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Use this instead of enumerating the count of the
|
||||
/// <see cref="Discord.WebSocket.SocketGuild.Users" /> collection, as you may see discrepancy
|
||||
/// between that and this property.
|
||||
/// </para>
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
public int MemberCount { get; internal set; }
|
||||
/// <summary> Gets the number of members downloaded to the local guild cache. </summary>
|
||||
public int DownloadedMemberCount { get; private set; }
|
||||
internal bool IsAvailable { get; private set; }
|
||||
/// <summary> Indicates whether the client is connected to this guild. </summary>
|
||||
public bool IsConnected { get; internal set; }
|
||||
|
||||
internal ulong? AFKChannelId { get; private set; }
|
||||
internal ulong? EmbedChannelId { get; private set; }
|
||||
internal ulong? SystemChannelId { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public ulong OwnerId { get; private set; }
|
||||
/// <summary> Gets the user that owns this guild. </summary>
|
||||
public SocketGuildUser Owner => GetUser(OwnerId);
|
||||
/// <inheritdoc />
|
||||
public string VoiceRegionId { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public string IconId { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public string SplashId { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
|
||||
/// <inheritdoc />
|
||||
public string IconUrl => CDN.GetGuildIconUrl(Id, IconId);
|
||||
/// <inheritdoc />
|
||||
public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId);
|
||||
/// <summary> Indicates whether the client has all the members downloaded to the local guild cache. </summary>
|
||||
public bool HasAllMembers => MemberCount == DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted;
|
||||
/// <summary> Indicates whether the guild cache is synced to this guild. </summary>
|
||||
public bool IsSynced => _syncPromise.Task.IsCompleted;
|
||||
public Task SyncPromise => _syncPromise.Task;
|
||||
public Task DownloaderPromise => _downloaderPromise.Task;
|
||||
/// <summary>
|
||||
/// Gets the <see cref="IAudioClient" /> associated with this guild.
|
||||
/// </summary>
|
||||
public IAudioClient AudioClient => _audioClient;
|
||||
/// <summary>
|
||||
/// Gets the default channel in this guild.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property retrieves the first viewable text channel for this guild.
|
||||
/// <note type="warning">
|
||||
/// This channel does not guarantee the user can send message to it, as it only looks for the first viewable
|
||||
/// text channel.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A <see cref="SocketTextChannel"/> representing the first viewable channel that the user has access to.
|
||||
/// </returns>
|
||||
public SocketTextChannel DefaultChannel => TextChannels
|
||||
.Where(c => CurrentUser.GetPermissions(c).ViewChannel)
|
||||
.OrderBy(c => c.Position)
|
||||
.FirstOrDefault();
|
||||
/// <summary>
|
||||
/// Gets the AFK voice channel in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="SocketVoiceChannel" /> that the AFK users will be moved to after they have idled for too
|
||||
/// long; <c>null</c> if none is set.
|
||||
/// </returns>
|
||||
public SocketVoiceChannel AFKChannel
|
||||
{
|
||||
get
|
||||
@@ -74,6 +136,12 @@ namespace Discord.WebSocket
|
||||
return id.HasValue ? GetVoiceChannel(id.Value) : null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the embed channel (i.e. the channel set in the guild's widget settings) in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A channel set within the server's widget settings; <c>null</c> if none is set.
|
||||
/// </returns>
|
||||
public SocketGuildChannel EmbedChannel
|
||||
{
|
||||
get
|
||||
@@ -82,6 +150,12 @@ namespace Discord.WebSocket
|
||||
return id.HasValue ? GetChannel(id.Value) : null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the system channel where randomized welcome messages are sent in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A text channel where randomized welcome messages will be sent to; <c>null</c> if none is set.
|
||||
/// </returns>
|
||||
public SocketTextChannel SystemChannel
|
||||
{
|
||||
get
|
||||
@@ -90,14 +164,47 @@ namespace Discord.WebSocket
|
||||
return id.HasValue ? GetTextChannel(id.Value) : null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets a collection of all text channels in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of message channels found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketTextChannel> TextChannels
|
||||
=> Channels.OfType<SocketTextChannel>().ToImmutableArray();
|
||||
/// <summary>
|
||||
/// Gets a collection of all voice channels in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of voice channels found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketVoiceChannel> VoiceChannels
|
||||
=> Channels.OfType<SocketVoiceChannel>().ToImmutableArray();
|
||||
/// <summary>
|
||||
/// Gets a collection of all category channels in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of category channels found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketCategoryChannel> CategoryChannels
|
||||
=> Channels.OfType<SocketCategoryChannel>().ToImmutableArray();
|
||||
/// <summary>
|
||||
/// Gets the current logged-in user.
|
||||
/// </summary>
|
||||
public SocketGuildUser CurrentUser => _members.TryGetValue(Discord.CurrentUser.Id, out SocketGuildUser member) ? member : null;
|
||||
/// <summary>
|
||||
/// Gets the built-in role containing all users in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A role object that represents an <c>@everyone</c> role in this guild.
|
||||
/// </returns>
|
||||
public SocketRole EveryoneRole => GetRole(Id);
|
||||
/// <summary>
|
||||
/// Gets a collection of all channels in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of generic channels found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketGuildChannel> Channels
|
||||
{
|
||||
get
|
||||
@@ -107,9 +214,38 @@ namespace Discord.WebSocket
|
||||
return channels.Select(x => state.GetChannel(x) as SocketGuildChannel).Where(x => x != null).ToReadOnlyCollection(channels);
|
||||
}
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<GuildEmote> Emotes => _emotes;
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<string> Features => _features;
|
||||
/// <summary>
|
||||
/// Gets a collection of users in this guild.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property retrieves all users found within this guild.
|
||||
/// <note type="warning">
|
||||
/// <para>
|
||||
/// This property may not always return all the members for large guilds (i.e. guilds containing
|
||||
/// 100+ users). If you are simply looking to get the number of users present in this guild,
|
||||
/// consider using <see cref="MemberCount"/> instead.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Otherwise, you may need to enable <see cref="DiscordSocketConfig.AlwaysDownloadUsers"/> to fetch
|
||||
/// the full user list upon startup, or use <see cref="DownloadUsersAsync"/> to manually download
|
||||
/// the users.
|
||||
/// </para>
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A collection of guild users found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketGuildUser> Users => _members.ToReadOnlyCollection();
|
||||
/// <summary>
|
||||
/// Gets a collection of all roles in this guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A read-only collection of roles found within this guild.
|
||||
/// </returns>
|
||||
public IReadOnlyCollection<SocketRole> Roles => _roles.ToReadOnlyCollection();
|
||||
|
||||
internal SocketGuild(DiscordSocketClient client, ulong id)
|
||||
@@ -270,40 +406,87 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//General
|
||||
/// <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 Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null)
|
||||
=> GuildHelper.ModifyAsync(this, Discord, func, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
|
||||
public Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null)
|
||||
=> GuildHelper.ModifyEmbedAsync(this, Discord, func, options);
|
||||
/// <inheritdoc />
|
||||
public Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
|
||||
=> GuildHelper.ReorderChannelsAsync(this, Discord, args, options);
|
||||
/// <inheritdoc />
|
||||
public Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
|
||||
=> GuildHelper.ReorderRolesAsync(this, Discord, args, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task LeaveAsync(RequestOptions options = null)
|
||||
=> GuildHelper.LeaveAsync(this, Discord, options);
|
||||
|
||||
//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 channel in this guild.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier for the channel.</param>
|
||||
/// <returns>
|
||||
/// A generic channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public SocketGuildChannel GetChannel(ulong id)
|
||||
{
|
||||
var channel = Discord.State.GetChannel(id) as SocketGuildChannel;
|
||||
@@ -311,14 +494,73 @@ namespace Discord.WebSocket
|
||||
return channel;
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets a text channel in this guild.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier for the text channel.</param>
|
||||
/// <returns>
|
||||
/// A text channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public SocketTextChannel GetTextChannel(ulong id)
|
||||
=> GetChannel(id) as SocketTextChannel;
|
||||
/// <summary>
|
||||
/// Gets a voice channel in this guild.
|
||||
/// </summary>
|
||||
/// <param name="id">The snowflake identifier for the voice channel.</param>
|
||||
/// <returns>
|
||||
/// A voice channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public SocketVoiceChannel GetVoiceChannel(ulong id)
|
||||
=> GetChannel(id) as SocketVoiceChannel;
|
||||
|
||||
/// <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 new voice channel in this guild.
|
||||
/// </summary>
|
||||
/// <param name="name">The new name for the voice 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>
|
||||
/// A task that represents the asynchronous creation operation. The task result contains the newly 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 new channel category in this guild.
|
||||
/// </summary>
|
||||
/// <param name="name">The new name for the category.</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>
|
||||
/// A task that represents the asynchronous creation operation. The task result contains the newly created
|
||||
/// category channel.
|
||||
/// </returns>
|
||||
public Task<RestCategoryChannel> CreateCategoryChannelAsync(string name, RequestOptions options = null)
|
||||
=> GuildHelper.CreateCategoryChannelAsync(this, Discord, name, options);
|
||||
|
||||
@@ -343,6 +585,14 @@ namespace Discord.WebSocket
|
||||
=> 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>
|
||||
@@ -350,18 +600,40 @@ namespace Discord.WebSocket
|
||||
/// </summary>
|
||||
/// <param name="options">The options to be used when sending the request.</param>
|
||||
/// <returns>
|
||||
/// A partial metadata of the vanity invite found within this guild.
|
||||
/// A task that represents the asynchronous get operation. The task result contains the partial metadata of
|
||||
/// the vanity invite found within this guild; <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public Task<RestInviteMetadata> GetVanityInviteAsync(RequestOptions options = null)
|
||||
=> 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 SocketRole GetRole(ulong id)
|
||||
{
|
||||
if (_roles.TryGetValue(id, out SocketRole value))
|
||||
return value;
|
||||
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>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous creation operation. The task result contains the newly created
|
||||
/// role.
|
||||
/// </returns>
|
||||
public Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
|
||||
bool isHoisted = false, RequestOptions options = null)
|
||||
=> GuildHelper.CreateRoleAsync(this, Discord, name, permissions, color, isHoisted, options);
|
||||
@@ -379,12 +651,27 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//Users
|
||||
/// <summary>
|
||||
/// Gets a user from this guild.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method retrieves a user found within this guild.
|
||||
/// <note>
|
||||
/// This may return <c>null</c> in the WebSocket implementation due to incomplete user collection in
|
||||
/// large guilds.
|
||||
/// </note>
|
||||
/// </remarks>
|
||||
/// <param name="id">The snowflake identifier of the user.</param>
|
||||
/// <returns>
|
||||
/// A guild user associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
|
||||
/// </returns>
|
||||
public SocketGuildUser GetUser(ulong id)
|
||||
{
|
||||
if (_members.TryGetValue(id, out SocketGuildUser member))
|
||||
return member;
|
||||
return null;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null)
|
||||
=> GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options);
|
||||
|
||||
@@ -438,6 +725,7 @@ namespace Discord.WebSocket
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DownloadUsersAsync()
|
||||
{
|
||||
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
|
||||
@@ -448,22 +736,53 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
//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);
|
||||
|
||||
//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);
|
||||
|
||||
@@ -576,7 +895,7 @@ namespace Discord.WebSocket
|
||||
try
|
||||
{
|
||||
var timeoutTask = Task.Delay(15000);
|
||||
if (await Task.WhenAny(promise.Task, timeoutTask) == timeoutTask)
|
||||
if (await Task.WhenAny(promise.Task, timeoutTask).ConfigureAwait(false) == timeoutTask)
|
||||
throw new TimeoutException();
|
||||
return await promise.Task.ConfigureAwait(false);
|
||||
}
|
||||
@@ -650,20 +969,35 @@ namespace Discord.WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the guild.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A string that resolves to <see cref="Discord.WebSocket.SocketGuild.Name"/>.
|
||||
/// </returns>
|
||||
public override string ToString() => Name;
|
||||
private string DebuggerDisplay => $"{Name} ({Id})";
|
||||
internal SocketGuild Clone() => MemberwiseClone() as SocketGuild;
|
||||
|
||||
//IGuild
|
||||
/// <inheritdoc />
|
||||
ulong? IGuild.AFKChannelId => AFKChannelId;
|
||||
/// <inheritdoc />
|
||||
IAudioClient IGuild.AudioClient => null;
|
||||
/// <inheritdoc />
|
||||
bool IGuild.Available => true;
|
||||
/// <inheritdoc />
|
||||
ulong IGuild.DefaultChannelId => DefaultChannel?.Id ?? 0;
|
||||
/// <inheritdoc />
|
||||
ulong? IGuild.EmbedChannelId => EmbedChannelId;
|
||||
/// <inheritdoc />
|
||||
ulong? IGuild.SystemChannelId => SystemChannelId;
|
||||
/// <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/>
|
||||
@@ -673,60 +1007,84 @@ namespace Discord.WebSocket
|
||||
async Task<IBan> IGuild.GetBanAsync(ulong userId, RequestOptions options)
|
||||
=> await GetBanAsync(userId, options).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IGuildChannel>> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGuildChannel>>(Channels);
|
||||
/// <inheritdoc />
|
||||
Task<IGuildChannel> IGuild.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildChannel>(GetChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<ITextChannel>> IGuild.GetTextChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<ITextChannel>>(TextChannels);
|
||||
/// <inheritdoc />
|
||||
Task<ITextChannel> IGuild.GetTextChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<ITextChannel>(GetTextChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<IVoiceChannel>> IGuild.GetVoiceChannelsAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IVoiceChannel>>(VoiceChannels);
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyCollection<ICategoryChannel>> IGuild.GetCategoriesAsync(CacheMode mode , RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<ICategoryChannel>>(CategoryChannels);
|
||||
/// <inheritdoc />
|
||||
Task<IVoiceChannel> IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IVoiceChannel>(GetVoiceChannel(id));
|
||||
/// <inheritdoc />
|
||||
Task<IVoiceChannel> IGuild.GetAFKChannelAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IVoiceChannel>(AFKChannel);
|
||||
/// <inheritdoc />
|
||||
Task<ITextChannel> IGuild.GetDefaultChannelAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<ITextChannel>(DefaultChannel);
|
||||
/// <inheritdoc />
|
||||
Task<IGuildChannel> IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildChannel>(EmbedChannel);
|
||||
/// <inheritdoc />
|
||||
Task<ITextChannel> IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<ITextChannel>(SystemChannel);
|
||||
/// <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 />
|
||||
Task<IReadOnlyCollection<IGuildUser>> IGuild.GetUsersAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IReadOnlyCollection<IGuildUser>>(Users);
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(GetUser(id));
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuild.GetCurrentUserAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(CurrentUser);
|
||||
/// <inheritdoc />
|
||||
Task<IGuildUser> IGuild.GetOwnerAsync(CacheMode mode, RequestOptions options)
|
||||
=> Task.FromResult<IGuildUser>(Owner);
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyCollection<IAuditLogEntry>> IGuild.GetAuditLogsAsync(int limit, CacheMode cacheMode, RequestOptions options)
|
||||
{
|
||||
if (cacheMode == CacheMode.AllowDownload)
|
||||
@@ -735,9 +1093,11 @@ namespace Discord.WebSocket
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Discord.WebSocket
|
||||
|
||||
public IReadOnlyCollection<SocketMessage> Messages => _messages.ToReadOnlyCollection();
|
||||
|
||||
public MessageCache(DiscordSocketClient discord, IChannel channel)
|
||||
public MessageCache(DiscordSocketClient discord)
|
||||
{
|
||||
_size = discord.MessageCacheSize;
|
||||
_messages = new ConcurrentDictionary<ulong, SocketMessage>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(_size * 1.05));
|
||||
@@ -44,6 +44,8 @@ namespace Discord.WebSocket
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="limit"/> is less than 0.</exception>
|
||||
public IReadOnlyCollection<SocketMessage> GetMany(ulong? fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
|
||||
{
|
||||
if (limit < 0) throw new ArgumentOutOfRangeException(nameof(limit));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Discord.Rest;
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
@@ -8,27 +8,80 @@ using Model = Discord.API.Message;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based message.
|
||||
/// </summary>
|
||||
public abstract class SocketMessage : SocketEntity<ulong>, IMessage
|
||||
{
|
||||
private long _timestampTicks;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the author of this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A WebSocket-based user object.
|
||||
/// </returns>
|
||||
public SocketUser Author { get; }
|
||||
/// <summary>
|
||||
/// Gets the source channel of the message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A WebSocket-based message channel.
|
||||
/// </returns>
|
||||
public ISocketMessageChannel Channel { 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>
|
||||
/// Returns all attachments included in this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Collection of attachments.
|
||||
/// </returns>
|
||||
public virtual IReadOnlyCollection<Attachment> Attachments => ImmutableArray.Create<Attachment>();
|
||||
/// <summary>
|
||||
/// Returns all embeds included in this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Collection of embed objects.
|
||||
/// </returns>
|
||||
public virtual IReadOnlyCollection<Embed> Embeds => ImmutableArray.Create<Embed>();
|
||||
/// <summary>
|
||||
/// Returns the channels mentioned in this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Collection of WebSocket-based guild channels.
|
||||
/// </returns>
|
||||
public virtual IReadOnlyCollection<SocketGuildChannel> MentionedChannels => ImmutableArray.Create<SocketGuildChannel>();
|
||||
/// <summary>
|
||||
/// Returns the roles mentioned in this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Collection of WebSocket-based roles.
|
||||
/// </returns>
|
||||
public virtual IReadOnlyCollection<SocketRole> MentionedRoles => ImmutableArray.Create<SocketRole>();
|
||||
/// <summary>
|
||||
/// Returns the users mentioned in this message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Collection of WebSocket-based users.
|
||||
/// </returns>
|
||||
public virtual IReadOnlyCollection<SocketUser> MentionedUsers => ImmutableArray.Create<SocketUser>();
|
||||
/// <inheritdoc />
|
||||
public virtual IReadOnlyCollection<ITag> Tags => ImmutableArray.Create<ITag>();
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTimeOffset Timestamp => DateTimeUtils.FromTicks(_timestampTicks);
|
||||
|
||||
internal SocketMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author, MessageSource source)
|
||||
@@ -54,20 +107,35 @@ namespace Discord.WebSocket
|
||||
Content = model.Content.Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DeleteAsync(RequestOptions options = null)
|
||||
=> MessageHelper.DeleteAsync(this, Discord, options);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content of the message.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Content of the message.
|
||||
/// </returns>
|
||||
public override string ToString() => Content;
|
||||
internal SocketMessage Clone() => MemberwiseClone() as SocketMessage;
|
||||
|
||||
//IMessage
|
||||
/// <inheritdoc />
|
||||
IUser IMessage.Author => Author;
|
||||
/// <inheritdoc />
|
||||
IMessageChannel IMessage.Channel => Channel;
|
||||
/// <inheritdoc />
|
||||
MessageType IMessage.Type => MessageType.Default;
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<IAttachment> IMessage.Attachments => Attachments;
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<IEmbed> IMessage.Embeds => Embeds;
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<ulong> IMessage.MentionedChannelIds => MentionedChannels.Select(x => x.Id).ToImmutableArray();
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<ulong> IMessage.MentionedRoleIds => MentionedRoles.Select(x => x.Id).ToImmutableArray();
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<ulong> IMessage.MentionedUserIds => MentionedUsers.Select(x => x.Id).ToImmutableArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,50 @@
|
||||
using Model = Discord.API.Gateway.Reaction;
|
||||
using Model = Discord.API.Gateway.Reaction;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based reaction object.
|
||||
/// </summary>
|
||||
public class SocketReaction : IReaction
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the ID of the user who added the reaction.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A user snowflake identifier associated with the user.
|
||||
/// </returns>
|
||||
public ulong UserId { get; }
|
||||
/// <summary>
|
||||
/// Gets the user who added the reaction if possible.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A user object where possible; a value is not always returned.
|
||||
/// </returns>
|
||||
/// <seealso cref="Optional{T}"/>
|
||||
public Optional<IUser> User { get; }
|
||||
/// <summary>
|
||||
/// Gets the ID of the message that has been reacted to.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A message snowflake identifier associated with the message.
|
||||
/// </returns>
|
||||
public ulong MessageId { get; }
|
||||
/// <summary>
|
||||
/// Gets the message that has been reacted to if possible.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A WebSocket-based message where possible; a value is not always returned.
|
||||
/// </returns>
|
||||
/// <seealso cref="Optional{T}"/>
|
||||
public Optional<SocketUserMessage> Message { get; }
|
||||
/// <summary>
|
||||
/// Gets the channel where the reaction takes place in.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A WebSocket-based message channel.
|
||||
/// </returns>
|
||||
public ISocketMessageChannel Channel { get; }
|
||||
/// <inheritdoc />
|
||||
public IEmote Emote { get; }
|
||||
|
||||
internal SocketReaction(ISocketMessageChannel channel, ulong messageId, Optional<SocketUserMessage> message, ulong userId, Optional<IUser> user, IEmote emoji)
|
||||
@@ -30,6 +66,7 @@ namespace Discord.WebSocket
|
||||
return new SocketReaction(channel, model.MessageId, message, model.UserId, user, emote);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool Equals(object other)
|
||||
{
|
||||
if (other == null) return false;
|
||||
@@ -41,6 +78,7 @@ namespace Discord.WebSocket
|
||||
return UserId == otherReaction.UserId && MessageId == otherReaction.MessageId && Emote.Equals(otherReaction.Emote);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode()
|
||||
{
|
||||
unchecked
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics;
|
||||
using Model = Discord.API.Message;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based message sent by the system.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketSystemMessage : SocketMessage, ISystemMessage
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public MessageType Type { get; private set; }
|
||||
|
||||
internal SocketSystemMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author)
|
||||
|
||||
@@ -9,6 +9,9 @@ using Model = Discord.API.Message;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based message sent by a user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketUserMessage : SocketMessage, IUserMessage
|
||||
{
|
||||
@@ -19,22 +22,32 @@ namespace Discord.WebSocket
|
||||
private ImmutableArray<Embed> _embeds;
|
||||
private ImmutableArray<ITag> _tags;
|
||||
|
||||
/// <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<ITag> Tags => _tags;
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketGuildChannel> MentionedChannels => MessageHelper.FilterTagsByValue<SocketGuildChannel>(TagType.ChannelMention, _tags);
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketRole> MentionedRoles => MessageHelper.FilterTagsByValue<SocketRole>(TagType.RoleMention, _tags);
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyCollection<SocketUser> MentionedUsers => MessageHelper.FilterTagsByValue<SocketUser>(TagType.UserMention, _tags);
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyDictionary<IEmote, ReactionMetadata> Reactions => _reactions.GroupBy(r => r.Emote).ToDictionary(x => x.Key, x => new ReactionMetadata { ReactionCount = x.Count(), IsMe = x.Any(y => y.UserId == Discord.CurrentUser.Id) });
|
||||
|
||||
internal SocketUserMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author, MessageSource source)
|
||||
: base(discord, id, channel, author, source)
|
||||
{
|
||||
}
|
||||
internal static new SocketUserMessage Create(DiscordSocketClient discord, ClientState state, SocketUser author, ISocketMessageChannel channel, Model model)
|
||||
internal new static SocketUserMessage Create(DiscordSocketClient discord, ClientState state, SocketUser author, ISocketMessageChannel channel, Model model)
|
||||
{
|
||||
var entity = new SocketUserMessage(discord, model.Id, channel, author, MessageHelper.GetSource(model));
|
||||
entity.Update(state, model);
|
||||
@@ -121,30 +134,40 @@ namespace Discord.WebSocket
|
||||
_reactions.Clear();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <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 Task ModifyAsync(Action<MessageProperties> func, RequestOptions options = null)
|
||||
=> MessageHelper.ModifyAsync(this, Discord, func, options);
|
||||
|
||||
/// <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);
|
||||
|
||||
|
||||
private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})";
|
||||
internal new SocketUserMessage Clone() => MemberwiseClone() as SocketUserMessage;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Discord.Rest;
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -8,21 +8,45 @@ using Model = Discord.API.Role;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based role to be given to a guild user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketRole : SocketEntity<ulong>, IRole
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the guild that owns this role.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="SocketGuild"/> representing the parent guild of this role.
|
||||
/// </returns>
|
||||
public SocketGuild 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>
|
||||
/// Returns a value that determines if the role is an @everyone role.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the role is @everyone; otherwise <c>false</c>.
|
||||
/// </returns>
|
||||
public bool IsEveryone => Id == Guild.Id;
|
||||
/// <inheritdoc />
|
||||
public string Mention => IsEveryone ? "@everyone" : MentionUtils.MentionRole(Id);
|
||||
public IEnumerable<SocketGuildUser> Members
|
||||
=> Guild.Users.Where(x => x.Roles.Any(r => r.Id == Id));
|
||||
@@ -49,18 +73,28 @@ namespace Discord.WebSocket
|
||||
Permissions = new GuildPermissions(model.Permissions);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<RoleProperties> func, RequestOptions options = null)
|
||||
=> RoleHelper.ModifyAsync(this, Discord, func, options);
|
||||
/// <inheritdoc />
|
||||
public Task DeleteAsync(RequestOptions options = null)
|
||||
=> RoleHelper.DeleteAsync(this, Discord, options);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the role.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A string that resolves to <see cref="Discord.WebSocket.SocketRole.Name" />.
|
||||
/// </returns>
|
||||
public override string ToString() => Name;
|
||||
private string DebuggerDisplay => $"{Name} ({Id})";
|
||||
internal SocketRole Clone() => MemberwiseClone() as SocketRole;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CompareTo(IRole role) => RoleUtils.Compare(this, role);
|
||||
|
||||
//IRole
|
||||
/// <inheritdoc />
|
||||
IGuild IRole.Guild => Guild;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
@@ -6,6 +6,7 @@ namespace Discord.WebSocket
|
||||
where T : IEquatable<T>
|
||||
{
|
||||
internal DiscordSocketClient Discord { get; }
|
||||
/// <inheritdoc />
|
||||
public T Id { get; }
|
||||
|
||||
internal SocketEntity(DiscordSocketClient discord, T id)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using Model = Discord.API.User;
|
||||
using PresenceModel = Discord.API.Presence;
|
||||
@@ -54,7 +54,8 @@ namespace Discord.WebSocket
|
||||
Presence = SocketPresence.Create(model);
|
||||
DMChannel = state.DMChannels.FirstOrDefault(x => x.Recipient.Id == Id);
|
||||
}
|
||||
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Global)";
|
||||
internal new SocketGlobalUser Clone() => MemberwiseClone() as SocketGlobalUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics;
|
||||
using Model = Discord.API.User;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
@@ -6,15 +6,28 @@ namespace Discord.WebSocket
|
||||
[DebuggerDisplay("{DebuggerDisplay,nq}")]
|
||||
public class SocketGroupUser : SocketUser, IGroupUser
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the group channel of the user.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="SocketGroupChannel" /> representing the channel of which the user belongs to.
|
||||
/// </returns>
|
||||
public SocketGroupChannel Channel { get; }
|
||||
/// <inheritdoc />
|
||||
internal override SocketGlobalUser GlobalUser { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsBot { get { return GlobalUser.IsBot; } internal set { GlobalUser.IsBot = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string Username { get { return GlobalUser.Username; } internal set { GlobalUser.Username = value; } }
|
||||
/// <inheritdoc />
|
||||
public override ushort DiscriminatorValue { get { return GlobalUser.DiscriminatorValue; } internal set { GlobalUser.DiscriminatorValue = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string AvatarId { get { return GlobalUser.AvatarId; } internal set { GlobalUser.AvatarId = value; } }
|
||||
/// <inheritdoc />
|
||||
internal override SocketPresence Presence { get { return GlobalUser.Presence; } set { GlobalUser.Presence = value; } }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsWebhook => false;
|
||||
|
||||
internal SocketGroupUser(SocketGroupChannel channel, SocketGlobalUser globalUser)
|
||||
@@ -30,15 +43,23 @@ namespace Discord.WebSocket
|
||||
return entity;
|
||||
}
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Group)";
|
||||
internal new SocketGroupUser Clone() => MemberwiseClone() as SocketGroupUser;
|
||||
|
||||
//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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Discord.Audio;
|
||||
using Discord.Audio;
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -12,6 +12,9 @@ using PresenceModel = Discord.API.Presence;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based guild user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketGuildUser : SocketUser, IGuildUser
|
||||
{
|
||||
@@ -19,33 +22,67 @@ namespace Discord.WebSocket
|
||||
private ImmutableArray<ulong> _roleIds;
|
||||
|
||||
internal override SocketGlobalUser GlobalUser { get; }
|
||||
/// <summary>
|
||||
/// Gets the guild the user is in.
|
||||
/// </summary>
|
||||
public SocketGuild Guild { get; }
|
||||
/// <inheritdoc />
|
||||
public string Nickname { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsBot { get { return GlobalUser.IsBot; } internal set { GlobalUser.IsBot = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string Username { get { return GlobalUser.Username; } internal set { GlobalUser.Username = value; } }
|
||||
/// <inheritdoc />
|
||||
public override ushort DiscriminatorValue { get { return GlobalUser.DiscriminatorValue; } internal set { GlobalUser.DiscriminatorValue = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string AvatarId { get { return GlobalUser.AvatarId; } internal set { GlobalUser.AvatarId = value; } }
|
||||
/// <inheritdoc />
|
||||
public GuildPermissions GuildPermissions => new GuildPermissions(Permissions.ResolveGuild(Guild, this));
|
||||
internal override SocketPresence Presence { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsWebhook => false;
|
||||
/// <inheritdoc />
|
||||
public bool IsSelfDeafened => VoiceState?.IsSelfDeafened ?? false;
|
||||
/// <inheritdoc />
|
||||
public bool IsSelfMuted => VoiceState?.IsSelfMuted ?? false;
|
||||
/// <inheritdoc />
|
||||
public bool IsSuppressed => VoiceState?.IsSuppressed ?? false;
|
||||
/// <inheritdoc />
|
||||
public bool IsDeafened => VoiceState?.IsDeafened ?? false;
|
||||
/// <inheritdoc />
|
||||
public bool IsMuted => VoiceState?.IsMuted ?? false;
|
||||
/// <inheritdoc />
|
||||
public DateTimeOffset? JoinedAt => DateTimeUtils.FromTicks(_joinedAtTicks);
|
||||
/// <summary>
|
||||
/// Returns a collection of roles that the user possesses.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<SocketRole> Roles
|
||||
=> _roleIds.Select(id => Guild.GetRole(id)).Where(x => x != null).ToReadOnlyCollection(() => _roleIds.Length);
|
||||
/// <summary>
|
||||
/// Returns the voice channel the user is in, or <c>null</c> if none.
|
||||
/// </summary>
|
||||
public SocketVoiceChannel VoiceChannel => VoiceState?.VoiceChannel;
|
||||
/// <inheritdoc />
|
||||
public string VoiceSessionId => VoiceState?.VoiceSessionId ?? "";
|
||||
/// <summary>
|
||||
/// Gets the voice connection status of the user if any.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="SocketVoiceState" /> representing the user's voice status; <c>null</c> if the user is not
|
||||
/// connected to a voice channel.
|
||||
/// </returns>
|
||||
public SocketVoiceState? VoiceState => Guild.GetVoiceState(Id);
|
||||
public AudioInStream AudioStream => Guild.GetAudioStream(Id);
|
||||
|
||||
/// <summary> The position of the user within the role hierarchy. </summary>
|
||||
/// <remarks> The returned value equal to the position of the highest role the user has,
|
||||
/// or int.MaxValue if user is the server owner. </remarks>
|
||||
/// <summary>
|
||||
/// Returns the position of the user within the role hierarchy.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The returned value equal to the position of the highest role the user has, or
|
||||
/// <see cref="int.MaxValue"/> if user is the server owner.
|
||||
/// </remarks>
|
||||
public int Hierarchy
|
||||
{
|
||||
get
|
||||
@@ -119,9 +156,11 @@ namespace Discord.WebSocket
|
||||
roles.Add(roleIds[i]);
|
||||
_roleIds = roles.ToImmutable();
|
||||
}
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<GuildUserProperties> func, RequestOptions options = null)
|
||||
=> UserHelper.ModifyAsync(this, Discord, func, options);
|
||||
/// <inheritdoc />
|
||||
public Task KickAsync(string reason = null, RequestOptions options = null)
|
||||
=> UserHelper.KickAsync(this, Discord, reason, options);
|
||||
/// <inheritdoc />
|
||||
@@ -137,17 +176,23 @@ namespace Discord.WebSocket
|
||||
public Task RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null)
|
||||
=> UserHelper.RemoveRolesAsync(this, Discord, roles, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ChannelPermissions GetPermissions(IGuildChannel channel)
|
||||
=> new ChannelPermissions(Permissions.ResolveChannel(Guild, this, channel, GuildPermissions.RawValue));
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Guild)";
|
||||
internal new SocketGuildUser Clone() => MemberwiseClone() as SocketGuildUser;
|
||||
|
||||
//IGuildUser
|
||||
/// <inheritdoc />
|
||||
IGuild IGuildUser.Guild => Guild;
|
||||
/// <inheritdoc />
|
||||
ulong IGuildUser.GuildId => Guild.Id;
|
||||
/// <inheritdoc />
|
||||
IReadOnlyCollection<ulong> IGuildUser.RoleIds => _roleIds;
|
||||
|
||||
|
||||
//IVoiceState
|
||||
/// <inheritdoc />
|
||||
IVoiceChannel IVoiceState.VoiceChannel => VoiceChannel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics;
|
||||
using Model = Discord.API.Presence;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
//TODO: C#7 Candidate for record type
|
||||
/// <summary>
|
||||
/// Represents the WebSocket user's presence status. This may include their online status and their activity.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public struct SocketPresence : IPresence
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public UserStatus Status { get; }
|
||||
/// <inheritdoc />
|
||||
public IActivity Activity { get; }
|
||||
|
||||
internal SocketPresence(UserStatus status, IActivity activity)
|
||||
@@ -20,6 +24,12 @@ namespace Discord.WebSocket
|
||||
return new SocketPresence(model.Status, model.Game?.ToEntity());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status of the user.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A string that resolves to <see cref="Discord.WebSocket.SocketPresence.Status" />.
|
||||
/// </returns>
|
||||
public override string ToString() => Status.ToString();
|
||||
private string DebuggerDisplay => $"{Status}{(Activity != null ? $", {Activity.Name}": "")}";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Discord.Rest;
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
@@ -6,20 +6,32 @@ using Model = Discord.API.User;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the logged-in WebSocket-based user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketSelfUser : SocketUser, ISelfUser
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Email { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public bool IsVerified { get; private set; }
|
||||
/// <inheritdoc />
|
||||
public bool IsMfaEnabled { get; private set; }
|
||||
internal override SocketGlobalUser GlobalUser { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsBot { get { return GlobalUser.IsBot; } internal set { GlobalUser.IsBot = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string Username { get { return GlobalUser.Username; } internal set { GlobalUser.Username = value; } }
|
||||
/// <inheritdoc />
|
||||
public override ushort DiscriminatorValue { get { return GlobalUser.DiscriminatorValue; } internal set { GlobalUser.DiscriminatorValue = value; } }
|
||||
/// <inheritdoc />
|
||||
public override string AvatarId { get { return GlobalUser.AvatarId; } internal set { GlobalUser.AvatarId = value; } }
|
||||
/// <inheritdoc />
|
||||
internal override SocketPresence Presence { get { return GlobalUser.Presence; } set { GlobalUser.Presence = value; } }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsWebhook => false;
|
||||
|
||||
internal SocketSelfUser(DiscordSocketClient discord, SocketGlobalUser globalUser)
|
||||
@@ -53,10 +65,12 @@ namespace Discord.WebSocket
|
||||
}
|
||||
return hasGlobalChanges;
|
||||
}
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ModifyAsync(Action<SelfUserProperties> func, RequestOptions options = null)
|
||||
=> UserHelper.ModifyAsync(this, Discord, func, options);
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Self)";
|
||||
internal new SocketSelfUser Clone() => MemberwiseClone() as SocketSelfUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using Model = Discord.API.User;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based user that is yet to be recognized by the client.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A user may not be recognized due to the user missing from the cache or failed to be recognized properly.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketUnknownUser : SocketUser
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Username { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override ushort DiscriminatorValue { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override string AvatarId { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override bool IsBot { get; internal set; }
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsWebhook => false;
|
||||
|
||||
internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null); } set { } }
|
||||
internal override SocketGlobalUser GlobalUser { get { throw new NotSupportedException(); } }
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="NotSupportedException">This field is not supported for an unknown user.</exception>
|
||||
internal override SocketGlobalUser GlobalUser =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
internal SocketUnknownUser(DiscordSocketClient discord, ulong id)
|
||||
: base(discord, id)
|
||||
@@ -28,6 +42,7 @@ namespace Discord.WebSocket
|
||||
return entity;
|
||||
}
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Unknown)";
|
||||
internal new SocketUnknownUser Clone() => MemberwiseClone() as SocketUnknownUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,39 @@
|
||||
using Discord.Rest;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
using Model = Discord.API.User;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public abstract class SocketUser : SocketEntity<ulong>, IUser
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public abstract bool IsBot { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public abstract string Username { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public abstract ushort DiscriminatorValue { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public abstract string AvatarId { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public abstract bool IsWebhook { get; }
|
||||
internal abstract SocketGlobalUser GlobalUser { get; }
|
||||
internal abstract SocketPresence Presence { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
|
||||
/// <inheritdoc />
|
||||
public string Discriminator => DiscriminatorValue.ToString("D4");
|
||||
/// <inheritdoc />
|
||||
public string Mention => MentionUtils.MentionUser(Id);
|
||||
/// <inheritdoc />
|
||||
public IActivity Activity => Presence.Activity;
|
||||
/// <inheritdoc />
|
||||
public UserStatus Status => Presence.Status;
|
||||
|
||||
internal SocketUser(DiscordSocketClient discord, ulong id)
|
||||
@@ -55,15 +70,24 @@ namespace Discord.WebSocket
|
||||
return hasChanges;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IDMChannel> GetOrCreateDMChannelAsync(RequestOptions options = null)
|
||||
=> GlobalUser.DMChannel ?? await UserHelper.CreateDMChannelAsync(this, Discord, options) as IDMChannel;
|
||||
=> GlobalUser.DMChannel ?? await UserHelper.CreateDMChannelAsync(this, Discord, options).ConfigureAwait(false) as IDMChannel;
|
||||
|
||||
/// <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 full name of the user (e.g. Example#0001).
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// The full name of the user.
|
||||
/// </returns>
|
||||
public override string ToString() => $"{Username}#{Discriminator}";
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")})";
|
||||
internal SocketUser Clone() => MemberwiseClone() as SocketUser;
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using Model = Discord.API.VoiceState;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
//TODO: C#7 Candidate for record type
|
||||
/// <summary>
|
||||
/// Represents a WebSocket user's voice connection status.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public struct SocketVoiceState : IVoiceState
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a default <see cref="SocketVoiceState"/> with everything set to <c>null</c> or <c>false</c>.
|
||||
/// </summary>
|
||||
public static readonly SocketVoiceState Default = new SocketVoiceState(null, null, false, false, false, false, false);
|
||||
|
||||
[Flags]
|
||||
@@ -22,14 +27,23 @@ namespace Discord.WebSocket
|
||||
}
|
||||
|
||||
private readonly Flags _voiceStates;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the voice channel that the user is currently in; or <c>null</c> if none.
|
||||
/// </summary>
|
||||
public SocketVoiceChannel VoiceChannel { get; }
|
||||
/// <inheritdoc />
|
||||
public string VoiceSessionId { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsMuted => (_voiceStates & Flags.Muted) != 0;
|
||||
/// <inheritdoc />
|
||||
public bool IsDeafened => (_voiceStates & Flags.Deafened) != 0;
|
||||
/// <inheritdoc />
|
||||
public bool IsSuppressed => (_voiceStates & Flags.Suppressed) != 0;
|
||||
/// <inheritdoc />
|
||||
public bool IsSelfMuted => (_voiceStates & Flags.SelfMuted) != 0;
|
||||
/// <inheritdoc />
|
||||
public bool IsSelfDeafened => (_voiceStates & Flags.SelfDeafened) != 0;
|
||||
|
||||
internal SocketVoiceState(SocketVoiceChannel voiceChannel, string sessionId, bool isSelfMuted, bool isSelfDeafened, bool isMuted, bool isDeafened, bool isSuppressed)
|
||||
@@ -55,10 +69,17 @@ namespace Discord.WebSocket
|
||||
return new SocketVoiceState(voiceChannel, model.SessionId, model.SelfMute, model.SelfDeaf, model.Mute, model.Deaf, model.Suppress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of this voice channel.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A string that resolves to name of this voice channel; otherwise "Unknown".
|
||||
/// </returns>
|
||||
public override string ToString() => VoiceChannel?.Name ?? "Unknown";
|
||||
private string DebuggerDisplay => $"{VoiceChannel?.Name ?? "Unknown"} ({_voiceStates})";
|
||||
internal SocketVoiceState Clone() => this;
|
||||
|
||||
/// <inheritdoc />
|
||||
IVoiceChannel IVoiceState.VoiceChannel => VoiceChannel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
@@ -7,21 +7,32 @@ using Model = Discord.API.User;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based webhook user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketWebhookUser : SocketUser, IWebhookUser
|
||||
{
|
||||
/// <summary> Gets the guild of this webhook. </summary>
|
||||
public SocketGuild Guild { get; }
|
||||
/// <inheritdoc />
|
||||
public ulong WebhookId { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Username { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override ushort DiscriminatorValue { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override string AvatarId { get; internal set; }
|
||||
/// <inheritdoc />
|
||||
public override bool IsBot { get; internal set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsWebhook => true;
|
||||
|
||||
internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null); } set { } }
|
||||
internal override SocketGlobalUser GlobalUser { get { throw new NotSupportedException(); } }
|
||||
internal override SocketGlobalUser GlobalUser =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
internal SocketWebhookUser(SocketGuild guild, ulong id, ulong webhookId)
|
||||
: base(guild.Discord, id)
|
||||
@@ -36,51 +47,70 @@ namespace Discord.WebSocket
|
||||
return entity;
|
||||
}
|
||||
|
||||
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Webhook)";
|
||||
internal new SocketWebhookUser Clone() => MemberwiseClone() as SocketWebhookUser;
|
||||
|
||||
|
||||
//IGuildUser
|
||||
/// <inheritdoc />
|
||||
IGuild IGuildUser.Guild => Guild;
|
||||
/// <inheritdoc />
|
||||
ulong IGuildUser.GuildId => Guild.Id;
|
||||
/// <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 />
|
||||
/// <exception cref="NotSupportedException">Webhook users cannot be kicked.</exception>
|
||||
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 />
|
||||
/// <exception cref="NotSupportedException">Webhook users cannot be modified.</exception>
|
||||
Task IGuildUser.ModifyAsync(Action<GuildUserProperties> func, RequestOptions options) =>
|
||||
throw new NotSupportedException("Webhook users cannot be modified.");
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="NotSupportedException">Roles are not supported on webhook users.</exception>
|
||||
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 />
|
||||
/// <exception cref="NotSupportedException">Roles are not supported on webhook users.</exception>
|
||||
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 />
|
||||
/// <exception cref="NotSupportedException">Roles are not supported on webhook users.</exception>
|
||||
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 />
|
||||
/// <exception cref="NotSupportedException">Roles are not supported on webhook users.</exception>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,33 @@ using System.Diagnostics;
|
||||
|
||||
namespace Discord.WebSocket
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a WebSocket-based voice server.
|
||||
/// </summary>
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
public class SocketVoiceServer
|
||||
{
|
||||
public Cacheable<IGuild, ulong> Guild { get; private set; }
|
||||
public string Endpoint { get; private set; }
|
||||
public string Token { get; private set; }
|
||||
/// <summary>
|
||||
/// Gets the guild associated with the voice server.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A cached entity of the guild.
|
||||
/// </returns>
|
||||
public Cacheable<IGuild, ulong> Guild { get; }
|
||||
/// <summary>
|
||||
/// Gets the endpoint URL of the voice server host.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An URL representing the voice server host.
|
||||
/// </returns>
|
||||
public string Endpoint { get; }
|
||||
/// <summary>
|
||||
/// Gets the voice connection token.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A voice connection token.
|
||||
/// </returns>
|
||||
public string Token { get; }
|
||||
|
||||
internal SocketVoiceServer(Cacheable<IGuild, ulong> guild, string endpoint, string token)
|
||||
{
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace Discord.Net.WebSockets
|
||||
{
|
||||
public static readonly WebSocketProvider Instance = Create();
|
||||
|
||||
/// <exception cref="PlatformNotSupportedException">The default WebSocketProvider is not supported on this platform.</exception>
|
||||
public static WebSocketProvider Create(IWebProxy proxy = null)
|
||||
{
|
||||
return () =>
|
||||
|
||||
Reference in New Issue
Block a user