Skip to content

Commit

Permalink
style: format codebase to improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanpth committed Sep 27, 2024
1 parent cf15227 commit b15e886
Show file tree
Hide file tree
Showing 26 changed files with 433 additions and 443 deletions.
108 changes: 54 additions & 54 deletions src/AdvancedBot.Core/BotClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using AdvancedBot.Core.Commands;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using AdvancedBot.Core.Commands;
using AdvancedBot.Core.Entities;
using AdvancedBot.Core.Services;
using AdvancedBot.Core.Services.DataStorage;
Expand All @@ -7,32 +11,28 @@
using Discord.WebSocket;
using GL.NET;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;

namespace AdvancedBot.Core
{
public class BotClient
{
private readonly DiscordSocketClient _client;
private readonly CustomCommandService _commands;
private IServiceProvider _services;
private readonly InteractionService _interactions;
private AccountService _accounts;
private readonly GLClient _glClient;
private readonly DiscordSocketClient client;
private readonly CustomCommandService commands;
private IServiceProvider services;
private readonly InteractionService interactions;
private AccountService accounts;
private readonly GLClient glClient;

public BotClient(CustomCommandService commands = null, DiscordSocketClient client = null)
{
_client = client ?? new DiscordSocketClient(new DiscordSocketConfig
this.client = client ?? new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Info,
AlwaysDownloadUsers = true,
MessageCacheSize = 1000
});

_commands = commands ?? new CustomCommandService(new CustomCommandServiceConfig
this.commands = commands ?? new CustomCommandService(new CustomCommandServiceConfig
{
CaseSensitiveCommands = false,
LogLevel = LogSeverity.Info,
Expand All @@ -45,82 +45,82 @@ public BotClient(CustomCommandService commands = null, DiscordSocketClient clien
#endif
});

_interactions = new InteractionService(_client.Rest, new InteractionServiceConfig() { UseCompiledLambda = true });
interactions = new InteractionService(this.client.Rest, new InteractionServiceConfig() { UseCompiledLambda = true });

var envVar = Environment.GetEnvironmentVariable("PhoenixApiCred");
string envVar = Environment.GetEnvironmentVariable("PhoenixApiCred");

if (envVar == null)
{
LogAsync(new LogMessage(LogSeverity.Warning, "BotClient", "Initializing GLClient without tokens!"));
_glClient = new GLClient("", "", "");
logAsync(new LogMessage(LogSeverity.Warning, "BotClient", "Initializing GLClient without tokens!"));
glClient = new GLClient("", "", "");
return;
}

var creds = envVar.Split(';');
_glClient = new GLClient(creds[0], creds[1], creds[2]);
string[] creds = envVar.Split(';');
glClient = new GLClient(creds[0], creds[1], creds[2]);
}

public async Task InitializeAsync()
{
Console.Title = $"Launching Discord Bot...";
_services = ConfigureServices();
_accounts = _services.GetRequiredService<AccountService>();
services = configureServices();
accounts = services.GetRequiredService<AccountService>();

_client.Ready += OnReadyAsync;
_interactions.SlashCommandExecuted += OnSlashCommandExecuted;
client.Ready += onReadyAsync;
interactions.SlashCommandExecuted += onSlashCommandExecuted;

_client.Log += LogAsync;
_commands.Log += LogAsync;
client.Log += logAsync;
commands.Log += logAsync;

var token = Environment.GetEnvironmentVariable("Token");
string token = Environment.GetEnvironmentVariable("Token");

await Task.Delay(10).ContinueWith(t => _client.LoginAsync(TokenType.Bot, token));
await _client.StartAsync();
await Task.Delay(10).ContinueWith(t => client.LoginAsync(TokenType.Bot, token));
await client.StartAsync();

await Task.Delay(-1);
}

private async Task OnReadyAsync()
private async Task onReadyAsync()
{
Console.Title = $"Running Discord Bot: {_client.CurrentUser.Username}";
Console.Title = $"Running Discord Bot: {client.CurrentUser.Username}";

Game activity = new(
"Galaxy Life",
ActivityType.Watching,
ActivityProperties.Instance
);

await _client.SetActivityAsync(activity);
Console.WriteLine($"Guild count: {_client.Guilds.Count}");
await client.SetActivityAsync(activity);
Console.WriteLine($"Guild count: {client.Guilds.Count}");

await _interactions.AddModulesAsync(Assembly.GetExecutingAssembly(), _services);
Console.WriteLine($"Modules count: {_interactions.Modules.Count}");
Console.WriteLine($"SlashCommands count: {_interactions.SlashCommands.Count}");
await interactions.AddModulesAsync(Assembly.GetExecutingAssembly(), services);
Console.WriteLine($"Modules count: {interactions.Modules.Count}");
Console.WriteLine($"SlashCommands count: {interactions.SlashCommands.Count}");

#if DEBUG
Console.WriteLine("Registered all commands to test server");
await _interactions.RegisterCommandsToGuildAsync(696343127144923158, false);
await interactions.RegisterCommandsToGuildAsync(696343127144923158, false);
#else
Console.WriteLine("Registered all commands globally");
await _interactions.RegisterCommandsGloballyAsync();
Console.WriteLine("Registered all commands globally");
await interactions.RegisterCommandsGloballyAsync();
#endif

_client.InteractionCreated += async (x) =>
client.InteractionCreated += async (x) =>
{
var context = new SocketInteractionContext(_client, x);
await _interactions.ExecuteCommandAsync(context, _services);
var context = new SocketInteractionContext(client, x);
await interactions.ExecuteCommandAsync(context, services);
};

_glClient.ErrorThrown += OnGLErrorThrown;
glClient.ErrorThrown += onGLErrorThrown;
}

private async void OnGLErrorThrown(object sender, ErrorEventArgs e)
private async void onGLErrorThrown(object sender, ErrorEventArgs e)
{
var exception = e.GetException();
await LogAsync(new LogMessage(LogSeverity.Critical, "GL.NET", exception.Message, exception));
await logAsync(new LogMessage(LogSeverity.Critical, "GL.NET", exception.Message, exception));
}

private Task LogAsync(LogMessage msg)
private Task logAsync(LogMessage msg)
{
if (msg.Exception != null)
{
Expand All @@ -134,7 +134,7 @@ private Task LogAsync(LogMessage msg)
return Task.CompletedTask;
}

private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionContext context, IResult result)
private async Task onSlashCommandExecuted(SlashCommandInfo cmd, IInteractionContext context, IResult result)
{
if (!result.IsSuccess)
{
Expand All @@ -149,8 +149,8 @@ private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont
}
}

var id = context.Interaction.IsDMInteraction ? context.User.Id : context.Guild.Id;
var acc = _accounts.GetOrCreateAccount(id, !context.Interaction.IsDMInteraction);
ulong id = context.Interaction.IsDMInteraction ? context.User.Id : context.Guild.Id;
var acc = accounts.GetOrCreateAccount(id, !context.Interaction.IsDMInteraction);

var cmdInfo = acc.CommandStats.Find(x => x.Name == cmd.Name);

Expand All @@ -167,16 +167,16 @@ private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont
cmdInfo.TimesFailed++;
}

_accounts.SaveAccount(acc);
accounts.SaveAccount(acc);
}

private ServiceProvider ConfigureServices()
private ServiceProvider configureServices()
{
return new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commands)
.AddSingleton(_interactions)
.AddSingleton(_glClient)
.AddSingleton(client)
.AddSingleton(commands)
.AddSingleton(interactions)
.AddSingleton(glClient)
.AddSingleton<LiteDBHandler>()
.AddSingleton<AccountService>()
.AddSingleton<PaginatorService>()
Expand Down
42 changes: 21 additions & 21 deletions src/AdvancedBot.Core/Commands/CustomCommandService.cs
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
using AdvancedBot.Core.Services;
using Discord;
using Discord.Commands;
using Humanizer;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AdvancedBot.Core.Services;
using Discord;
using Discord.Commands;
using Humanizer;

namespace AdvancedBot.Core.Commands
{
public class CustomCommandService : CommandService
{
public PaginatorService Paginator { get; set; }
public ulong LogChannelId;
private readonly string _documentationUrl;
private readonly string _sourceRepo;
private readonly string _contributors;
private readonly bool _botIsPrivate;
private readonly string documentationUrl;
private readonly string sourceRepo;
private readonly string contributors;
private readonly bool botIsPrivate;

public CustomCommandService() : base() { }

public CustomCommandService(CustomCommandServiceConfig config) : base(config)
{
_documentationUrl = config.DocumentationUrl;
_sourceRepo = config.RepositoryUrl;
_contributors = config.Contributors;
_botIsPrivate = config.BotInviteIsPrivate;
documentationUrl = config.DocumentationUrl;
sourceRepo = config.RepositoryUrl;
contributors = config.Contributors;
botIsPrivate = config.BotInviteIsPrivate;
LogChannelId = config.LogChannelId;
}

public async Task SendBotInfoAsync(IInteractionContext context)
{
var botName = context.Client.CurrentUser.Username;
var botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl();
string botName = context.Client.CurrentUser.Username;
string botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl();

var repoLink = string.IsNullOrEmpty(_sourceRepo) ? $"Unavailable" : $"[GitHub repository]({_sourceRepo})";
var docsLink = string.IsNullOrEmpty(_documentationUrl) ? $"Unavailable" : $"[Read the docs]({_documentationUrl})";
var inviteLink = $"[Invite link](https://discordapp.com/api/oauth2/authorize?client_id={context.Client.CurrentUser.Id}&permissions=8&scope=bot)";
string repoLink = string.IsNullOrEmpty(sourceRepo) ? $"Unavailable" : $"[GitHub repository]({sourceRepo})";
string docsLink = string.IsNullOrEmpty(documentationUrl) ? $"Unavailable" : $"[Read the docs]({documentationUrl})";
string inviteLink = $"[Invite link](https://discordapp.com/api/oauth2/authorize?client_id={context.Client.CurrentUser.Id}&permissions=8&scope=bot)";

var embed = new EmbedBuilder()
.WithTitle($"About {botName}")
Expand All @@ -50,12 +50,12 @@ public async Task SendBotInfoAsync(IInteractionContext context)
.WithIconUrl(context.User.GetDisplayAvatarUrl()))
.WithCurrentTimestamp();

if (!_botIsPrivate)
if (!botIsPrivate)
{
embed.AddField("Invitation", inviteLink, true);
}

embed.AddField("Developed by", _contributors);
embed.AddField("Developed by", contributors);

await context.Interaction.ModifyOriginalResponseAsync(msg => msg.Embeds = new Embed[] { embed.Build() });
}
Expand All @@ -77,8 +77,8 @@ public static string GenerateCommandUsage(CommandInfo command, string prefix)

for (int i = 0; i < command.Parameters.Count; i++)
{
var pref = command.Parameters[i].IsOptional ? "[" : "<";
var suff = command.Parameters[i].IsOptional ? "]" : ">";
string pref = command.Parameters[i].IsOptional ? "[" : "<";
string suff = command.Parameters[i].IsOptional ? "]" : ">";

parameters.Append($"{pref}{command.Parameters[i].Name.Underscore().Dasherize()}{suff} ");
}
Expand Down
12 changes: 6 additions & 6 deletions src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
using System;
using System.Threading.Tasks;
using AdvancedBot.Core.Commands.Preconditions;
using AdvancedBot.Core.Entities;
using AdvancedBot.Core.Entities.Enums;
using AdvancedBot.Core.Services;
using Discord;
using Discord.Interactions;
using System;
using System.Threading.Tasks;

namespace AdvancedBot.Core.Commands.Modules
{
[Group("channels", "All commands regarding channel counters")]
[RequireCustomPermission(GuildPermission.ManageChannels)]
public class ChannelInfoModule : TopModule
{
private readonly ChannelCounterService _counter;
private readonly ChannelCounterService counter;

public ChannelInfoModule(ChannelCounterService counter)
{
_counter = counter;
this.counter = counter;
}

[SlashCommand("setup", "Set up the channel counter")]
Expand All @@ -34,8 +34,8 @@ public async Task SetupChannelCountersAsync()
{
var counter = new ChannelCounter(voiceChannel.Id, ChannelCounterType.FlashStatus);

_counter.AddNewChannelCounter(Context.Guild.Id, counter);
await _counter.UpdateChannelAsync(Accounts.GetOrCreateAccount(Context.Guild.Id), counter);
this.counter.AddNewChannelCounter(Context.Guild.Id, counter);
await this.counter.UpdateChannelAsync(Accounts.GetOrCreateAccount(Context.Guild.Id), counter);

await ModifyOriginalResponseAsync(msg => msg.Content = $"Setup the Server Status Voice Channel {voiceChannel.Mention}");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading.Tasks;
using AdvancedBot.Core.Services;
using Discord.Interactions;
using System.Threading.Tasks;

namespace AdvancedBot.Core.Commands.Modules
{
Expand Down
Loading

0 comments on commit b15e886

Please sign in to comment.