public UserAccountRepositoryTests() { _iLogger = new Mock <Logger>(); _logger = new Mock <DiscordLogger>(_iLogger); _storage = new Mock <JsonStorage>(); // _userRepo = new Mock<UserAccountRepository>(_logger, _storage); }
public CommandHandler(DiscordSocketClient client, DiscordLogger logger, CommandService service, GamblingBotConfig config) { _client = client; _logger = logger; _service = service; _config = config; }
public UserEventsHandlerService(DiscordSocketClient client, DiscordLogger logger, DiscordBotConfig config, IUserAccountRepository userAccountRepository) { _userAccountRepository = userAccountRepository; _config = config; _client = client; _logger = logger; }
private async Task PullAvatarAsync(IGuildUser user) { try { string avatarURL = user.GetAvatarUrl(format: ImageFormat.Auto, 1024); if (avatarURL is null) { await Context.Message.Channel.SendMessageAsync($"{user.Mention} does not have a profile picture"); return; } var embed = new EmbedBuilder(); embed.WithColor(new Color(0, 204, 255)); embed.WithTitle($"{user.Username}'s avatar"); embed.WithUrl(avatarURL); embed.WithImageUrl(avatarURL); await Context.Channel.SendMessageAsync("", false, embed.Build()); } catch (Exception ex) { DiscordLogger.HandleExceptionQuietly($"{GetType().FullName}: {DiscordLogger.GetAsyncMethodName()}", ex); } }
static Task LogDiscord(LogMessage arg) { var text = arg.Message; switch (arg.Severity) { case LogSeverity.Critical: DiscordLogger.Write(LogEventLevel.Fatal, text); break; case LogSeverity.Error: DiscordLogger.Write(LogEventLevel.Error, text); break; case LogSeverity.Warning: DiscordLogger.Write(LogEventLevel.Warning, text); break; case LogSeverity.Info: DiscordLogger.Write(LogEventLevel.Information, text); break; case LogSeverity.Debug: DiscordLogger.Write(LogEventLevel.Debug, text); break; case LogSeverity.Verbose: default: DiscordLogger.Write(LogEventLevel.Verbose, text); break; } return(Task.CompletedTask); }
public BotConfigRepository(DiscordLogger logger, IDataStorage dataStorage, DiscordBotConfig config) { _logger = logger; _dataStorage = dataStorage; _config = config; LoadOrCreate(); }
public CommandHandlerService(DiscordSocketClient client, DiscordLogger logger, DiscordBotConfig config, CommandService service, IServiceProvider serviceProvider) { _config = config; _client = client; _logger = logger; _service = service; _serviceProvider = serviceProvider; }
public HamburgerDiscord(IDiscord hamburgerDiscord, DiscordLogger dislogger, ILogger logger, CommandHandler commandHandler, JoinHandler joinHandler) { _discord = hamburgerDiscord; _discordLogger = dislogger; _logger = logger; _commandHandler = commandHandler; _joinHandler = joinHandler; }
public ReadyHandler(IServiceProvider serviceProvider) : base(serviceProvider) { ApplicationContext.DiscordClient = client; discordLogger = services.GetService <DiscordLogger>(); activityCycler = services.GetService <ActivityCycler>(); client.Ready += HandleReady; }
public MessageHandlerService(DiscordSocketClient client, DiscordLogger logger, DiscordBotConfig config, LevelingService levelingService, IUserAccountRepository userRepo) { _config = config; _client = client; _logger = logger; _levelingService = levelingService; _userRepo = userRepo; _messagesList = new List <Message>(); }
public MiunieDiscord(IDiscord discord, DiscordLogger discordLogger, ILogWriter logger, CommandHandler commandHandler) { _discord = discord; _discordLogger = discordLogger; _logger = logger; _commandHandler = commandHandler; _connectionState = Core.Entities.ConnectionState.DISCONNECTED; }
private async Task RestartBot() { try { await Context.Channel.SendMessageAsync("Restarting bot", false); await Program.RestartBot(); } catch (Exception ex) { DiscordLogger.HandleExceptionQuietly($"{GetType().FullName}: {DiscordLogger.GetAsyncMethodName()}", ex); } }
public static async Task RestartBot() { try { _tokenSource.Cancel(); _tokenSource = null; await Main(); } catch (Exception ex) { await CommandWindowLogger.LogMessageAsync( new LogMessage(LogSeverity.Critical, DiscordLogger.GetAsyncMethodName(), ex.Message, ex)); } }
internal async Task ReadyProcedures() { try { await Domain.InitializeDomain(_client); await Domain.GetLogChannel().SendMessageAsync("Bot initialized"); } catch (Exception ex) { await CommandWindowLogger.LogMessageAsync( new LogMessage(LogSeverity.Critical, DiscordLogger.GetAsyncMethodName(), ex.Message, ex)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "TtsApi v1"); //Disable the "Try it out" button //c.SupportedSubmitMethods(Array.Empty<SubmitMethod>()); //This garbage doesn't work and therefore the authorization is lost after every reload. //Making swagger completely useless for this project. //c.ConfigObject.AdditionalItems.Add("persistAuthorization", "true"); }); app.UseExceptionHandler(appErr => appErr.Run(context => { context.Response.StatusCode = 500; IExceptionHandlerPathFeature exception = context.Features.Get <IExceptionHandlerPathFeature>(); DiscordLogger.LogException(exception.Error); return(null); } ) ); //app.UseHttpsRedirection(); //This breaks UseCors app.UseWebSockets(); app.UseCors(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHub <TtsHub>("/TtsHub", options => { // Not sure if we even need this // options.ApplicationMaxBufferSize = 30 * 1024; // * 1000; }); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public MessageHandler(IServiceProvider theServices, IOptions <AppSettings> appSettings) : base(theServices) { commands = services.GetService <CommandService>(); rateLimiter = services.GetService <UsageRateLimiter>(); discordLogger = services.GetService <DiscordLogger>(); responseService = services.GetService <ResponseService>(); lazyTowerBanManager = new Lazy <TowerBanManager>(() => services.GetService <TowerBanManager>()); testChannelId = appSettings.Value.Settings.DevelopmentGuild.Test; defaultCommandPrefix = services.GetScoppedSettings <AppSettings>().Settings.DefaultCommandPrefix; client.MessageReceived += HandleMessageAsync; commands.CommandExecuted += HandleCommandExecution; }
public async Task <IndexResponse> PostPlayer(PlayerSignupModel player) { var asyncIndexResponse = await client.IndexDocumentAsync(player); if (asyncIndexResponse.IsValid) { await DiscordLogger.PostMessageToDiscordAsync($"Signup data: Name: '{player.Name}' with Code: '{player.QuakeLoginCode}' and ID: '{player.QuakeId}' posted to elastic"); return(asyncIndexResponse); } else { await DiscordLogger.PostMessageToDiscordAsync($"Signup data: Name: '{player.Name}' with Code: '{player.QuakeLoginCode}' and ID: '{player.QuakeId}' NOT posted to elastic"); return(asyncIndexResponse); } }
public async Task <IndexResponse> PostMatch(MatchModel match) { var asyncIndexResponse = await client.IndexDocumentAsync(match); if (asyncIndexResponse.IsValid) { await DiscordLogger.PostMessageToDiscordAsync($"New match posted: Match date: '{match.MatchDate}' with '{match.MatchMVP}' as the MVP!"); return(asyncIndexResponse); } else { await DiscordLogger.PostMessageToDiscordAsync($"Match data: '{match.Id}' could NOT posted to elastic"); return(asyncIndexResponse); } }
private static ICommandHandler BuildCommandHandler(IServiceProvider provider, BotConfig config) { var logger = provider.GetService <ILogger <ICommandHandler> >(); var commandService = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync, SeparatorChar = ' ', LogLevel = config.LogLevel }); var discordLogger = new DiscordLogger <ICommandHandler>(logger); commandService.Log += discordLogger.OnLogAsync; var handler = ActivatorUtilities.CreateInstance(provider, typeof(CommandHandler), commandService) as ICommandHandler; return(handler); }
public async Task RunBotAsync() { var logger = new DiscordLogger <SocketDiscordBot>(_logger); _client.Ready += OnReadyAsync; _client.Log += logger.OnLogAsync; _client.LoggedOut += OnLoggedOutAsync; _client.Disconnected += OnDisconnected; await _behaviorService.InstallAsync(); try { await ConnectAsync(); } catch (Exception ex) { _logger.LogError(ex); throw; } }
public Connection(DiscordLogger logger, DiscordSocketClient client, IPlayersOnlineInfo playersOnlineInfo) { _logger = logger; _client = client; _playersOnlineInfo = playersOnlineInfo; }
public MiunieDiscord(IDiscord discord, DiscordLogger discordLogger, CommandServiceFactory cmdServiceFactory) { _discord = discord; _discord.Client.DebugLogger.LogMessageReceived += discordLogger.Log; cmdServiceFactory.Create(_discord.Client); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [Queue("outqueue"), StorageAccount("AzureWebJobsStorage")] ICollector <string> msg, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); // pull out body text string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); // deserialize //dynamic data = JsonConvert.DeserializeObject(requestBody); dynamic data = requestBody; // store message in data queue if (string.IsNullOrEmpty(data.ToString()) || string.IsNullOrWhiteSpace(data.ToString()) || data == null) { return(new BadRequestObjectResult("Your match stats payload was empty. Please send correct payload.")); } // Add a message to the output collection. msg.Add(data.ToString()); CrmodStatParser parser = null; try { parser = new CrmodStatParser(log); parser.SplitMatchStats(requestBody); parser.ProcessMatchInfo(); parser.ProcessTeamStats(); parser.ProcessPlayerStats(); parser.ProcessQuadStats(); parser.ProcessBadStats(); parser.ProcessEfficiencyStats(); parser.ProcessKillStats(); } catch (Exception e) { await DiscordLogger.PostMessageToDiscordAsync("Error parsing CRMOD match results payload. Error: " + e.Message); return(new BadRequestObjectResult("Unable to parse CRMOD match results payload. Error: " + e.Message)); } var esClient = new ElasticService(); // some horrible stuff going on here. I'm lazy to fix it but the purpose is to make the elastic->javascript parsing much easier... for my brain. var matchToPost = mapToMatchModel(parser.MatchResults); // Post match data in entirety to elastic var asyncMatchIndexResponse = await esClient.PostMatch(matchToPost); if (asyncMatchIndexResponse.IsValid) { log.LogInformation($"Match data: '{parser.MatchResults.Id}' posted to elastic"); } else { log.LogError($"Match data: '{parser.MatchResults.Id}' could NOT be posted to elastic"); } // upload all player stats foreach (var player in parser.MatchResults.ListOfPlayers) { if (int.TryParse(player.Key, out int statId)) { if (statId > 0) { var asyncPlayerIndexResponse = await esClient.PostPlayerStats(player.Value); if (asyncPlayerIndexResponse.IsValid) { log.LogInformation($"Player: '{player.Key}' for match '{player.Value.MatchId}' posted to elastic"); } else { log.LogError($"Player: '{player.Key}' for match '{player.Value.MatchId}' could NOT posted to elastic"); } } } else { log.LogError($"Int32.TryParse could not parse '{player.Key}' to an int. In match '{player.Value.MatchId}'"); } } return(data != null ? (ActionResult) new OkObjectResult("Match Stats Received.") : new BadRequestObjectResult("Your match stats payload was empty. Please send correct payload.")); }