Skip to content

Commit

Permalink
Add watchlist feature (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
joker-119 authored Nov 12, 2022
1 parent e208977 commit f1a9327
Show file tree
Hide file tree
Showing 19 changed files with 315 additions and 45 deletions.
4 changes: 4 additions & 0 deletions DiscordIntegration.Bot/Bot.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using DiscordIntegration.Dependency.Database;

namespace DiscordIntegration.Bot;

using System.Collections.Specialized;
Expand Down Expand Up @@ -56,6 +58,8 @@ private async Task Init()
return;
}

DatabaseHandler.Init();

Log.Debug(ServerNumber, nameof(Init), "Setting up commands...");
InteractionService = new(Client, new InteractionServiceConfig()
{
Expand Down
2 changes: 1 addition & 1 deletion DiscordIntegration.Bot/Commands/SendCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public async Task Send([Summary("command", "The command to send.")] string comma
ErrorCodes canRunCommand = SlashCommandHandler.CanRunCommand((IGuildUser) Context.User, bot.ServerNumber, command);
if (canRunCommand != ErrorCodes.None)
{
await RespondAsync(embed: await ErrorHandlingService.GetErrorEmbed(canRunCommand));
await RespondAsync(embed: await ErrorHandlingService.GetErrorEmbed(canRunCommand), ephemeral: true);
return;
}

Expand Down
63 changes: 63 additions & 0 deletions DiscordIntegration.Bot/Commands/WatchlistCommands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using DiscordIntegration.Bot.Services;
using DiscordIntegration.Dependency.Database;

namespace DiscordIntegration.Bot.Commands;

using Discord;
using Discord.Interactions;

[Group("watchlist", "Commands for managing the watchlist.")]
public class WatchlistCommands: InteractionModuleBase<SocketInteractionContext>
{
private readonly Bot bot;

public WatchlistCommands(Bot bot) => this.bot = bot;

[SlashCommand("add", "Adds a UserID to the watchlist.")]
public async Task AddToWatchlist([Summary("UserId", "The user ID of the player to watch.")] string userId, [Summary("Reason", "The reason they should be watched.")] string reason)
{
ErrorCodes canRunCommand = SlashCommandHandler.CanRunCommand((IGuildUser) Context.User, bot.ServerNumber, "watchlist");
if (canRunCommand != ErrorCodes.None)
{
await RespondAsync(embed: await ErrorHandlingService.GetErrorEmbed(canRunCommand), ephemeral: true);
return;
}

if (DatabaseHandler.CheckWatchlist(userId, out string res))
{
await RespondAsync(
embed: await EmbedBuilderService.CreateBasicEmbed("User already on Watchlist",
$"The userID {userId} is already on the watchlist for {reason}. If you wish to change the reason, please remove the user first then re-add them.",
Color.Orange), ephemeral: true);
return;
}

DatabaseHandler.AddEntry(userId, reason);
await RespondAsync(
embed: await EmbedBuilderService.CreateBasicEmbed("User added to Watchlist",
$"The userID {userId} has been added to the watchlist for {reason}", Color.Green), ephemeral: true);
}

[SlashCommand("remove", "Removes a UserID from the watchlist.")]
public async Task RemoveFromWatchlist([Summary("UserID", "The user ID of the player to remove from the watchlist.")] string userId)
{
ErrorCodes canRunCommand =
SlashCommandHandler.CanRunCommand((IGuildUser)Context.User, bot.ServerNumber, "watchlist");
if (canRunCommand != ErrorCodes.None)
{
await RespondAsync(embed: await ErrorHandlingService.GetErrorEmbed(canRunCommand), ephemeral: true);
return;
}

if (!DatabaseHandler.CheckWatchlist(userId, out string _))
{
await RespondAsync(embed: await ErrorHandlingService.GetErrorEmbed(ErrorCodes.NoRecordForUserFound), ephemeral: true);
return;
}

DatabaseHandler.RemoveEntry(userId);
await RespondAsync(
embed: await EmbedBuilderService.CreateBasicEmbed("User removed from watchlist.",
$"User {userId} has been removed from the watchlist.", Color.Green), ephemeral: true);
}
}
8 changes: 8 additions & 0 deletions DiscordIntegration.Bot/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ public class Config
LogType = LogType.Embed
},
},
Watchlist = new List<LogChannel>
{
new()
{
Id = 0,
LogType = LogType.Embed
},
},
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions DiscordIntegration.Bot/ConfigObjects/LogChannels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class LogChannels
public List<LogChannel>? Reports { get; set; } = new();
public List<LogChannel>? StaffCopy { get; set; } = new();
public List<LogChannel>? Errors { get; set; } = new();
public List<LogChannel>? Watchlist { get; set; } = new();

public IEnumerable<LogChannel> this[ChannelType result]
{
Expand All @@ -22,6 +23,7 @@ public IEnumerable<LogChannel> this[ChannelType result]
ChannelType.Reports => Reports,
ChannelType.StaffCopy => StaffCopy,
ChannelType.Errors => Errors,
ChannelType.Watchlist => Watchlist,
_ => throw new ArgumentOutOfRangeException(nameof(result), result, null)
})!;
}
Expand Down
4 changes: 2 additions & 2 deletions DiscordIntegration.Bot/DiscordIntegration.Bot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyVersion>1.5.1</AssemblyVersion>
<FileVersion>1.5.1</FileVersion>
<AssemblyVersion>1.6.0</AssemblyVersion>
<FileVersion>1.6.0</FileVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion DiscordIntegration.Dependency/ChannelType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public enum ChannelType
Bans,
Reports,
StaffCopy,
Errors
Errors,
Watchlist
}
}
82 changes: 82 additions & 0 deletions DiscordIntegration.Dependency/Database/DatabaseHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.IO;
using Microsoft.Data.Sqlite;

