Beispiel #1
0
        public WebSocket(DiscordConfig config, JsonSerializer serializer, Logger logger)
        {
            _config = config;
            _serializer = serializer;
            Logger = logger;

            _lock = new AsyncLock();
            _taskManager = new TaskManager(Cleanup);
            CancelToken = new CancellationToken(true);
            _connectedEvent = new ManualResetEventSlim(false);

#if !NETSTANDARD1_3
            _engine = new WS4NetEngine(config, _taskManager);
#else
            _engine = new BuiltInEngine(config);
#endif
            _engine.BinaryMessage += (s, e) =>
            {
                using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
                using (var decompressed = new MemoryStream())
                {
                    using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
                        zlib.CopyTo(decompressed);
                    decompressed.Position = 0;
                    using (var reader = new StreamReader(decompressed))
                        ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult();
                }
            };
            _engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait();
        }
        public AudioClient(DiscordClient client, Server server, int id)
		{
            Id = id;
            _config = client.Config;
            Service = client.Services.Get<AudioService>();
            Config = Service.Config;
            Serializer = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken = new CancellationToken(true);

            //Networking
            if (Config.EnableMultiserver)
            {
                ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}"));
                GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}"));
                GatewaySocket.Connected += (s, e) =>
                {
                    if (_gatewayState == ConnectionState.Connecting)
                        EndGatewayConnect();
                };
            }
            else
                GatewaySocket = client.GatewaySocket;
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream = new OutStream(this);
        }
 internal WS4NetEngine(DiscordConfig config, TaskManager taskManager)
 {
     _config = config;
     _taskManager = taskManager;
     _sendQueue = new ConcurrentQueue<string>();
     _waitUntilConnect = new ManualResetEventSlim();
     _waitUntilDisconnect = new ManualResetEventSlim(true);
 }
Beispiel #4
0
        public AudioClient(DiscordClient client, Server server, int id)
        {
            Id            = id;
            Service       = client.GetService <AudioService>();
            Config        = Service.Config;
            Serializer    = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager    = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken     = new CancellationToken(true);

            //Networking
            if (Config.EnableMultiserver)
            {
                //TODO: We can remove this hack when official API launches
                var baseConfig = client.Config;
                var builder    = new DiscordConfigBuilder
                {
                    AppName               = baseConfig.AppName,
                    AppUrl                = baseConfig.AppUrl,
                    AppVersion            = baseConfig.AppVersion,
                    CacheToken            = baseConfig.CacheDir != null,
                    ConnectionTimeout     = baseConfig.ConnectionTimeout,
                    EnablePreUpdateEvents = false,
                    FailedReconnectDelay  = baseConfig.FailedReconnectDelay,
                    LargeThreshold        = 1,
                    LogLevel              = baseConfig.LogLevel,
                    MessageCacheSize      = 0,
                    ReconnectDelay        = baseConfig.ReconnectDelay,
                    UsePermissionsCache   = false
                };
                _config = builder.Build();

                ClientAPI                = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}"));
                GatewaySocket            = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}"));
                GatewaySocket.Connected += (s, e) =>
                {
                    if (_gatewayState == ConnectionState.Connecting)
                    {
                        EndGatewayConnect();
                    }
                };
            }
            else
            {
                _config       = client.Config;
                GatewaySocket = client.GatewaySocket;
            }
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket        = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream       = new OutStream(this);
        }
Beispiel #5
0
        private async Task Run(string[] args)
        {
            /*
             * var cfg = new C3POBotConfig();
             * var json = string.Empty;
             * if (!File.Exists("config.json"))
             * {
             *  json = JsonConvert.SerializeObject(cfg);
             *  File.WriteAllText("config.json", json, new UTF8Encoding(false));
             *  Console.WriteLine("Config file was not found, a new one was generated. Fill it with proper values and rerun this program");
             *  Console.ReadKey();
             *
             *  return;
             * }
             *
             * json = File.ReadAllText("config.json", new UTF8Encoding(false));
             * cfg = JsonConvert.DeserializeObject<C3POBotConfig>(json);
             *
             * var tskl = new List<Task>();
             * for (var i = 0; i < cfg.ShardCount; i++)
             * {
             *  var bot = new C3POBot(cfg, i);
             *  tskl.Add(bot.RunAsync());
             *  await Task.Delay(7500);
             * }
             *
             * await Task.WhenAll(tskl);
             */
            var dcfg = new DiscordConfig
            {
                AutoReconnect         = true,
                DiscordBranch         = Branch.Stable,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Unnecessary,
                Token                 = "MzEyNDkwMzU4MTI5MDMzMjE3.C_b06A.dwytB2wEycnwI2slNToh3uKkZpg",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false
            };
            var bot = new DiscordShardedClient(dcfg);

            bot.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;
            await bot.StartAsync();

            bot.UseInteractivity();
            var modules = bot.UseCommandsNext(new CommandsNextConfiguration {
                Prefix = "#"
            });

            foreach (var m in modules.Values)
            {
                m.RegisterCommands <C3POBotCommands>();
                m.RegisterCommands <C3POBotNextCommands>();
                m.RegisterCommands <C3POBotEvalCommands>();
            }

            await Task.Delay(-1);
        }
