Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ bld/
[Oo]bj/
[Ll]og/

# VSCODE
.vscode/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vs/**/*
Expand Down
36 changes: 32 additions & 4 deletions Components/GuildConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,44 @@

namespace tModloaderDiscordBot.Components
{
/// <summary>
/// Defines the stored configuration of a guild
/// </summary>
public sealed class GuildConfig
{
/// <summary>
/// The guild's snowflake Id this configuration belongs to
/// </summary>
public ulong GuildId;
public IList<SiteStatus> SiteStatuses = new List<SiteStatus>();
public IList<GuildTag> GuildTags = new List<GuildTag>();
public BotPermissions Permissions = new BotPermissions();

/// <summary>
/// A list of site statuses being tracked by this configuration
/// </summary>
public IList<SiteStatus> SiteStatuses = [];

/// <summary>
/// The tags that belong to this configuration
/// </summary>
public IList<GuildTag> GuildTags = [];

/// <summary>
/// The bot's permissions
/// </summary>
public BotPermissions Permissions = new();

[JsonIgnore] private GuildConfigService _guildConfigService;

/// <summary>
/// Initializes the configuration
/// </summary>
public void Initialize(GuildConfigService guildConfigService)
{
_guildConfigService = guildConfigService;
}

/// <summary>
/// Creates a new configuration instance for the given guild
/// </summary>
public GuildConfig(SocketGuild guild)
{
if (guild != null)
Expand All @@ -28,9 +52,13 @@ public GuildConfig(SocketGuild guild)
}
}

/// <summary>
/// Attempts to update this configuration and write it to storage
/// </summary>
/// <returns></returns>
public async Task<bool> Update()
{
if (_guildConfigService == null)
if (_guildConfigService == null)
return false;

await _guildConfigService.UpdateCacheForConfig(this);
Expand Down
31 changes: 31 additions & 0 deletions Components/GuildTag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,46 @@

namespace tModloaderDiscordBot.Components
{
/// <summary>
/// Defines a tag in a guild
/// </summary>
public sealed class GuildTag
{
/// <summary>
/// The owner's snowflake Id
/// </summary>
public ulong OwnerId;

/// <summary>
/// The tag's name
/// </summary>
public string Name;

/// <summary>
/// The tag's value
/// </summary>
public string Value;

/// <summary>
/// Whether the tag is global
/// </summary>
public bool IsGlobal;

/// <summary>
/// Returns whether the given snowflake id is the owner of this tag
/// </summary>
public bool IsOwner(ulong id) => OwnerId == id;

/// <summary>
/// Returns whether the tag's name matches the given name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool MatchesName(string name) => Name.EqualsIgnoreCase(name);

/// <summary>
/// Returns whether the given key is valid for use after being sanitized
/// </summary>
public static bool IsKeyValid(string key) => Format.Sanitize(key).Equals(key) && !key.Contains(" ");
}
}
7 changes: 1 addition & 6 deletions Components/ModInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,5 @@ public override string ToString()
}
}

