| @@ -0,0 +1,13 @@ | |||||
| #pragma warning disable CS1591 | |||||
| using Newtonsoft.Json; | |||||
| namespace Discord.API.Rest | |||||
| { | |||||
| public class GetBotGatewayResponse | |||||
| { | |||||
| [JsonProperty("url")] | |||||
| public string Url { get; set; } | |||||
| [JsonProperty("shards")] | |||||
| public int Shards { get; set; } | |||||
| } | |||||
| } | |||||
| @@ -24,5 +24,8 @@ namespace Discord | |||||
| /// <summary> Gets or sets the minimum log level severity that will be sent to the LogMessage event. </summary> | /// <summary> Gets or sets the minimum log level severity that will be sent to the LogMessage event. </summary> | ||||
| public LogSeverity LogLevel { get; set; } = LogSeverity.Info; | public LogSeverity LogLevel { get; set; } = LogSeverity.Info; | ||||
| /// <summary> Gets or sets whether the initial log entry should be printed. </summary> | |||||
| internal bool DisplayInitialLog { get; set; } = true; | |||||
| } | } | ||||
| } | } | ||||
| @@ -11,7 +11,7 @@ namespace Discord.Rest | |||||
| public abstract class BaseDiscordClient : IDiscordClient | public abstract class BaseDiscordClient : IDiscordClient | ||||
| { | { | ||||
| public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } } | public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } } | ||||
| private readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>(); | |||||
| internal readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>(); | |||||
| public event Func<Task> LoggedIn { add { _loggedInEvent.Add(value); } remove { _loggedInEvent.Remove(value); } } | public event Func<Task> LoggedIn { add { _loggedInEvent.Add(value); } remove { _loggedInEvent.Remove(value); } } | ||||
| private readonly AsyncEvent<Func<Task>> _loggedInEvent = new AsyncEvent<Func<Task>>(); | private readonly AsyncEvent<Func<Task>> _loggedInEvent = new AsyncEvent<Func<Task>>(); | ||||
| @@ -38,7 +38,7 @@ namespace Discord.Rest | |||||
| _connectionLock = new SemaphoreSlim(1, 1); | _connectionLock = new SemaphoreSlim(1, 1); | ||||
| _restLogger = LogManager.CreateLogger("Rest"); | _restLogger = LogManager.CreateLogger("Rest"); | ||||
| _queueLogger = LogManager.CreateLogger("Queue"); | _queueLogger = LogManager.CreateLogger("Queue"); | ||||
| _isFirstLogin = true; | |||||
| _isFirstLogin = config.DisplayInitialLog; | |||||
| ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => | ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => | ||||
| { | { | ||||
| @@ -0,0 +1,31 @@ | |||||
| using Discord.WebSocket; | |||||
| namespace Discord.Commands | |||||
| { | |||||
| public class ShardedCommandContext : ICommandContext | |||||
| { | |||||
| public DiscordShardedClient Client { get; } | |||||
| public SocketGuild Guild { get; } | |||||
| public ISocketMessageChannel Channel { get; } | |||||
| public SocketUser User { get; } | |||||
| public SocketUserMessage Message { get; } | |||||
| public bool IsPrivate => Channel is IPrivateChannel; | |||||
| public ShardedCommandContext(DiscordShardedClient client, SocketUserMessage msg) | |||||
| { | |||||
| Client = client; | |||||
| Guild = (msg.Channel as SocketGuildChannel)?.Guild; | |||||
| Channel = msg.Channel; | |||||
| User = msg.Author; | |||||
| Message = msg; | |||||
| } | |||||
| //ICommandContext | |||||
| IDiscordClient ICommandContext.Client => Client; | |||||
| IGuild ICommandContext.Guild => Guild; | |||||
| IMessageChannel ICommandContext.Channel => Channel; | |||||
| IUser ICommandContext.User => User; | |||||
| IUserMessage ICommandContext.Message => Message; | |||||
| } | |||||
| } | |||||
| @@ -0,0 +1,199 @@ | |||||
| using System; | |||||
| using System.Threading.Tasks; | |||||
| namespace Discord.WebSocket | |||||
| { | |||||
| //TODO: Add event docstrings | |||||
| public partial class DiscordShardedClient | |||||
| { | |||||
| //Channels | |||||
| public event Func<SocketChannel, Task> ChannelCreated | |||||
| { | |||||
| add { _channelCreatedEvent.Add(value); } | |||||
| remove { _channelCreatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketChannel, Task>> _channelCreatedEvent = new AsyncEvent<Func<SocketChannel, Task>>(); | |||||
| public event Func<SocketChannel, Task> ChannelDestroyed | |||||
| { | |||||
| add { _channelDestroyedEvent.Add(value); } | |||||
| remove { _channelDestroyedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketChannel, Task>> _channelDestroyedEvent = new AsyncEvent<Func<SocketChannel, Task>>(); | |||||
| public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated | |||||
| { | |||||
| add { _channelUpdatedEvent.Add(value); } | |||||
| remove { _channelUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketChannel, SocketChannel, Task>> _channelUpdatedEvent = new AsyncEvent<Func<SocketChannel, SocketChannel, Task>>(); | |||||
| //Messages | |||||
| public event Func<SocketMessage, Task> MessageReceived | |||||
| { | |||||
| add { _messageReceivedEvent.Add(value); } | |||||
| remove { _messageReceivedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>(); | |||||
| public event Func<ulong, Optional<SocketMessage>, Task> MessageDeleted | |||||
| { | |||||
| add { _messageDeletedEvent.Add(value); } | |||||
| remove { _messageDeletedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<ulong, Optional<SocketMessage>, Task>> _messageDeletedEvent = new AsyncEvent<Func<ulong, Optional<SocketMessage>, Task>>(); | |||||
| public event Func<Optional<SocketMessage>, SocketMessage, Task> MessageUpdated | |||||
| { | |||||
| add { _messageUpdatedEvent.Add(value); } | |||||
| remove { _messageUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<Optional<SocketMessage>, SocketMessage, Task>> _messageUpdatedEvent = new AsyncEvent<Func<Optional<SocketMessage>, SocketMessage, Task>>(); | |||||
| public event Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task> ReactionAdded | |||||
| { | |||||
| add { _reactionAddedEvent.Add(value); } | |||||
| remove { _reactionAddedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task>> _reactionAddedEvent = new AsyncEvent<Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task>>(); | |||||
| public event Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task> ReactionRemoved | |||||
| { | |||||
| add { _reactionRemovedEvent.Add(value); } | |||||
| remove { _reactionRemovedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task>> _reactionRemovedEvent = new AsyncEvent<Func<ulong, Optional<SocketUserMessage>, SocketReaction, Task>>(); | |||||
| public event Func<ulong, Optional<SocketUserMessage>, Task> ReactionsCleared | |||||
| { | |||||
| add { _reactionsClearedEvent.Add(value); } | |||||
| remove { _reactionsClearedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<ulong, Optional<SocketUserMessage>, Task>> _reactionsClearedEvent = new AsyncEvent<Func<ulong, Optional<SocketUserMessage>, Task>>(); | |||||
| //Roles | |||||
| public event Func<SocketRole, Task> RoleCreated | |||||
| { | |||||
| add { _roleCreatedEvent.Add(value); } | |||||
| remove { _roleCreatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketRole, Task>> _roleCreatedEvent = new AsyncEvent<Func<SocketRole, Task>>(); | |||||
| public event Func<SocketRole, Task> RoleDeleted | |||||
| { | |||||
| add { _roleDeletedEvent.Add(value); } | |||||
| remove { _roleDeletedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketRole, Task>> _roleDeletedEvent = new AsyncEvent<Func<SocketRole, Task>>(); | |||||
| public event Func<SocketRole, SocketRole, Task> RoleUpdated | |||||
| { | |||||
| add { _roleUpdatedEvent.Add(value); } | |||||
| remove { _roleUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketRole, SocketRole, Task>> _roleUpdatedEvent = new AsyncEvent<Func<SocketRole, SocketRole, Task>>(); | |||||
| //Guilds | |||||
| public event Func<SocketGuild, Task> JoinedGuild | |||||
| { | |||||
| add { _joinedGuildEvent.Add(value); } | |||||
| remove { _joinedGuildEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, Task>> _joinedGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>(); | |||||
| public event Func<SocketGuild, Task> LeftGuild | |||||
| { | |||||
| add { _leftGuildEvent.Add(value); } | |||||
| remove { _leftGuildEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, Task>> _leftGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>(); | |||||
| public event Func<SocketGuild, Task> GuildAvailable | |||||
| { | |||||
| add { _guildAvailableEvent.Add(value); } | |||||
| remove { _guildAvailableEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, Task>> _guildAvailableEvent = new AsyncEvent<Func<SocketGuild, Task>>(); | |||||
| public event Func<SocketGuild, Task> GuildUnavailable | |||||
| { | |||||
| add { _guildUnavailableEvent.Add(value); } | |||||
| remove { _guildUnavailableEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, Task>> _guildUnavailableEvent = new AsyncEvent<Func<SocketGuild, Task>>(); | |||||
| public event Func<SocketGuild, Task> GuildMembersDownloaded | |||||
| { | |||||
| add { _guildMembersDownloadedEvent.Add(value); } | |||||
| remove { _guildMembersDownloadedEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, Task>> _guildMembersDownloadedEvent = new AsyncEvent<Func<SocketGuild, Task>>(); | |||||
| public event Func<SocketGuild, SocketGuild, Task> GuildUpdated | |||||
| { | |||||
| add { _guildUpdatedEvent.Add(value); } | |||||
| remove { _guildUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private AsyncEvent<Func<SocketGuild, SocketGuild, Task>> _guildUpdatedEvent = new AsyncEvent<Func<SocketGuild, SocketGuild, Task>>(); | |||||
| //Users | |||||
| public event Func<SocketGuildUser, Task> UserJoined | |||||
| { | |||||
| add { _userJoinedEvent.Add(value); } | |||||
| remove { _userJoinedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketGuildUser, Task>> _userJoinedEvent = new AsyncEvent<Func<SocketGuildUser, Task>>(); | |||||
| public event Func<SocketGuildUser, Task> UserLeft | |||||
| { | |||||
| add { _userLeftEvent.Add(value); } | |||||
| remove { _userLeftEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketGuildUser, Task>> _userLeftEvent = new AsyncEvent<Func<SocketGuildUser, Task>>(); | |||||
| public event Func<SocketUser, SocketGuild, Task> UserBanned | |||||
| { | |||||
| add { _userBannedEvent.Add(value); } | |||||
| remove { _userBannedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userBannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>(); | |||||
| public event Func<SocketUser, SocketGuild, Task> UserUnbanned | |||||
| { | |||||
| add { _userUnbannedEvent.Add(value); } | |||||
| remove { _userUnbannedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userUnbannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>(); | |||||
| public event Func<SocketUser, SocketUser, Task> UserUpdated | |||||
| { | |||||
| add { _userUpdatedEvent.Add(value); } | |||||
| remove { _userUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketUser, SocketUser, Task>> _userUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketUser, Task>>(); | |||||
| public event Func<SocketGuildUser, SocketGuildUser, Task> GuildMemberUpdated | |||||
| { | |||||
| add { _guildMemberUpdatedEvent.Add(value); } | |||||
| remove { _guildMemberUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>> _guildMemberUpdatedEvent = new AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>>(); | |||||
| public event Func<Optional<SocketGuild>, SocketUser, SocketPresence, SocketPresence, Task> UserPresenceUpdated | |||||
| { | |||||
| add { _userPresenceUpdatedEvent.Add(value); } | |||||
| remove { _userPresenceUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<Optional<SocketGuild>, SocketUser, SocketPresence, SocketPresence, Task>> _userPresenceUpdatedEvent = new AsyncEvent<Func<Optional<SocketGuild>, SocketUser, SocketPresence, SocketPresence, Task>>(); | |||||
| public event Func<SocketUser, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated | |||||
| { | |||||
| add { _userVoiceStateUpdatedEvent.Add(value); } | |||||
| remove { _userVoiceStateUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>> _userVoiceStateUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>>(); | |||||
| public event Func<SocketSelfUser, SocketSelfUser, Task> CurrentUserUpdated | |||||
| { | |||||
| add { _selfUpdatedEvent.Add(value); } | |||||
| remove { _selfUpdatedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>> _selfUpdatedEvent = new AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>>(); | |||||
| public event Func<SocketUser, ISocketMessageChannel, Task> UserIsTyping | |||||
| { | |||||
| add { _userIsTypingEvent.Add(value); } | |||||
| remove { _userIsTypingEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>> _userIsTypingEvent = new AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>>(); | |||||
| public event Func<SocketGroupUser, Task> RecipientAdded | |||||
| { | |||||
| add { _recipientAddedEvent.Add(value); } | |||||
| remove { _recipientAddedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientAddedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>(); | |||||
| public event Func<SocketGroupUser, Task> RecipientRemoved | |||||
| { | |||||
| add { _recipientRemovedEvent.Add(value); } | |||||
| remove { _recipientRemovedEvent.Remove(value); } | |||||
| } | |||||
| private readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientRemovedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>(); | |||||
| } | |||||
| } | |||||
| @@ -0,0 +1,364 @@ | |||||
| using Discord.API; | |||||
| using Discord.Rest; | |||||
| using System; | |||||
| using System.Collections.Generic; | |||||
| using System.IO; | |||||
| using System.Linq; | |||||
| using System.Threading.Tasks; | |||||
| namespace Discord.WebSocket | |||||
| { | |||||
| public partial class DiscordShardedClient : BaseDiscordClient, IDiscordClient | |||||
| { | |||||
| private readonly DiscordSocketConfig _baseConfig; | |||||
| private int[] _shardIds; | |||||
| private Dictionary<int, int> _shardIdsToIndex; | |||||
| private DiscordSocketClient[] _shards; | |||||
| private int _totalShards; | |||||
| private bool _automaticShards; | |||||
| /// <summary> Gets the estimated round-trip latency, in milliseconds, to the gateway server. </summary> | |||||
| public int Latency { get; private set; } | |||||
| internal UserStatus Status => _shards[0].Status; | |||||
| internal Game? Game => _shards[0].Game; | |||||
| public new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient; | |||||
| public new SocketSelfUser CurrentUser { get { return base.CurrentUser as SocketSelfUser; } private set { base.CurrentUser = value; } } | |||||
| public IReadOnlyCollection<SocketGuild> Guilds => GetGuilds().ToReadOnlyCollection(() => GetGuildCount()); | |||||
| public IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(() => GetPrivateChannelCount()); | |||||
| public IReadOnlyCollection<DiscordSocketClient> Shards => _shards; | |||||
| public IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _shards[0].VoiceRegions; | |||||
| /// <summary> Creates a new REST/WebSocket discord client. </summary> | |||||
| public DiscordShardedClient() : this(null, new DiscordSocketConfig()) { } | |||||
| /// <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> | |||||
| public DiscordShardedClient(int[] ids) : this(ids, new DiscordSocketConfig()) { } | |||||
| /// <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) | |||||
| { | |||||
| if (config.ShardId != null) | |||||
| throw new ArgumentException($"{nameof(config.ShardId)} must not be set."); | |||||
| if (ids != null && config.TotalShards == null) | |||||
| throw new ArgumentException($"Custom ids are not supported when {nameof(config.TotalShards)} is not specified."); | |||||
| _shardIdsToIndex = new Dictionary<int, int>(); | |||||
| config.DisplayInitialLog = false; | |||||
| _baseConfig = config; | |||||
| if (config.TotalShards == null) | |||||
| _automaticShards = true; | |||||
| else | |||||
| { | |||||
| _totalShards = config.TotalShards.Value; | |||||
| _shardIds = ids ?? Enumerable.Range(0, _totalShards).ToArray(); | |||||
| _shards = new DiscordSocketClient[_shardIds.Length]; | |||||
| for (int i = 0; i < _shardIds.Length; i++) | |||||
| { | |||||
| _shardIdsToIndex.Add(_shardIds[i], i); | |||||
| var newConfig = config.Clone(); | |||||
| newConfig.ShardId = _shardIds[i]; | |||||
| _shards[i] = new DiscordSocketClient(newConfig); | |||||
| RegisterEvents(_shards[i]); | |||||
| } | |||||
| } | |||||
| } | |||||
| private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config) | |||||
| => new API.DiscordSocketApiClient(config.RestClientProvider, DiscordRestConfig.UserAgent, config.WebSocketProvider); | |||||
| protected override async Task OnLoginAsync(TokenType tokenType, string token) | |||||
| { | |||||
| if (_automaticShards) | |||||
| { | |||||
| var response = await ApiClient.GetBotGatewayAsync().ConfigureAwait(false); | |||||
| _shardIds = Enumerable.Range(0, response.Shards).ToArray(); | |||||
| _totalShards = _shardIds.Length; | |||||
| _shards = new DiscordSocketClient[_shardIds.Length]; | |||||
| for (int i = 0; i < _shardIds.Length; i++) | |||||
| { | |||||
| _shardIdsToIndex.Add(_shardIds[i], i); | |||||
| var newConfig = _baseConfig.Clone(); | |||||
| newConfig.ShardId = _shardIds[i]; | |||||
| newConfig.TotalShards = _totalShards; | |||||
| _shards[i] = new DiscordSocketClient(newConfig); | |||||
| RegisterEvents(_shards[i]); | |||||
| } | |||||
| } | |||||
| //Assume threadsafe: already in a connection lock | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].LoginAsync(tokenType, token, false); | |||||
| } | |||||
| protected override async Task OnLogoutAsync() | |||||
| { | |||||
| //Assume threadsafe: already in a connection lock | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].LogoutAsync(); | |||||
| CurrentUser = null; | |||||
| if (_automaticShards) | |||||
| { | |||||
| _shardIds = new int[0]; | |||||
| _shardIdsToIndex.Clear(); | |||||
| _totalShards = 0; | |||||
| _shards = null; | |||||
| } | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public async Task ConnectAsync(bool waitForGuilds = true) | |||||
| { | |||||
| await _connectionLock.WaitAsync().ConfigureAwait(false); | |||||
| try | |||||
| { | |||||
| await ConnectInternalAsync(waitForGuilds).ConfigureAwait(false); | |||||
| } | |||||
| catch | |||||
| { | |||||
| await DisconnectInternalAsync().ConfigureAwait(false); | |||||
| throw; | |||||
| } | |||||
| finally { _connectionLock.Release(); } | |||||
| } | |||||
| private async Task ConnectInternalAsync(bool waitForGuilds) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| await _shards[i].ConnectAsync(waitForGuilds).ConfigureAwait(false); | |||||
| if (i == 0) | |||||
| CurrentUser = _shards[i].CurrentUser; | |||||
| } | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public async Task DisconnectAsync() | |||||
| { | |||||
| await _connectionLock.WaitAsync().ConfigureAwait(false); | |||||
| try | |||||
| { | |||||
| await DisconnectInternalAsync().ConfigureAwait(false); | |||||
| } | |||||
| finally { _connectionLock.Release(); } | |||||
| } | |||||
| private async Task DisconnectInternalAsync() | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].DisconnectAsync(); | |||||
| } | |||||
| public DiscordSocketClient GetShard(int id) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| if (_shards[i].ShardId == id) | |||||
| return _shards[i]; | |||||
| } | |||||
| return null; | |||||
| } | |||||
| private int GetShardIdFor(ulong guildId) | |||||
| => (int)((guildId >> 22) % (uint)_totalShards); | |||||
| private int GetShardIdFor(IGuild guild) | |||||
| => GetShardIdFor(guild.Id); | |||||
| private DiscordSocketClient GetShardFor(ulong guildId) | |||||
| { | |||||
| int id = GetShardIdFor(guildId); | |||||
| if (_shardIdsToIndex.TryGetValue(id, out id)) | |||||
| return _shards[id]; | |||||
| return null; | |||||
| } | |||||
| private DiscordSocketClient GetShardFor(IGuild guild) | |||||
| => GetShardFor(guild.Id); | |||||
| /// <inheritdoc /> | |||||
| public async Task<RestApplication> GetApplicationInfoAsync() | |||||
| => await _shards[0].GetApplicationInfoAsync().ConfigureAwait(false); | |||||
| /// <inheritdoc /> | |||||
| public SocketGuild GetGuild(ulong id) => GetShardFor(id).GetGuild(id); | |||||
| /// <inheritdoc /> | |||||
| public Task<RestGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null) | |||||
| => ClientHelper.CreateGuildAsync(this, name, region, jpegIcon); | |||||
| /// <inheritdoc /> | |||||
| public SocketChannel GetChannel(ulong id) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| var channel = _shards[i].GetChannel(id); | |||||
| if (channel != null) | |||||
| return channel; | |||||
| } | |||||
| return null; | |||||
| } | |||||
| private IEnumerable<ISocketPrivateChannel> GetPrivateChannels() | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| foreach (var channel in _shards[i].PrivateChannels) | |||||
| yield return channel; | |||||
| } | |||||
| } | |||||
| private int GetPrivateChannelCount() | |||||
| { | |||||
| int result = 0; | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| result += _shards[i].PrivateChannels.Count; | |||||
| return result; | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync() | |||||
| => ClientHelper.GetConnectionsAsync(this); | |||||
| private IEnumerable<SocketGuild> GetGuilds() | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| foreach (var guild in _shards[i].Guilds) | |||||
| yield return guild; | |||||
| } | |||||
| } | |||||
| private int GetGuildCount() | |||||
| { | |||||
| int result = 0; | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| result += _shards[i].Guilds.Count; | |||||
| return result; | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public Task<RestInvite> GetInviteAsync(string inviteId) | |||||
| => ClientHelper.GetInviteAsync(this, inviteId); | |||||
| /// <inheritdoc /> | |||||
| public SocketUser GetUser(ulong id) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| var user = _shards[i].GetUser(id); | |||||
| if (user != null) | |||||
| return user; | |||||
| } | |||||
| return null; | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public SocketUser GetUser(string username, string discriminator) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| var user = _shards[i].GetUser(username, discriminator); | |||||
| if (user != null) | |||||
| return user; | |||||
| } | |||||
| return null; | |||||
| } | |||||
| /// <inheritdoc /> | |||||
| public RestVoiceRegion GetVoiceRegion(string id) | |||||
| => _shards[0].GetVoiceRegion(id); | |||||
| /// <summary> Downloads the users list for all large guilds. </summary> | |||||
| public async Task DownloadAllUsersAsync() | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].DownloadAllUsersAsync().ConfigureAwait(false); | |||||
| } | |||||
| /// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary> | |||||
| public async Task DownloadUsersAsync(IEnumerable<SocketGuild> guilds) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| { | |||||
| int id = _shardIds[i]; | |||||
| var arr = guilds.Where(x => GetShardIdFor(x) == id).ToArray(); | |||||
| if (arr.Length > 0) | |||||
| await _shards[i].DownloadUsersAsync(arr); | |||||
| } | |||||
| } | |||||
| public async Task SetStatusAsync(UserStatus status) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].SetStatusAsync(status).ConfigureAwait(false); | |||||
| } | |||||
| public async Task SetGameAsync(string name, string streamUrl = null, StreamType streamType = StreamType.NotStreaming) | |||||
| { | |||||
| for (int i = 0; i < _shards.Length; i++) | |||||
| await _shards[i].SetGameAsync(name, streamUrl, streamType).ConfigureAwait(false); | |||||
| } | |||||
| private void RegisterEvents(DiscordSocketClient client) | |||||
| { | |||||
| client.Log += (msg) => _logEvent.InvokeAsync(msg); | |||||
| client.ChannelCreated += (channel) => _channelCreatedEvent.InvokeAsync(channel); | |||||
| client.ChannelDestroyed += (channel) => _channelDestroyedEvent.InvokeAsync(channel); | |||||
| client.ChannelUpdated += (oldChannel, newChannel) => _channelUpdatedEvent.InvokeAsync(oldChannel, newChannel); | |||||
| client.MessageReceived += (msg) => _messageReceivedEvent.InvokeAsync(msg); | |||||
| client.MessageDeleted += (id, msg) => _messageDeletedEvent.InvokeAsync(id, msg); | |||||
| client.MessageUpdated += (oldMsg, newMsg) => _messageUpdatedEvent.InvokeAsync(oldMsg, newMsg); | |||||
| client.ReactionAdded += (id, msg, reaction) => _reactionAddedEvent.InvokeAsync(id, msg, reaction); | |||||
| client.ReactionRemoved += (id, msg, reaction) => _reactionRemovedEvent.InvokeAsync(id, msg, reaction); | |||||
| client.ReactionsCleared += (id, msg) => _reactionsClearedEvent.InvokeAsync(id, msg); | |||||
| client.RoleCreated += (role) => _roleCreatedEvent.InvokeAsync(role); | |||||
| client.RoleDeleted += (role) => _roleDeletedEvent.InvokeAsync(role); | |||||
| client.RoleUpdated += (oldRole, newRole) => _roleUpdatedEvent.InvokeAsync(oldRole, newRole); | |||||
| client.JoinedGuild += (guild) => _joinedGuildEvent.InvokeAsync(guild); | |||||
| client.LeftGuild += (guild) => _leftGuildEvent.InvokeAsync(guild); | |||||
| client.GuildAvailable += (guild) => _guildAvailableEvent.InvokeAsync(guild); | |||||
| client.GuildUnavailable += (guild) => _guildUnavailableEvent.InvokeAsync(guild); | |||||
| client.GuildMembersDownloaded += (guild) => _guildMembersDownloadedEvent.InvokeAsync(guild); | |||||
| client.GuildUpdated += (oldGuild, newGuild) => _guildUpdatedEvent.InvokeAsync(oldGuild, newGuild); | |||||
| client.UserJoined += (user) => _userJoinedEvent.InvokeAsync(user); | |||||
| client.UserLeft += (user) => _userLeftEvent.InvokeAsync(user); | |||||
| client.UserBanned += (user, guild) => _userBannedEvent.InvokeAsync(user, guild); | |||||
| client.UserUnbanned += (user, guild) => _userUnbannedEvent.InvokeAsync(user, guild); | |||||
| client.UserUpdated += (oldUser, newUser) => _userUpdatedEvent.InvokeAsync(oldUser, newUser); | |||||
| client.UserPresenceUpdated += (guild, user, oldPresence, newPresence) => _userPresenceUpdatedEvent.InvokeAsync(guild, user, oldPresence, newPresence); | |||||
| client.UserVoiceStateUpdated += (user, oldVoiceState, newVoiceState) => _userVoiceStateUpdatedEvent.InvokeAsync(user, oldVoiceState, newVoiceState); | |||||
| client.CurrentUserUpdated += (oldUser, newUser) => _selfUpdatedEvent.InvokeAsync(oldUser, newUser); | |||||
| client.UserIsTyping += (oldUser, newUser) => _userIsTypingEvent.InvokeAsync(oldUser, newUser); | |||||
| client.RecipientAdded += (user) => _recipientAddedEvent.InvokeAsync(user); | |||||
| client.RecipientAdded += (user) => _recipientRemovedEvent.InvokeAsync(user); | |||||
| } | |||||
| //IDiscordClient | |||||
| Task IDiscordClient.ConnectAsync() | |||||
| => ConnectAsync(); | |||||
| async Task<IApplication> IDiscordClient.GetApplicationInfoAsync() | |||||
| => await GetApplicationInfoAsync().ConfigureAwait(false); | |||||
| Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode) | |||||
| => Task.FromResult<IChannel>(GetChannel(id)); | |||||
| Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode) | |||||
| => Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels); | |||||
| async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync() | |||||
| => await GetConnectionsAsync().ConfigureAwait(false); | |||||
| async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId) | |||||
| => await GetInviteAsync(inviteId).ConfigureAwait(false); | |||||
| Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode) | |||||
| => Task.FromResult<IGuild>(GetGuild(id)); | |||||
| Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode) | |||||
| => Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds); | |||||
| async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon) | |||||
| => await CreateGuildAsync(name, region, jpegIcon).ConfigureAwait(false); | |||||
| Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode) | |||||
| => Task.FromResult<IUser>(GetUser(id)); | |||||
| Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator) | |||||
| => Task.FromResult<IUser>(GetUser(username, discriminator)); | |||||
| Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync() | |||||
| => Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions); | |||||
| Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id) | |||||
| => Task.FromResult<IVoiceRegion>(GetVoiceRegion(id)); | |||||
| } | |||||
| } | |||||
| @@ -178,6 +178,11 @@ namespace Discord.API | |||||
| options = RequestOptions.CreateOrClone(options); | options = RequestOptions.CreateOrClone(options); | ||||
| return await SendAsync<GetGatewayResponse>("GET", () => "gateway", new BucketIds(), options: options).ConfigureAwait(false); | return await SendAsync<GetGatewayResponse>("GET", () => "gateway", new BucketIds(), options: options).ConfigureAwait(false); | ||||
| } | } | ||||
| public async Task<GetBotGatewayResponse> GetBotGatewayAsync(RequestOptions options = null) | |||||
| { | |||||
| options = RequestOptions.CreateOrClone(options); | |||||
| return await SendAsync<GetBotGatewayResponse>("GET", () => "gateway/bot", new BucketIds(), options: options).ConfigureAwait(false); | |||||
| } | |||||
| public async Task SendIdentifyAsync(int largeThreshold = 100, bool useCompression = true, int shardID = 0, int totalShards = 1, RequestOptions options = null) | public async Task SendIdentifyAsync(int largeThreshold = 100, bool useCompression = true, int shardID = 0, int totalShards = 1, RequestOptions options = null) | ||||
| { | { | ||||
| options = RequestOptions.CreateOrClone(options); | options = RequestOptions.CreateOrClone(options); | ||||
| @@ -3,7 +3,6 @@ using Discord.API.Gateway; | |||||
| using Discord.Audio; | using Discord.Audio; | ||||
| using Discord.Logging; | using Discord.Logging; | ||||
| using Discord.Net.Converters; | using Discord.Net.Converters; | ||||
| using Discord.Net.Queue; | |||||
| using Discord.Net.Udp; | using Discord.Net.Udp; | ||||
| using Discord.Net.WebSockets; | using Discord.Net.WebSockets; | ||||
| using Discord.Rest; | using Discord.Rest; | ||||
| @@ -65,6 +64,7 @@ namespace Discord.WebSocket | |||||
| public new SocketSelfUser CurrentUser { get { return base.CurrentUser as SocketSelfUser; } private set { base.CurrentUser = value; } } | public new SocketSelfUser CurrentUser { get { return base.CurrentUser as SocketSelfUser; } private set { base.CurrentUser = value; } } | ||||
| public IReadOnlyCollection<SocketGuild> Guilds => State.Guilds; | public IReadOnlyCollection<SocketGuild> Guilds => State.Guilds; | ||||
| public IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels; | public IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels; | ||||
| public IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection(); | |||||
| /// <summary> Creates a new REST/WebSocket discord client. </summary> | /// <summary> Creates a new REST/WebSocket discord client. </summary> | ||||
| public DiscordSocketClient() : this(new DiscordSocketConfig()) { } | public DiscordSocketClient() : this(new DiscordSocketConfig()) { } | ||||
| @@ -73,8 +73,8 @@ namespace Discord.WebSocket | |||||
| private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client) | private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client) | ||||
| : base(config, client) | : base(config, client) | ||||
| { | { | ||||
| ShardId = config.ShardId; | |||||
| TotalShards = config.TotalShards; | |||||
| ShardId = config.ShardId ?? 0; | |||||
| TotalShards = config.TotalShards ?? 1; | |||||
| MessageCacheSize = config.MessageCacheSize; | MessageCacheSize = config.MessageCacheSize; | ||||
| LargeThreshold = config.LargeThreshold; | LargeThreshold = config.LargeThreshold; | ||||
| AudioMode = config.AudioMode; | AudioMode = config.AudioMode; | ||||
| @@ -85,7 +85,7 @@ namespace Discord.WebSocket | |||||
| State = new ClientState(0, 0); | State = new ClientState(0, 0); | ||||
| _nextAudioId = 1; | _nextAudioId = 1; | ||||
| _gatewayLogger = LogManager.CreateLogger("Gateway"); | |||||
| _gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : "Shard #" + ShardId); | |||||
| _serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() }; | _serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() }; | ||||
| _serializer.Error += (s, e) => | _serializer.Error += (s, e) => | ||||
| @@ -206,7 +206,7 @@ namespace Discord.WebSocket | |||||
| await _connectTask.Task.ConfigureAwait(false); | await _connectTask.Task.ConfigureAwait(false); | ||||
| await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); | await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); | ||||
| await SendStatus().ConfigureAwait(false); | |||||
| await SendStatusAsync().ConfigureAwait(false); | |||||
| await _gatewayLogger.DebugAsync("Raising Event").ConfigureAwait(false); | await _gatewayLogger.DebugAsync("Raising Event").ConfigureAwait(false); | ||||
| if (!isReconnecting) | if (!isReconnecting) | ||||
| @@ -424,11 +424,7 @@ namespace Discord.WebSocket | |||||
| public Task DownloadAllUsersAsync() | public Task DownloadAllUsersAsync() | ||||
| => DownloadUsersAsync(State.Guilds.Where(x => !x.HasAllMembers)); | => DownloadUsersAsync(State.Guilds.Where(x => !x.HasAllMembers)); | ||||
| /// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary> | /// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary> | ||||
| public Task DownloadUsersAsync(IEnumerable<IGuild> guilds) | |||||
| => DownloadUsersAsync(guilds.Select(x => x as SocketGuild).Where(x => x != null)); | |||||
| public Task DownloadUsersAsync(params IGuild[] guilds) | |||||
| => DownloadUsersAsync(guilds.Select(x => x as SocketGuild).Where(x => x != null)); | |||||
| private async Task DownloadUsersAsync(IEnumerable<SocketGuild> guilds) | |||||
| public async Task DownloadUsersAsync(IEnumerable<SocketGuild> guilds) | |||||
| { | { | ||||
| var cachedGuilds = guilds.ToImmutableArray(); | var cachedGuilds = guilds.ToImmutableArray(); | ||||
| if (cachedGuilds.Length == 0) return; | if (cachedGuilds.Length == 0) return; | ||||
| @@ -474,25 +470,25 @@ namespace Discord.WebSocket | |||||
| } | } | ||||
| } | } | ||||
| public async Task SetStatus(UserStatus status) | |||||
| public async Task SetStatusAsync(UserStatus status) | |||||
| { | { | ||||
| Status = status; | Status = status; | ||||
| if (status == UserStatus.AFK) | if (status == UserStatus.AFK) | ||||
| _statusSince = DateTimeOffset.UtcNow; | _statusSince = DateTimeOffset.UtcNow; | ||||
| else | else | ||||
| _statusSince = null; | _statusSince = null; | ||||
| await SendStatus().ConfigureAwait(false); | |||||
| await SendStatusAsync().ConfigureAwait(false); | |||||
| } | } | ||||
| public async Task SetGame(string name, string streamUrl = null, StreamType streamType = StreamType.NotStreaming) | |||||
| public async Task SetGameAsync(string name, string streamUrl = null, StreamType streamType = StreamType.NotStreaming) | |||||
| { | { | ||||
| if (name != null) | if (name != null) | ||||
| Game = new Game(name, streamUrl, streamType); | Game = new Game(name, streamUrl, streamType); | ||||
| else | else | ||||
| Game = null; | Game = null; | ||||
| CurrentUser.Presence = new SocketPresence(Status, Game); | CurrentUser.Presence = new SocketPresence(Status, Game); | ||||
| await SendStatus().ConfigureAwait(false); | |||||
| await SendStatusAsync().ConfigureAwait(false); | |||||
| } | } | ||||
| private async Task SendStatus() | |||||
| private async Task SendStatusAsync() | |||||
| { | { | ||||
| var game = Game; | var game = Game; | ||||
| var status = Status; | var status = Status; | ||||
| @@ -1803,7 +1799,7 @@ namespace Discord.WebSocket | |||||
| => Task.FromResult<IUser>(GetUser(username, discriminator)); | => Task.FromResult<IUser>(GetUser(username, discriminator)); | ||||
| Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync() | Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync() | ||||
| => Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(_voiceRegions.ToReadOnlyCollection()); | |||||
| => Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions); | |||||
| Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id) | Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id) | ||||
| => Task.FromResult<IVoiceRegion>(GetVoiceRegion(id)); | => Task.FromResult<IVoiceRegion>(GetVoiceRegion(id)); | ||||
| } | } | ||||
| @@ -14,9 +14,9 @@ namespace Discord.WebSocket | |||||
| public int ConnectionTimeout { get; set; } = 30000; | 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 TotalShards. </summary> | ||||
| public int ShardId { get; set; } = 0; | |||||
| 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; } = 1; | |||||
| 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; | public int MessageCacheSize { get; set; } = 0; | ||||
| @@ -54,5 +54,7 @@ namespace Discord.WebSocket | |||||
| }; | }; | ||||
| #endif | #endif | ||||
| } | } | ||||
| internal DiscordSocketConfig Clone() => MemberwiseClone() as DiscordSocketConfig; | |||||
| } | } | ||||
| } | } | ||||