Beispiel #6
0
        void ApplyDiscordProps()
        {
            DiscordConfig cfg = DiscordPlugin.Config;

            cfg.Enabled    = dis_chkEnabled.Checked;
            cfg.BotToken   = dis_txtToken.Text;
            cfg.Channels   = dis_txtChannel.Text;
            cfg.OpChannels = dis_txtOpChannel.Text;
        }
        public GatewaySocket(DiscordConfig config, JsonSerializer serializer, Logger logger)
			: base(config, serializer, logger)
		{
			Disconnected += async (s, e) =>
			{
				if (e.WasUnexpected)
					await Reconnect().ConfigureAwait(false);
			};
		}
Beispiel #8
0
        void LoadDiscordProps()
        {
            DiscordConfig cfg = DiscordPlugin.Config;

            dis_chkEnabled.Checked = cfg.Enabled;
            dis_txtToken.Text      = cfg.BotToken;
            dis_txtChannel.Text    = cfg.Channels;
            dis_txtOpChannel.Text  = cfg.OpChannels;
            ToggleDiscordSettings(cfg.Enabled);
        }
Beispiel #9
0
 public static IEnumerable <Discord.Models.Webhook> GetWebhooks(this DiscordConfig config, params string[] webhookNames)
 {
     if (webhookNames != null && webhookNames.Length > 0)
     {
         return(config.Webhooks?.Where(i => webhookNames.Contains(i.Name, StringComparer.InvariantCultureIgnoreCase)));
     }
     else
     {
         return(config.Webhooks);
     }
 }
Beispiel #10
0
        public RestClient(DiscordConfig config, string baseUrl, Logger logger)
        {
            _config = config;
            Logger  = logger;

#if !DOTNET5_4
            _engine = new RestSharpEngine(config, baseUrl, logger);
#else
            _engine = new BuiltInEngine(config, baseUrl, logger);
#endif
        }
 internal VoiceSocket(DiscordConfig config, AudioServiceConfig audioConfig, JsonSerializer serializer, Logger logger)
     : base(config, serializer, logger)
 {
     _audioConfig = audioConfig;
     _decoders = new ConcurrentDictionary<uint, OpusDecoder>();
     _targetAudioBufferLength = _audioConfig.BufferLength / 20; //20 ms frames
     _encodingBuffer = new byte[MaxOpusSize];
     _ssrcMapping = new ConcurrentDictionary<uint, ulong>();
     _encoder = new OpusEncoder(48000, _audioConfig.Channels, 20, _audioConfig.Bitrate, OpusApplication.MusicOrMixed);
     _sendBuffer = new VoiceBuffer((int)Math.Ceiling(_audioConfig.BufferLength / (double)_encoder.FrameLength), _encoder.FrameSize);
 }
 public GatewaySocket(DiscordConfig config, JsonSerializer serializer, Logger logger)
     : base(config, serializer, logger)
 {
     Disconnected += async(s, e) =>
     {
         if (e.WasUnexpected)
         {
             await Reconnect().ConfigureAwait(false);
         }
     };
 }