namespace DiscordIntegration.Dependency.Database;

public class DatabaseHandler
{
private static string _connectionString =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DiscordIntegration.db");

public static void Init()
{
using SqliteConnection conn = new(_connectionString);
conn.Open();

using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"CREATE TABLE IF NOT EXISTS Watchlist(Id INTEGER PRIMARY KEY AUTOINCREMENT, UserId TEXT, Reason TEXT)";
cmd.ExecuteNonQuery();
}

conn.Close();
}

public static void AddEntry(string userId, string reason)
{
using SqliteConnection conn = new(_connectionString);
conn.Open();

using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Watchlist(UserId, Reason) VALUES(@id, @reason)";
cmd.Parameters.AddWithValue("@id", userId);
cmd.Parameters.AddWithValue("@reason", reason);
cmd.ExecuteNonQuery();
}
conn.Close();
}


public static void RemoveEntry(string userId)
{
using SqliteConnection conn = new(_connectionString);
conn.Open();

using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "DELETE FROM Watchlist WHERE UserId=@id";
cmd.Parameters.AddWithValue("@id", userId);

cmd.ExecuteNonQuery();
}

conn.Close();
}

public static bool CheckWatchlist(string userId, out string reason)
{
reason = "Not in watchlist";
using SqliteConnection conn = new(_connectionString);
conn.Open();

using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Watchlist WHERE UserId=@id";
cmd.Parameters.AddWithValue("@id", userId);

using (SqliteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
reason = reader.GetString(2);
return true;
}
}
}
conn.Close();
return false;
}
}
34 changes: 4 additions & 30 deletions DiscordIntegration.Dependency/DiscordIntegration.Dependency.csproj
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,10 @@
<FileAlignment>512</FileAlignment>
<LangVersion>10</LangVersion>
<Nullable>enable</Nullable>
<TargetFramework>net472</TargetFramework>
<AssemblyVersion>1.4.2</AssemblyVersion>
<FileVersion>1.4.2</FileVersion>
<AssemblyVersion>1.5.0</AssemblyVersion>
<FileVersion>1.5.0</FileVersion>
<OutputPath>../bin/Plugin/dependencies</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>../bin/Plugin/dependencies/</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>../bin/Plugin/dependencies/</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
Expand All @@ -48,15 +29,8 @@
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->

</Project>
1 change: 1 addition & 0 deletions DiscordIntegration.Dependency/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net472" />
<package id="Microsoft.Data.Sqlite" version="7.0.0" targetFramework="net472" />
</packages>
Empty file modified DiscordIntegration/API/Network.cs
100755 → 100644
Empty file.
8 changes: 7 additions & 1 deletion DiscordIntegration/Commands/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,17 @@ public override void LoadGeneratedCommands()
{
RegisterCommand(PlayerList.Instance);
RegisterCommand(StaffList.Instance);

if (Instance.Config.UseWatchlist)
{
RegisterCommand(WatchlistAdd.Instance);
RegisterCommand(WatchlistRemove.Instance);
}
}

protected override bool ExecuteParent(ArraySegment<string> arguments, ICommandSender sender, out string response)
{
response = $"{Language.InvalidSubcommand} {Language.Available}: playerlist, stafflist, reload, add, remove";
response = $"{Language.InvalidSubcommand} {Language.Available}: playerlist, stafflis" + $"{(Instance.Config.UseWatchlist ? "watchadd, watchrem" : string.Empty)}";
return false;
}
}
Expand Down
56 changes: 56 additions & 0 deletions DiscordIntegration/Commands/WatchlistAdd.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// -----------------------------------------------------------------------
// <copyright file="PlayerList.cs" company="Exiled Team">
// Copyright (c) Exiled Team. All rights reserved.
// Licensed under the CC BY-SA 3.0 license.
// </copyright>
// -----------------------------------------------------------------------

using DiscordIntegration.Dependency.Database;

namespace DiscordIntegration.Commands
{
using System;
using System.Text;
using CommandSystem;
using Exiled.API.Features;
using Exiled.Permissions.Extensions;
using NorthwoodLib.Pools;
using static DiscordIntegration;

/// <summary>
/// Adds a user to the watchlist.
/// </summary>
internal sealed class WatchlistAdd : ICommand
{
#pragma warning disable SA1600 // Elements should be documented
private WatchlistAdd()
{
}

public static WatchlistAdd Instance { get; } = new WatchlistAdd();

public string Command { get; } = "watchadd";

public string[] Aliases { get; } = new[] { "wla" };

public string Description { get; } = Language.WatchlistAddDescription;

public bool Execute(ArraySegment<string> arguments, ICommandSender sender, out string response)
{
if (!sender.CheckPermission("di.watchlistadd"))
{
response = string.Format(Language.NotEnoughPermissions, "di.watchlistadd");
return false;
}

Player player = Player.Get(arguments.ElementAt(2));
string reason = string.Empty;
foreach (string s in arguments.Skip(2))
reason += $"{s} ";
reason = reason.TrimEnd(' ');
DatabaseHandler.AddEntry(player.UserId, reason);
response = $"{player.Nickname} added to watchlist for {reason}";
return true;
}
}
}
Loading

0 comments on commit f1a9327

Please sign in to comment.