Exemplo n.º 1
0
        internal async Task <int> InitializeShardsAsync()
        {
            if (this.Shards.Count != 0)
            {
                return(this.Shards.Count);
            }

            var shardc = this.Config.ShardCount == 1 ? await this.GetShardCountAsync().ConfigureAwait(false) : this.Config.ShardCount;

            for (var i = 0; i < shardc; i++)
            {
                var cfg = new DiscordConfiguration(this.Config)
                {
                    ShardId               = i,
                    ShardCount            = shardc,
                    UseInternalLogHandler = false
                };

                var client = new DiscordClient(cfg);
                if (!this.Shards.TryAdd(i, client))
                {
                    throw new Exception("Could not initialize shards.");
                }
            }

            return(shardc);
        }
Exemplo n.º 2
0
        internal async Task <int> InitializeShardsAsync()
        {
            if (this._shards.Count != 0)
            {
                return(this._shards.Count);
            }

            this.GatewayInfo = await this.GetGatewayInfoAsync().ConfigureAwait(false);

            var shardc = this.Configuration.ShardCount == 1 ? this.GatewayInfo.ShardCount : this.Configuration.ShardCount;
            var lf     = new ShardedLoggerFactory(this.Logger);

            for (var i = 0; i < shardc; i++)
            {
                var cfg = new DiscordConfiguration(this.Configuration)
                {
                    ShardId       = i,
                    ShardCount    = shardc,
                    LoggerFactory = lf
                };

                var client = new DiscordClient(cfg);
                if (!this._shards.TryAdd(i, client))
                {
                    throw new InvalidOperationException("Could not initialize shards.");
                }
            }

            return(shardc);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes this Discord API client.
        /// </summary>
        /// <param name="config">Configuration for this client.</param>
        protected BaseDiscordClient(DiscordConfiguration config)
        {
            this.Configuration = new DiscordConfiguration(config);

            if (this.Configuration.LoggerFactory == null)
            {
                this.Configuration.LoggerFactory = new DefaultLoggerFactory();
                this.Configuration.LoggerFactory.AddProvider(new DefaultLoggerProvider(this));
            }
            this.Logger = this.Configuration.LoggerFactory.CreateLogger <BaseDiscordClient>();

            this.ApiClient            = new DiscordApiClient(this);
            this.UserCache            = new ConcurrentDictionary <ulong, DiscordUser>();
            this.InternalVoiceRegions = new ConcurrentDictionary <string, DiscordVoiceRegion>();
            this._voice_regions_lazy  = new Lazy <IReadOnlyDictionary <string, DiscordVoiceRegion> >(() => new ReadOnlyDictionary <string, DiscordVoiceRegion>(this.InternalVoiceRegions));

            var a = typeof(DiscordClient).GetTypeInfo().Assembly;

            var iv = a.GetCustomAttribute <AssemblyInformationalVersionAttribute>();

            if (iv != null)
            {
                this.VersionString = iv.InformationalVersion;
            }
            else
            {
                var v  = a.GetName().Version;
                var vs = v.ToString(3);

                if (v.Revision > 0)
                {
                    this.VersionString = $"{vs}, CI build {v.Revision}";
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes this Discord API client.
 /// </summary>
 /// <param name="config">Configuration for this client.</param>
 protected BaseDiscordClient(DiscordConfiguration config)
 {
     this.Configuration = config;
     this.ApiClient     = new DiscordApiClient(this);
     this.DebugLogger   = new DebugLogger(this);
     this.UserCache     = new ConcurrentDictionary <ulong, DiscordUser>();
 }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes this Discord API client.
 /// </summary>
 /// <param name="config">Configuration for this client.</param>
 protected BaseDiscordClient(DiscordConfiguration config)
 {
     Configuration        = new DiscordConfiguration(config);
     ApiClient            = new DiscordApiClient(this);
     DebugLogger          = new DebugLogger(this);
     UserCache            = new ConcurrentDictionary <ulong, DiscordUser>();
     InternalVoiceRegions = new ConcurrentDictionary <string, DiscordVoiceRegion>();
     _voice_regions_lazy  = new Lazy <IReadOnlyDictionary <string, DiscordVoiceRegion> >(() => new ReadOnlyDictionary <string, DiscordVoiceRegion>(InternalVoiceRegions));
 }
Exemplo n.º 6
0
        public DiscordRestClient(DiscordConfiguration config) : base(config)
        {
            disposed = false;
            var gs = ApiClient.GetCurrentUserGuildsAsync(100, null, null).GetAwaiter().GetResult();

            _guilds = new Dictionary <ulong, DiscordGuild>();
            foreach (DiscordGuild g in gs)
            {
                _guilds[g.Id] = g;
            }
        }
Exemplo n.º 7
0
        public DiscordRestClient(DiscordConfiguration config) : base(config)
        {
            disposed = false;

            _guilds_lazy = new Lazy <IReadOnlyDictionary <ulong, DiscordGuild> >(() => new ReadOnlyDictionary <ulong, DiscordGuild>(_guilds));

            var gs = ApiClient.GetCurrentUserGuildsAsync(100, null, null).ConfigureAwait(false).GetAwaiter().GetResult();

            foreach (DiscordGuild g in gs)
            {
                _guilds[g.Id] = g;
            }
        }
Exemplo n.º 8
0
        internal static string GetFormattedToken(DiscordConfiguration config)
        {
            switch (config.TokenType)
            {
            case TokenType.Bearer:
                return($"Bearer {config.Token}");

            case TokenType.Bot:
                return($"Bot {config.Token}");

            default:
                throw new ArgumentException("Invalid token type specified.", nameof(config.Token));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes new auto-sharding Discord client.
        /// </summary>
        /// <param name="config">Configuration to use.</param>
        public DiscordShardedClient(DiscordConfiguration config)
        {
            this.InternalSetup();

            this.Configuration = config;
            this.ShardClients  = new ReadOnlyConcurrentDictionary <int, DiscordClient>(this._shards);

            if (this.Configuration.LoggerFactory == null)
            {
                this.Configuration.LoggerFactory = new DefaultLoggerFactory();
                this.Configuration.LoggerFactory.AddProvider(new DefaultLoggerProvider(this.Configuration.MinimumLogLevel, this.Configuration.LogTimestampFormat));
            }
            this.Logger = this.Configuration.LoggerFactory.CreateLogger <BaseDiscordClient>();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of DiscordClient.
        /// </summary>
        /// <param name="config">Specifies configuration parameters.</param>
        public DiscordClient(DiscordConfiguration config)
            : base(config)
        {
            if (this.Configuration.MessageCacheSize > 0)
            {
                var intents = this.Configuration.Intents;
                this.MessageCache = intents.HasIntent(DiscordIntents.GuildMessages) || intents.HasIntent(DiscordIntents.DirectMessages)
                        ? new RingBuffer <DiscordMessage>(this.Configuration.MessageCacheSize)
                        : null;
            }

            this.InternalSetup();

            this.Guilds          = new ReadOnlyConcurrentDictionary <ulong, DiscordGuild>(this._guilds);
            this.PrivateChannels = new ReadOnlyConcurrentDictionary <ulong, DiscordDmChannel>(this._privateChannels);
        }
Exemplo n.º 11
0
        internal static string GetFormattedToken(DiscordConfiguration config)
        {
            switch (config.TokenType)
            {
            case TokenType.Bearer:
            {
                return($"Bearer {config.Token}");
            }

            case TokenType.Bot:
            {
                return($"Bot {config.Token}");
            }

            default:
            {
                return(config.Token);
            }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of DiscordClient.
        /// </summary>
        /// <param name="config">Specifies configuration parameters.</param>
        public DiscordClient(DiscordConfiguration config)
            : base(config)
        {
            if (this.Configuration.MessageCacheSize > 0)
            {
                var intents = this.Configuration.Intents;

                if (intents.HasValue)
                {
                    this.MessageCache = intents.Value.HasIntent(DiscordIntents.GuildMessages) || intents.Value.HasIntent(DiscordIntents.DirectMessages)
                        ? new RingBuffer <DiscordMessage>(this.Configuration.MessageCacheSize)
                        : null;
                }
                else
                {
                    this.MessageCache = new RingBuffer <DiscordMessage>(this.Configuration.MessageCacheSize); //This will need to be changed once intents become mandatory.
                }
            }

            this.InternalSetup();

            this.Guilds          = new ReadOnlyConcurrentDictionary <ulong, DiscordGuild>(this._guilds);
            this.PrivateChannels = new ReadOnlyConcurrentDictionary <ulong, DiscordDmChannel>(this._privateChannels);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes new auto-sharding Discord client.
        /// </summary>
        /// <param name="config">Configuration to use.</param>
        public DiscordShardedClient(DiscordConfiguration config)
        {
            if (config.TokenType == TokenType.User)
            {
                throw new InvalidOperationException("You cannot shard using a user token.");
            }

            this._clientErrored            = new AsyncEvent <ClientErrorEventArgs>(this.Goof, "CLIENT_ERRORED");
            this._socketErrored            = new AsyncEvent <SocketErrorEventArgs>(this.Goof, "SOCKET_ERRORED");
            this._socketOpened             = new AsyncEvent(this.EventErrorHandler, "SOCKET_OPENED");
            this._socketClosed             = new AsyncEvent <SocketCloseEventArgs>(this.EventErrorHandler, "SOCKET_CLOSED");
            this._ready                    = new AsyncEvent <ReadyEventArgs>(this.EventErrorHandler, "READY");
            this._resumed                  = new AsyncEvent <ReadyEventArgs>(this.EventErrorHandler, "RESUMED");
            this._channelCreated           = new AsyncEvent <ChannelCreateEventArgs>(this.EventErrorHandler, "CHANNEL_CREATED");
            this._dmChannelCreated         = new AsyncEvent <DmChannelCreateEventArgs>(this.EventErrorHandler, "DM_CHANNEL_CREATED");
            this._channelUpdated           = new AsyncEvent <ChannelUpdateEventArgs>(this.EventErrorHandler, "CHANNEL_UPDATED");
            this._channelDeleted           = new AsyncEvent <ChannelDeleteEventArgs>(this.EventErrorHandler, "CHANNEL_DELETED");
            this._dmChannelDeleted         = new AsyncEvent <DmChannelDeleteEventArgs>(this.EventErrorHandler, "DM_CHANNEL_DELETED");
            this._channelPinsUpdated       = new AsyncEvent <ChannelPinsUpdateEventArgs>(this.EventErrorHandler, "CHANNEL_PINS_UPDATED");
            this._guildCreated             = new AsyncEvent <GuildCreateEventArgs>(this.EventErrorHandler, "GUILD_CREATED");
            this._guildAvailable           = new AsyncEvent <GuildCreateEventArgs>(this.EventErrorHandler, "GUILD_AVAILABLE");
            this._guildUpdated             = new AsyncEvent <GuildUpdateEventArgs>(this.EventErrorHandler, "GUILD_UPDATED");
            this._guildDeleted             = new AsyncEvent <GuildDeleteEventArgs>(this.EventErrorHandler, "GUILD_DELETED");
            this._guildUnavailable         = new AsyncEvent <GuildDeleteEventArgs>(this.EventErrorHandler, "GUILD_UNAVAILABLE");
            this._guildDownloadCompleted   = new AsyncEvent <GuildDownloadCompletedEventArgs>(this.EventErrorHandler, "GUILD_DOWNLOAD_COMPLETED");
            this._messageCreated           = new AsyncEvent <MessageCreateEventArgs>(this.EventErrorHandler, "MESSAGE_CREATED");
            this._presenceUpdated          = new AsyncEvent <PresenceUpdateEventArgs>(this.EventErrorHandler, "PRESENCE_UPDATED");
            this._guildBanAdded            = new AsyncEvent <GuildBanAddEventArgs>(this.EventErrorHandler, "GUILD_BAN_ADDED");
            this._guildBanRemoved          = new AsyncEvent <GuildBanRemoveEventArgs>(this.EventErrorHandler, "GUILD_BAN_REMOVED");
            this._guildEmojisUpdated       = new AsyncEvent <GuildEmojisUpdateEventArgs>(this.EventErrorHandler, "GUILD_EMOJI_UPDATED");
            this._guildIntegrationsUpdated = new AsyncEvent <GuildIntegrationsUpdateEventArgs>(this.EventErrorHandler, "GUILD_INTEGRATIONS_UPDATED");
            this._guildMemberAdded         = new AsyncEvent <GuildMemberAddEventArgs>(this.EventErrorHandler, "GUILD_MEMBER_ADDED");
            this._guildMemberRemoved       = new AsyncEvent <GuildMemberRemoveEventArgs>(this.EventErrorHandler, "GUILD_MEMBER_REMOVED");
            this._guildMemberUpdated       = new AsyncEvent <GuildMemberUpdateEventArgs>(this.EventErrorHandler, "GUILD_MEMBER_UPDATED");
            this._guildRoleCreated         = new AsyncEvent <GuildRoleCreateEventArgs>(this.EventErrorHandler, "GUILD_ROLE_CREATED");
            this._guildRoleUpdated         = new AsyncEvent <GuildRoleUpdateEventArgs>(this.EventErrorHandler, "GUILD_ROLE_UPDATED");
            this._guildRoleDeleted         = new AsyncEvent <GuildRoleDeleteEventArgs>(this.EventErrorHandler, "GUILD_ROLE_DELETED");
            this._messageUpdated           = new AsyncEvent <MessageUpdateEventArgs>(this.EventErrorHandler, "MESSAGE_UPDATED");
            this._messageDeleted           = new AsyncEvent <MessageDeleteEventArgs>(this.EventErrorHandler, "MESSAGE_DELETED");
            this._messageBulkDeleted       = new AsyncEvent <MessageBulkDeleteEventArgs>(this.EventErrorHandler, "MESSAGE_BULK_DELETED");
            this._typingStarted            = new AsyncEvent <TypingStartEventArgs>(this.EventErrorHandler, "TYPING_STARTED");
            this._userSettingsUpdated      = new AsyncEvent <UserSettingsUpdateEventArgs>(this.EventErrorHandler, "USER_SETTINGS_UPDATED");
            this._userUpdated              = new AsyncEvent <UserUpdateEventArgs>(this.EventErrorHandler, "USER_UPDATED");
            this._voiceStateUpdated        = new AsyncEvent <VoiceStateUpdateEventArgs>(this.EventErrorHandler, "VOICE_STATE_UPDATED");
            this._voiceServerUpdated       = new AsyncEvent <VoiceServerUpdateEventArgs>(this.EventErrorHandler, "VOICE_SERVER_UPDATED");
            this._guildMembersChunk        = new AsyncEvent <GuildMembersChunkEventArgs>(this.EventErrorHandler, "GUILD_MEMBERS_CHUNKED");
            this._unknownEvent             = new AsyncEvent <UnknownEventArgs>(this.EventErrorHandler, "UNKNOWN_EVENT");
            this._messageReactionAdded     = new AsyncEvent <MessageReactionAddEventArgs>(this.EventErrorHandler, "MESSAGE_REACTION_ADDED");
            this._messageReactionRemoved   = new AsyncEvent <MessageReactionRemoveEventArgs>(this.EventErrorHandler, "MESSAGE_REACTION_REMOVED");
            this._messageReactionsCleared  = new AsyncEvent <MessageReactionsClearEventArgs>(this.EventErrorHandler, "MESSAGE_REACTIONS_CLEARED");
            this._webhooksUpdated          = new AsyncEvent <WebhooksUpdateEventArgs>(this.EventErrorHandler, "WEBHOOKS_UPDATED");
            this._heartbeated              = new AsyncEvent <HeartbeatEventArgs>(this.EventErrorHandler, "HEARTBEATED");

            this.Config      = config;
            this.Shards      = new ConcurrentDictionary <int, DiscordClient>();
            this.DebugLogger = new DebugLogger(config.LogLevel, config.DateTimeFormat);

            if (config.UseInternalLogHandler)
            {
                DebugLogger.LogMessageReceived += (sender, e) => DebugLogger.LogHandler(sender, e);
            }
        }
Exemplo n.º 14
0
 public DiscordRestClient(DiscordConfiguration config) : base(config)
 {
     disposed = false;
 }
Exemplo n.º 15
0
 /// <summary>
 /// Initializes this Discord API client.
 /// </summary>
 /// <param name="config">Configuration for this client.</param>
 protected BaseDiscordClient(DiscordConfiguration config)
 {
     this.Configuration = config;
     this.ApiClient     = new DiscordApiClient(this);
     this.DebugLogger   = new DebugLogger(this);
 }