Beispiel #13
0
 internal VoiceSocket(DiscordConfig config, AudioServiceConfig audioConfig, JsonSerializer serializer, Logger logger)
     : base(config, serializer, logger)
 {
     _audioConfig             = audioConfig;
     _decoders                = new ConcurrentDictionary <uint, OpusDecoder>();
     _targetAudioBufferLength = _audioConfig.BufferLength / 20; //20 ms frames
     _encodingBuffer          = new byte[MaxOpusSize];
     _ssrcMapping             = new ConcurrentDictionary <uint, ulong>();
     _encoder    = new OpusEncoder(48000, _audioConfig.Channels, 20, _audioConfig.Bitrate, OpusApplication.MusicOrMixed);
     _sendBuffer = new VoiceBuffer((int)Math.Ceiling(_audioConfig.BufferLength / (double)_encoder.FrameLength), _encoder.FrameSize);
 }
Beispiel #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.Configure <UserSecrets>(Configuration.GetSection(nameof(UserSecrets)));
            var secrets = Configuration.GetSection(nameof(UserSecrets)).Get <UserSecrets>();

            services.Configure <ConnectedClientSettings>(Configuration.GetSection("ChatClients"));

            // Injected into ChatClients by DI for Hangfire scheduled actions
            var slackConfig = new SlackConfig
            {
                ApiKey         = secrets.SlackApiKey,
                DefaultChannel = Configuration["ChatClients:SlackDefaultChannel"],
            };
            var discordConfig = new DiscordConfig
            {
                DiscordToken   = secrets.DiscordToken,
                DefaultChannel = Configuration["ChatClients:DiscordDefaultChannel"],
            };
            var twitchConfig = new TwitchConfig {
                Username = secrets.TwitchUsername,
                Token    = secrets.TwitchToken,
                Channel  = secrets.TwitchChannel,
            };

            services.AddSingleton(slackConfig);
            services.AddSingleton(discordConfig);
            services.AddSingleton(twitchConfig);

            services.AddSingleton <IConnectedClients, ConnectedClients>();
            services.AddSingleton <IBotSettings, BotSettings>();
            services.AddSingleton <IBotClient, BotGraphClient>();

            services.AddHangfire(x => x.UseSqlServerStorage(secrets.DatabaseConnectionString));

            services.AddDbContext <AppDataContext>(options =>
                                                   options.UseSqlServer(secrets.DatabaseConnectionString));

            services.AddScoped <IRepository, EntityFrameworkRepository>();
            services.AddSingleton <IActionScheduler, HangfireActionScheduler>();
            services.AddSingleton <IAnswerSearchEngine, AnswerSearch>();
            services.AddSingleton <IBot, Core.Bot>();

            RegisterGraphQL.Configure(services, _env);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Beispiel #15
0
        public JsonRestClient(DiscordConfig config, string baseUrl, ILogger logger = null)
            : base(config, baseUrl, logger)
        {
            _serializer = new JsonSerializer();
#if TEST_RESPONSES
            _serializer.CheckAdditionalContent = true;
            _serializer.MissingMemberHandling  = MissingMemberHandling.Error;
#else
            _serializer.CheckAdditionalContent = false;
            _serializer.MissingMemberHandling  = MissingMemberHandling.Ignore;
#endif
        }
