Skip to content

Commit

Permalink
style: format codebase to match updated code styling preferences
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanpth committed Oct 1, 2024
1 parent e3cd95e commit 102b5d2
Show file tree
Hide file tree
Showing 24 changed files with 327 additions and 327 deletions.
82 changes: 41 additions & 41 deletions src/AdvancedBot.Core/BotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@ 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)
{
this.client = client ?? new DiscordSocketClient(new DiscordSocketConfig
_client = client ?? new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Info,
AlwaysDownloadUsers = true,
MessageCacheSize = 1000
});

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

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

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

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

string[] creds = envVar.Split(';');
glClient = new GLClient(creds[0], creds[1], creds[2]);
var 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;

string token = Environment.GetEnvironmentVariable("Token");
var 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()
{
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);
Console.WriteLine("Registered all commands globally");
await interactions.RegisterCommandsGloballyAsync();
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)
Expand Down Expand Up @@ -148,8 +148,8 @@ private async Task onSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont
}
}

ulong id = context.Interaction.IsDMInteraction ? context.User.Id : context.Guild.Id;
var acc = accounts.GetOrCreateAccount(id, !context.Interaction.IsDMInteraction);
var 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 @@ -166,16 +166,16 @@ private async Task onSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont
cmdInfo.TimesFailed++;
}

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

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
36 changes: 18 additions & 18 deletions src/AdvancedBot.Core/Commands/CustomCommandService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,30 @@ 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)
{
string botName = context.Client.CurrentUser.Username;
string botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl();
var botName = context.Client.CurrentUser.Username;
var botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl();

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 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)";

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 @@ -75,10 +75,10 @@ public static string GenerateCommandUsage(CommandInfo command, string prefix)
{
StringBuilder parameters = new();

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

parameters.Append($"{pref}{command.Parameters[i].Name.Underscore().Dasherize()}{suff} ");
}
Expand Down
8 changes: 4 additions & 4 deletions src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ namespace AdvancedBot.Core.Commands.Modules;
[RequireCustomPermission(GuildPermission.ManageChannels)]
public class ChannelInfoModule : TopModule
{
private readonly ChannelCounterService counter;
private readonly ChannelCounterService _counter;

public ChannelInfoModule(ChannelCounterService counter)
{
this.counter = counter;
_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);

this.counter.AddNewChannelCounter(Context.Guild.Id, counter);
await this.counter.UpdateChannelAsync(Accounts.GetOrCreateAccount(Context.Guild.Id), counter);
_counter.AddNewChannelCounter(Context.Guild.Id, counter);
await _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
Expand Up @@ -233,7 +233,7 @@ public async Task BanModalResponse(string userId, BanModal modal)
return;
}

int days = 0;
var days = 0;
if (!string.IsNullOrEmpty(modal.Duration) && int.TryParse(modal.Duration, out days))
{
}
Expand Down
16 changes: 8 additions & 8 deletions src/AdvancedBot.Core/Commands/Modules/DevModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ namespace AdvancedBot.Core.Commands.Modules;
[RequirePrivateList]
public class DevModule : TopModule
{
private readonly InteractionService interactions;
private readonly InteractionService _interactions;

public DevModule(InteractionService interactions)
{
this.interactions = interactions;
_interactions = interactions;
}

[SlashCommand("allstats", "Shows combined stats from all servers")]
Expand All @@ -39,7 +39,7 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"),
var fields = new List<EmbedField>();
var commands = allInfos.OrderByDescending(x => x.TimesRun).ToArray();

for (int i = 0; i < commands.Length; i++)
for (var i = 0; i < commands.Length; i++)
{
fields.Add(
new EmbedFieldBuilder()
Expand All @@ -48,7 +48,7 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"),
.Build());
}

string title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}";
var title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}";