public class VoteData
{
public int score;
public int votes_up;
public int votes_down;
}

}
10 changes: 2 additions & 8 deletions Components/SiteStatus.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace tModloaderDiscordBot.Components
{
public enum SiteStatusCode
{
Offline,
Online,
Unknown,
Invalid
}

public class SiteStatus
{
[JsonIgnore]
Expand Down Expand Up @@ -72,6 +65,7 @@ public Task Revalidate()

internal bool Ping()
{
//new HttpClient()
var request = WebRequest.Create(Address);
return request.GetResponse() is HttpWebResponse response && response.StatusCode == HttpStatusCode.OK;
}
Expand Down
7 changes: 7 additions & 0 deletions Components/SiteStatusCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
public enum SiteStatusCode
{
Offline,
Online,
Unknown,
Invalid
}
6 changes: 6 additions & 0 deletions Components/VoteData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
public class VoteData
{
public int score;
public int votes_up;
public int votes_down;
}
18 changes: 18 additions & 0 deletions ConnectionStateExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Discord;

namespace tModloaderDiscordBot;

public static class ConnectionStateExtensions
{
public static UserStatus ToUserStatus(this ConnectionState state)
{
return state switch
{
ConnectionState.Connected => UserStatus.Online,
ConnectionState.Disconnected => UserStatus.DoNotDisturb,
ConnectionState.Connecting => UserStatus.Idle,
ConnectionState.Disconnecting => UserStatus.DoNotDisturb,
_ => UserStatus.Online
};
}
}
36 changes: 36 additions & 0 deletions DiscordEventListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Threading;
using System.Threading.Tasks;
using Discord.WebSocket;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using tModloaderDiscordBot.Notifications;

namespace tModloaderDiscordBot;

/// <summary>
/// Listens to Discord's events and creates notifications for them commands and forwards it to Mediatr
/// </summary>
public class DiscordEventListener(DiscordSocketClient client, IServiceScopeFactory serviceScope)
{
private readonly CancellationToken _cancellationToken = new CancellationTokenSource().Token;

private IMediator Mediator
{
get
{
var scope = serviceScope.CreateScope();
return scope.ServiceProvider.GetRequiredService<IMediator>();
}
}

public async Task SetupAsync()
{
client.MessageReceived += OnMessageReceivedAsync;
await Task.CompletedTask;
}

private Task OnMessageReceivedAsync(SocketMessage arg)
{
return Mediator.Publish(new MessageReceivedNotification(arg), _cancellationToken);
}
}
34 changes: 34 additions & 0 deletions Factories/CommandServiceFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Discord;
using Discord.Commands;

namespace tModloaderDiscordBot.Factories
{
internal class CommandServiceFactory
{
private CommandServiceFactory()
{

}

public static CommandServiceConfig CreateCommandServiceConfig()
{
return new CommandServiceConfig
{
DefaultRunMode = RunMode.Async,
CaseSensitiveCommands = false,
#if TESTBOT
LogLevel = LogSeverity.Critical,
ThrowOnError = true,
#else
LogLevel = LogSeverity.Debug,
ThrowOnError = false
#endif
};
}

public static CommandService CreateCommandService()
{
return new CommandService(CreateCommandServiceConfig());
}
}
}
26 changes: 26 additions & 0 deletions Factories/DiscordClientFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Discord;
using Discord.WebSocket;

namespace tModloaderDiscordBot.Factories
{
internal class DiscordClientFactory
{
private DiscordClientFactory() { }

public static DiscordSocketConfig CreateDiscordSocketConfig()
{
return new DiscordSocketConfig
{
GatewayIntents = (GatewayIntents.AllUnprivileged | GatewayIntents.GuildMembers) & ~(GatewayIntents.GuildScheduledEvents | GatewayIntents.GuildInvites),
AlwaysDownloadUsers = true,
LogLevel = LogSeverity.Verbose,
MessageCacheSize = 100
};
}

public static IDiscordClient CreateDiscordSocketClient()
{
return new DiscordSocketClient(CreateDiscordSocketConfig());
}
}
}
43 changes: 43 additions & 0 deletions Factories/ServiceProviderFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using System.Resources;
using tModloaderDiscordBot.Services;

namespace tModloaderDiscordBot.Factories
{
internal static class ServiceProviderFactory
{
private static Assembly EntryAssembly => Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly();

private static readonly ResourceManager ResourceManager =
new("tModloaderDiscordBot.Properties.Resources", EntryAssembly);

public static IServiceCollection CreateServiceCollection()
{
return new ServiceCollection()
.AddMediatR(typeof(Program))
.AddSingleton<DiscordEventListener>()
.AddSingleton<UserHandlerService>()
.AddSingleton<CommandHandlerService>()
.AddSingleton<HastebinService>()
.AddSingleton<AutoPinService>()
.AddSingleton<RecruitmentChannelService>()
.AddSingleton<BanAppealChannelService>()
.AddSingleton<SupportChannelAutoMessageService>()
.AddSingleton<CrosspostService>()
//.AddSingleton<ReactionRoleService>()
// How to use resources:
//_services.GetRequiredService<ResourceManager>().GetString("key")
.AddSingleton(ResourceManager)
.AddSingleton<LoggingService>()
.AddSingleton<GuildConfigService>()
.AddSingleton<SiteStatusService>()
.AddSingleton<GuildTagService>()
.AddSingleton<PermissionService>()
.AddSingleton<LegacyModService>()
.AddSingleton<ModService>()
.AddSingleton<AuthorService>();
}
}
}
Loading