Beispiel #16
0
        public void GetDiscordConfigTest_2()
        {
            try
            {
                DiscordConfig discord = Config.GetDiscordConfig(configLines, 6);
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.Fail();
        }
Beispiel #17
0
    public static async Task Main()
    {
        DiscordConfig config = await GetConfig <DiscordConfig>();

        prod   = config.Production;
        UBIKey = config.JacobUBIKey;

        platform = Platform.Discord;

        await Bot.RunAsync(config.Token, config.Prefix);

        await Task.Delay(-1);
    }
Beispiel #18
0
        public void GetDiscordConfigTest_5()
        {
            try
            {
                DiscordConfig discord = Config.GetDiscordConfig(null, 7);
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.Fail();
        }
Beispiel #19
0
        public void GetDiscordConfigTest_3()
        {
            try
            {
                DiscordConfig discord = Config.GetDiscordConfig(configLines, -1);
            }
            catch (IndexOutOfRangeException)
            {
                return;
            }

            Assert.Fail();
        }
        public DiscordClient(string token)
        {
            var cfg = new DiscordConfig
            {
                Token     = token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            this.Client = new DSharpPlus.DiscordClient(cfg);
        }
        public async Task RunBotAsync()
        {
            // first, let's load our configuration file
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            // next, let's load the values from that file
            // to our client's configuration
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfig
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            // then we want to instantiate our client
            this.Client = new DiscordClient(cfg);

            // If you are on Windows 7, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetClient>();

            // If you are using Mono, install
            // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocketSharpClient>();

            // next, let's hook some events, so we know
            // what's going on
            this.Client.Ready          += this.Client_Ready;
            this.Client.GuildAvailable += this.Client_GuildAvailable;
            this.Client.ClientError    += this.Client_ClientError;

            // finnaly, let's connect and log in
            await this.Client.ConnectAsync();

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
        public async Task RunBotAsync()
        {
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfig
            {
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                Token                 = cfgjson.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            };

            this.Client = new DiscordClient(cfg);

            this.Client.Ready          += this.Client_Ready;
            this.Client.GuildAvailable += this.Client_GuildAvailable;
            this.Client.ClientError    += this.Client_ClientError;

            var ccfg = new CommandsNextConfiguration
            {
                // let's use the string prefix defined in config.json
                StringPrefix = cfgjson.CommandPrefix,

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            this.Commands = this.Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            this.Commands.CommandExecuted += this.Commands_CommandExecuted;
            this.Commands.CommandErrored  += this.Commands_CommandErrored;

            this.Commands.RegisterCommands <Commandes>();

            await this.Client.ConnectAsync();

            await Task.Delay(-1);
        }
Beispiel #23
0
        public static void EmbedReport(DiscordBot disc, string type, string title, string duration, string reason)
        {
            ChannelSendEmbed embed  = new ChannelSendEmbed(discordChannelID);
            DiscordConfig    config = DiscordPlugin.Config;

            embed.Color = Int32.Parse(embedColour);
            embed.Title = title;
            if (type == "frozen" || type == "temp-banned")
            {
                embed.Fields.Add("Duration", duration);
            }
            embed.Fields.Add("Reason", reason);

            disc.Send(embed);
        }
Beispiel #24
0
        public void GetDiscordConfigTest_1()
        {
            DiscordConfig discord = null;

            try
            {
                discord = Config.GetDiscordConfig(configLines, 7);
            }
            catch
            {
                Assert.Fail();
            }

            Assert.IsTrue(discord != null && discord.Token == "12345678abcdef");
        }
Beispiel #25
0
        protected RestClient(DiscordConfig config, string baseUrl, ILogger logger = null)
        {
            _config = config;
            _logger = logger;

#if !NETSTANDARD1_3
            _engine = new RestSharpEngine(config, baseUrl, logger);
#else
            _engine = new BuiltInEngine(config, baseUrl, logger);
#endif

            if (logger != null && logger.Level >= LogSeverity.Verbose)
            {
                SentRequest += (s, e) => _logger.Verbose($"{e.Request.Method} {e.Request.Endpoint}: {e.Milliseconds} ms");
            }
        }
Beispiel #26
0
        public BuiltInEngine(DiscordConfig config, string baseUrl, ILogger logger)
        {
            _config  = config;
            _baseUrl = baseUrl;
            _logger  = logger;

            _rateLimitLock = new AsyncLock();
            _client        = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                UseCookies             = false,
                UseProxy = false
            });
            _client.DefaultRequestHeaders.Add("accept", "*/*");
            _client.DefaultRequestHeaders.Add("accept-encoding", "gzip,deflate");
            _client.DefaultRequestHeaders.Add("user-agent", config.UserAgent);
        }
Beispiel #27
0
        public BuiltInEngine(DiscordConfig config, string baseUrl, ILogger logger)
		{
			_config = config;
            _baseUrl = baseUrl;
            _logger = logger;

            _rateLimitLock = new AsyncLock();
            _client = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                UseCookies = false,
                UseProxy = false
            });
            _client.DefaultRequestHeaders.Add("accept", "*/*");
            _client.DefaultRequestHeaders.Add("accept-encoding", "gzip,deflate");
            _client.DefaultRequestHeaders.Add("user-agent", config.UserAgent);
        }
        public RestSharpEngine(DiscordConfig config, string baseUrl, Logger logger)
		{
			_config = config;
            Logger = logger;

            _rateLimitLock = new AsyncLock();
            _client = new RestSharpClient(baseUrl)
			{
				PreAuthenticate = false,
				ReadWriteTimeout = _config.RestTimeout,
				UserAgent = config.UserAgent
            };
			_client.Proxy = null;
            _client.RemoveDefaultParameter("Accept");
            _client.AddDefaultHeader("accept", "*/*");
			_client.AddDefaultHeader("accept-encoding", "gzip,deflate");
        }
Beispiel #29
0
        public RestSharpEngine(DiscordConfig config, string baseUrl, ILogger logger)
        {
            _config = config;
            _logger = logger;

            _rateLimitLock = new AsyncLock();
            _client        = new RestSharpClient(baseUrl)
            {
                PreAuthenticate  = false,
                ReadWriteTimeout = DiscordConfig.RestTimeout,
                UserAgent        = config.UserAgent
            };
            _client.Proxy = null;
            _client.RemoveDefaultParameter("Accept");
            _client.AddDefaultHeader("accept", "*/*");
            _client.AddDefaultHeader("accept-encoding", "gzip,deflate");
        }
Beispiel #30
0
        public async Task RunBot()
        {
            var json    = JsonManager.ParseJsonAsync("Config/config.json").Result;
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfig
            {
                Token = cfgjson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Info,
                UseInternalLogHandler = true
            };

            var ccfg = new CommandsNextConfiguration
            {
                StringPrefix = cfgjson.Prefix, EnableDms = true, EnableMentionPrefix = true
            };

            Client              = new DiscordClient(cfg);
            this.Commands       = Client.UseCommandsNext(ccfg);
            this.EventManager   = new EventManager(cfgjson.Prefix);
            this.CommandManager = new CommandManager();

            Client.UseInteractivity();

            Client.Ready          += this.EventManager.Ready;
            Client.ClientError    += this.EventManager.ClientError;
            Client.MessageCreated += this.EventManager.OnMessage;
            Client.SocketError    += this.EventManager.SocketError;

            Client.GuildMemberAdd += this.EventManager.GuildMemberAdd;

            this.Commands.CommandExecuted += this.CommandManager.CommandExecuted;
            this.Commands.CommandErrored  += this.CommandManager.CommandError;

            this.Commands.RegisterCommands <CommandManager>();
            this.Commands.RegisterCommands <SuperCommands>();
            this.Commands.RegisterCommands <AdminCommands>();
            this.Commands.RegisterCommands <MemberCommands>();
            this.Commands.RegisterCommands <GeneralCommands>();
            this.Commands.RegisterCommands <HighscoreCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Beispiel #31
0
        public WebSocket(DiscordConfig config, JsonSerializer serializer, Logger logger
#if WINDOWS_UWP
                         , IWebSocketEngine customSocket
#endif
                         )
        {
            _config     = config;
            _serializer = serializer;
            Logger      = logger;

            _lock           = new AsyncLock();
            _taskManager    = new TaskManager(Cleanup);
            CancelToken     = new CancellationToken(true);
            _connectedEvent = new ManualResetEventSlim(false);

#if !NETSTANDARD1_3
            _engine = new WS4NetEngine(config, _taskManager);
#elif WINDOWS_UWP
            if (customSocket != null)
            {
                _engine = customSocket;
            }
            else
            {
                _engine = new BuiltInEngine(config);
            }
#else
            _engine = new BuiltInEngine(config);
#endif
            _engine.BinaryMessage += (s, e) =>
            {
                using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
                    using (var decompressed = new MemoryStream())
                    {
                        using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
                            zlib.CopyTo(decompressed);
                        decompressed.Position = 0;
                        using (var reader = new StreamReader(decompressed))
                            ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult();
                    }
            };
            _engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait();
        }
Beispiel #32
0
        public AudioClient(DiscordClient client, Server server, int id)
        {
            Id            = id;
            _config       = client.Config;
            Service       = client.Services.Get <AudioService>();
            Config        = Service.Config;
            Serializer    = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager    = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken     = new CancellationToken(true);

            //Networking
            if (Config.EnableMultiserver)
            {
                ClientAPI                = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}"));
                GatewaySocket            = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}"));
                GatewaySocket.Connected += (s, e) =>
                {
                    if (_gatewayState == ConnectionState.Connecting)
                    {
                        EndGatewayConnect();
                    }
                };
            }
            else
            {
                GatewaySocket = client.GatewaySocket;
            }
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket        = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream       = new OutStream(this);
        }