var templateEmbed = new EmbedBuilder()
.WithTitle(title);
Expand All @@ -60,15 +60,15 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"),
[CommandContextType(InteractionContextType.Guild, InteractionContextType.PrivateChannel)]
public async Task AddModerationModuleToGuildAsync(string guildId, string modulename)
{
var module = interactions.Modules.First(module => module.Name.Equals(modulename, System.StringComparison.CurrentCultureIgnoreCase));
var module = _interactions.Modules.First(module => module.Name.Equals(modulename, System.StringComparison.CurrentCultureIgnoreCase));

if (module == null)
{
await ModifyOriginalResponseAsync(msg => msg.Content = $"Could not find any module named **{modulename}**.");
return;
}

await interactions.AddModulesToGuildAsync(ulong.Parse(guildId), false, module);
await _interactions.AddModulesToGuildAsync(ulong.Parse(guildId), false, module);

var embed = new EmbedBuilder()
.WithTitle("Module successfully added")
Expand All @@ -88,9 +88,9 @@ private static List<CommandStats> calculateCommandStatsOnAccounts(Account[] acco
{
var allInfos = new List<CommandStats>();

for (int i = 0; i < accounts.Length; i++)
for (var i = 0; i < accounts.Length; i++)
{
for (int j = 0; j < accounts[i].CommandStats.Count; j++)
for (var j = 0; j < accounts[i].CommandStats.Count; j++)
{
var cmdStats = accounts[i].CommandStats[j];
var foundCmd = allInfos.Find(x => x.Name == cmdStats.Name);
Expand Down
14 changes: 7 additions & 7 deletions src/AdvancedBot.Core/Commands/Modules/GLModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public async Task DisplayServerStatusAsync()
{
var status = await GLClient.Api.GetServerStatus();

string thumbnailUrl =
var thumbnailUrl =
Context.Channel is IGuildChannel
? Context.Guild.IconUrl
: Context.Client.CurrentUser.GetDisplayAvatarUrl();
Expand All @@ -33,7 +33,7 @@ Context.Channel is IGuildChannel
.WithIconUrl(Context.User.GetDisplayAvatarUrl()))
.WithCurrentTimestamp();

for (int i = 0; i < status.Count; i++)
for (var i = 0; i < status.Count; i++)
{
embed.AddField($"{status[i].Name} ({status[i].Ping}ms)", status[i].IsOnline ? "✅ Operational" : "🛑 Offline", true);
}
Expand Down Expand Up @@ -105,9 +105,9 @@ public async Task GetLeaderboardAsync([
] string type)
{
List<string> displayTexts = ["Failed to get information"];
string title = "Galaxy Life Leaderboard";
var title = "Galaxy Life Leaderboard";

string thumbnailUrl =
var thumbnailUrl =
Context.Channel is IGuildChannel
? Context.Guild.IconUrl
: Context.Client.CurrentUser.GetDisplayAvatarUrl();
Expand Down Expand Up @@ -153,7 +153,7 @@ Context.Channel is IGuildChannel
return;
}

for (int i = 0; i < displayTexts.Count; i++)
for (var i = 0; i < displayTexts.Count; i++)
{
displayTexts[i] = $"**#{i + 1}** | {displayTexts[i]}";
}
Expand Down Expand Up @@ -197,15 +197,15 @@ public async Task CompareUsersAsync(string firstPlayer, string secondPlayer)
return;
}

string thumbnailUrl =
var thumbnailUrl =
Context.Channel is IGuildChannel
? Context.Guild.IconUrl
: Context.Client.CurrentUser.GetDisplayAvatarUrl();

var baseUserStats = await GLClient.Api.GetUserStats(baseUser.Id);
var secondUserStats = await GLClient.Api.GetUserStats(secondUser.Id);

decimal expDifference = Math.Round((decimal)baseUser.Experience / secondUser.Experience, 2);
var expDifference = Math.Round((decimal)baseUser.Experience / secondUser.Experience, 2);

var embed = new EmbedBuilder()
.WithTitle($"{baseUser.Name} vs {secondUser.Name}")
Expand Down
Loading

0 comments on commit 102b5d2

Please sign in to comment.