Skip to content

Commit

Permalink
Use top level statements
Browse files Browse the repository at this point in the history
  • Loading branch information
hhvrc committed Nov 26, 2024
1 parent 628dbd2 commit dd4fd05
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 159 deletions.
9 changes: 5 additions & 4 deletions DiscordBot/MessageHandler/MessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
using Microsoft.Extensions.DependencyInjection;
using OpenShock.DiscordBot.OpenShockDiscordDb;
using OpenShock.DiscordBot.Services;
using OpenShock.DiscordBot.Utils;
using OpenShock.SDK.CSharp.Models;
using System.Text.RegularExpressions;

namespace OpenShock.DiscordBot.MessageHandler;
namespace OpenShock.DiscordBot;

public sealed partial class MessageHandler
{
Expand Down Expand Up @@ -39,7 +39,8 @@ public async Task HandleMessageAsync(SocketMessage message)

bool isInBotChannel = message.Channel.Id == 1114123393567047730;

if (isInBotChannel && message.Content.StartsWith("debug ")) {
if (isInBotChannel && message.Content.StartsWith("debug "))
{
await message.Channel.SendMessageAsync($"Message received: ``{message.Content[6..]}``");
}

Expand Down Expand Up @@ -67,7 +68,7 @@ public async Task HandleMessageAsync(SocketMessage message)
if (isInBotChannel) await message.Channel.SendMessageAsync("Profanity detected, but cant shock you, register and/or enable it");
return;
}

// If the channel is a bot channel, respond with debug message
if (isInBotChannel) await message.Channel.SendMessageAsync($"Profanity detected! {count} bad {(count > 1 ? "words" : "word")}, shocking at {intensityPercent:F0}%");

Expand Down
154 changes: 0 additions & 154 deletions DiscordBot/OpenShockDiscordBot.cs

This file was deleted.

143 changes: 143 additions & 0 deletions DiscordBot/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenShock.DiscordBot;
using OpenShock.DiscordBot.OpenShockDiscordDb;
using OpenShock.DiscordBot.Services;
using OpenShock.DiscordBot.Services.UserRepository;
using OpenShock.DiscordBot.Utils;
using Serilog;
using System.Reflection;

HostBuilder builder = new();

builder.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "DOTNET_");
if (args is { Length: > 0 }) config.AddCommandLine(args);
})
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile("appsettings.Custom.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true,
reloadOnChange: false);
config.AddEnvironmentVariables();
if (args is { Length: > 0 }) config.AddCommandLine(args);
})
.UseDefaultServiceProvider((context, options) =>
{
var isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
})
.UseSerilog((context, _, config) => { config.ReadFrom.Configuration(context.Configuration); });

// <---- Services ---->

builder.ConfigureServices((context, services) =>
{
var discordBotConfig = context.Configuration.GetSection("bot").Get<DiscordBotConfig>() ??
throw new Exception("Could not load bot config");
services.AddSingleton(discordBotConfig);
services.AddDbContextPool<OpenShockDiscordContext>(x =>
{
x.UseNpgsql(discordBotConfig.Db.Conn);
// ReSharper disable once InvertIf
if (discordBotConfig.Db.Debug)
{
x.EnableDetailedErrors();
x.EnableSensitiveDataLogging();
}
});
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSingleton<IOpenShockBackendService, OpenShockBackendService>();
services.AddSingleton<MessageHandler>();
services.AddSingleton<DiscordSocketClient>(new DiscordSocketClient(new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.AllUnprivileged |
GatewayIntents.MessageContent
}));
services.AddSingleton<InteractionService>(x =>
new InteractionService(x.GetRequiredService<DiscordSocketClient>()));
services.AddSingleton<InteractionHandler>();
services.AddHostedService<StatusTask>();
});

try
{
var host = builder.Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Starting OpenShock Discord Bot version {Version}", Assembly.GetEntryAssembly()?.GetName().Version?.ToString());

var config = host.Services.GetRequiredService<DiscordBotConfig>();

// <---- DATABASE MIGRATION ---->

if (!config.Db.SkipMigration)
{
logger.LogInformation("Running database migrations...");
using var scope = host.Services.CreateScope();
var openShockContext = scope.ServiceProvider.GetRequiredService<OpenShockDiscordContext>();
var pendingMigrations = (await openShockContext.Database.GetPendingMigrationsAsync()).ToList();

if (pendingMigrations.Count > 0)
{
logger.LogInformation("Found pending migrations, applying [{@Migrations}]", pendingMigrations);
await openShockContext.Database.MigrateAsync();
logger.LogInformation("Applied database migrations... proceeding with startup");
}
else logger.LogInformation("No pending migrations found, proceeding with startup");
}
else logger.LogWarning("Skipping possible database migrations...");

// <---- Initialize Service stuff, this also instantiates the singletons!!! ---->

var client = host.Services.GetRequiredService<DiscordSocketClient>();
var interactionService = host.Services.GetRequiredService<InteractionService>();
var interactionHandler = host.Services.GetRequiredService<InteractionHandler>();
var messageHandler = host.Services.GetRequiredService<MessageHandler>();

client.Log += LoggingUtils.LogAsync;
client.Ready += () => ReadyAsync(client, interactionService);

client.MessageReceived += messageHandler.HandleMessageAsync;

interactionService.Log += LoggingUtils.LogAsync;

await interactionHandler.InitializeAsync();

// <---- Run discord client ---->

await client.LoginAsync(TokenType.Bot, config.Token);
await client.StartAsync();

await host.RunAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
}

static async Task ReadyAsync(BaseSocketClient client, InteractionService interactionService)
{
Log.Information("Connected as [{CurrentUser}]", client.CurrentUser.Username);
await client.SetActivityAsync(
new Game($"electricity flow, v{Assembly.GetEntryAssembly()?.GetName().Version?.ToString()}",
ActivityType.Watching));

await interactionService.RegisterCommandsGloballyAsync();
}
2 changes: 1 addition & 1 deletion DiscordBot/Utils/ProfanityDetector.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Buffers;

namespace OpenShock.DiscordBot.MessageHandler;
namespace OpenShock.DiscordBot.Utils;

public static class ProfanityDetector
{
Expand Down

0 comments on commit dd4fd05

Please sign in to comment.