Beispiel #33
0
        public async Task Run()
        {
            var savage_config = new DiscordConfig
            {
                AutoReconnect         = true,
                DiscordBranch         = Branch.Stable,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Info,
                Token                 = "",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false
            };

            this.Client = new DiscordClient(savage_config);

            var CommandConfig = new CommandsNextConfiguration
            {
                StringPrefix = "#",

                EnableMentionPrefix = true,

                EnableDms = false
            };

            this.Commands = this.Client.UseCommandsNext(CommandConfig);

            this.Commands.RegisterCommands <Commands_Base>();

            this.Commands.RegisterCommands <Commands_Admin>();

            var discord_conn = new DiscordConnection();

            this.Client.SetWebSocketClient <WebSocket4NetClient>();

            await this.Client.ConnectAsync();

            await Task.Delay(-1);
        }
        public BucketDiscordClient(DiscordConfig config)
        {
            _wrapped = config != null
                ? new DiscordClient(config)
                : new DiscordClient();

            OnReady = Observable.FromEventPattern(h => _wrapped.Ready += h, h => _wrapped.Ready -= h);

            OnMessageReceived = Observable.FromEventPattern <MessageEventArgs>(h => _wrapped.MessageReceived += h,
                                                                               h => _wrapped.MessageReceived -= h).Select(o => o.EventArgs);

            OnServerJoined =
                Observable.FromEventPattern <ServerEventArgs>(h => _wrapped.JoinedServer += h,
                                                              h => _wrapped.JoinedServer -= h).Select(o => o.EventArgs);

            OnUserJoined =
                Observable.FromEventPattern <UserEventArgs>(h => _wrapped.UserJoined += h, h => _wrapped.UserJoined -= h)
                .Select(e => e.EventArgs);

            OnLogMessage =
                Observable.FromEventPattern <LogMessageEventArgs>(h => _wrapped.Log.Message += h,
                                                                  h => _wrapped.Log.Message -= h).Select(e => e.EventArgs);
        }
Beispiel #35
0
            public Config()
            {
                string botConfigPath = Path.Combine(TShock.SavePath, "discord_bot_config.json");

                if (File.Exists(botConfigPath))
                {
                    using (var reader = new StreamReader(botConfigPath))
                    {
                        string txt = reader.ReadToEnd();
                        BotConfig = JsonConvert.DeserializeObject <DiscordConfig>(txt);
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("{0} not found", botConfigPath));
                    BotConfig = new DiscordConfig()
                    {
                        DiscordAppToken = string.Empty,
                        DiscordBotName  = string.Empty,
                        DiscordCannelId = string.Empty
                    };
                }
            }
Beispiel #36
0
        /// <summary>
        /// Creates a new <see cref="DiscordBot"/> running the given <see cref="Command"/>s.
        /// </summary>
        /// <param name="token">The token of the bot.</param>
        /// <param name="commands">The <see cref="Command"/>s of the bot.</param>
        /// <param name="config">The <see cref="DiscordConfig"/> of the bot.</param>
        public DiscordBot(string token, IEnumerable <Command> commands, DiscordConfig config)
        {
            if (commands == null)
            {
                throw new ArgumentNullException(nameof(commands));
            }

            Parser = new CommandParser(commands);

            if (config != null)
            {
                Client = new DiscordClient(config);
            }
            else
            {
                Client = new DiscordClient();
            }

            Client.ExecuteAndWait(async() => {
                Client.MessageReceived += GotMessage;

                await Client.Connect(token, TokenType.Bot);
            });
        }
Beispiel #37
0
        public AudioClient(DiscordClient client, Server server, int id)
        {
            Id = id;
            Service = client.GetService<AudioService>();
            Config = Service.Config;
            Serializer = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken = new CancellationToken(true);

            //Networking
            _config = client.Config;
            GatewaySocket = client.GatewaySocket;
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream = new OutStream(this);
        }
Beispiel #38
0
        public AudioClient(DiscordClient client, Server server, int id)
        {
            Id            = id;
            Service       = client.GetService <AudioService>();
            Config        = Service.Config;
            Serializer    = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager    = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken     = new CancellationToken(true);

            //Networking
            _config       = client.Config;
            GatewaySocket = client.GatewaySocket;
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket        = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream       = new OutStream(this);
        }
 internal BuiltInEngine(DiscordConfig config)
 {
     _config = config;
     _sendQueue = new ConcurrentQueue<string>();
 }