Skip to content

Commit

Permalink
Discord Ban Webhook (DeltaV-Station#119) (#20)
Browse files Browse the repository at this point in the history
* tudo feito pros bans e rolebans

* fim finalmente

* Update Content.Server/Administration/Managers/BanManager.Discord.cs



* formatações do code rabbit

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
AgentePanela and coderabbitai[bot] authored Feb 2, 2025
1 parent fff90e0 commit 60accdf
Show file tree
Hide file tree
Showing 4 changed files with 184 additions and 0 deletions.
137 changes: 137 additions & 0 deletions Content.Server/Administration/Managers/BanManager.Discord.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using Content.Server.Discord;
using Content.Server.GameTicking;
using Content.Shared._Gabystation.CCVar;
using Robust.Shared.Network;
using Content.Server.Database;

namespace Content.Server.Administration.Managers;

// Gabystation - Serverban & Roleban webhook
public sealed partial class BanManager
{
[Dependency] private readonly DiscordWebhook _discord = default!;
private WebhookData? _webhook;

private void InitializeDiscord()
{
var value = _cfg.GetCVar(GabyCVars.BanDiscordWebhook);
if (!string.IsNullOrEmpty(value))
{
_discord.TryGetWebhook(value, val => _webhook = val);
}
}
// TODO: This is shitcode, revamp.
// TODO: Embed.

/// <summary>
/// Send to webhook a server ban message.
/// </summary>
private async void SendServerBanWebhook(ServerBanDef ban, string player, string admin, uint? minutes)
{
try
{
if (_webhook is null)
return;

var hook = _webhook.Value.ToIdentifier();

var id = ban.Id?.ToString() ?? "?";
var rId = ban.RoundId?.ToString() ?? "?";



var footer = Loc.GetString("ban-manager-notify-discord-footer",
("round", rId),
("id", id)); // Todo: fallback

var message = "...";

if (ban.ExpirationTime is null)
message = Loc.GetString("ban-manager-notify-discord-perma",
("admin", admin),
("player", player),
("reason", ban.Reason));
else
message = Loc.GetString("ban-manager-notify-discord",
("admin", admin),
("player", player),
("time", FormatTime(minutes)),
("reason", ban.Reason));

var payload = new WebhookPayload
{
Content = $"{message}\n{footer}",
};

await _discord.CreateMessage(hook, payload);
}
catch (Exception e)
{
_sawmill.Error($"Failed to send ban information to webhook!\n{e}");
}
}

/// <summary>
/// Send to webhook a role ban message.
/// </summary>
private async void SendRoleBanWebhook(ServerRoleBanDef ban, string player, string admin, uint? minutes)
{ //roleban is SHIT, it send a message to every role
try
{
if (_webhook is null)
return;

var hook = _webhook.Value.ToIdentifier();

var id = ban.Id?.ToString() ?? "?";
var rId = ban.RoundId?.ToString() ?? "?";

var footer = Loc.GetString("ban-manager-notify-discord-footer",
("round", rId),
("id", id));

var message = "...";

if (ban.ExpirationTime is null)
message = Loc.GetString("ban-manager-notify-discord-role-perma",
("admin", admin),
("role", ban.Role),
("player", player),
("reason", ban.Reason));
else
message = Loc.GetString("ban-manager-notify-discord-role",
("admin", admin),
("player", player),
("role", ban.Role),
("time", FormatTime(minutes)),
("reason", ban.Reason));

var payload = new WebhookPayload
{
Content = $"{message}\n{footer}",
};

await _discord.CreateMessage(hook, payload);
}
catch (Exception e)
{
_sawmill.Error($"Failed to send roleban information to webhook!\n{e}");
}
}

private string FormatTime(uint? time)
{
if (time is null)
return Loc.GetString("ban-manager-notify-discord-permanent");

var minutes = time ?? 0;

if (minutes < 60)
return Loc.GetString("ban-manager-notify-discord-format-minutes", ("minutes", minutes));

if (minutes < 1440)
return Loc.GetString("ban-manager-notify-discord-format-hours", ("hours", minutes / 60));

return Loc.GetString("ban-manager-notify-discord-format-days", ("days", minutes / 1440));
}
}
9 changes: 9 additions & 0 deletions Content.Server/Administration/Managers/BanManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public void Initialize()

_userDbData.AddOnLoadPlayer(CachePlayerData);
_userDbData.AddOnPlayerDisconnect(ClearPlayerData);

InitializeDiscord(); // Gabystation - Ban webhook
}

private async Task CachePlayerData(ICommonSession player, CancellationToken cancel)
Expand Down Expand Up @@ -181,6 +183,8 @@ public async void CreateServerBan(NetUserId? target, string? targetUsername, Net

_sawmill.Info(logMessage);
_chat.SendAdminAlert(logMessage);
var user = targetUsername ?? "?"; // Gabystation - ban webhook
SendServerBanWebhook(banDef, user, adminName, minutes); // Gabystation - ban webhook

KickMatchingConnectedPlayers(banDef, "newly placed ban");
}
Expand Down Expand Up @@ -242,6 +246,9 @@ public async void CreateRoleBan(NetUserId? target, string? targetUsername, NetUs
_systems.TryGetEntitySystem(out GameTicker? ticker);
int? roundId = ticker == null || ticker.RoundId == 0 ? null : ticker.RoundId;
var playtime = target == null ? TimeSpan.Zero : (await _db.GetPlayTimes(target.Value)).Find(p => p.Tracker == PlayTimeTrackingShared.TrackerOverall)?.TimeSpent ?? TimeSpan.Zero;
var adminName = banningAdmin == null // Gabystation - Ban Webhook
? Loc.GetString("system-user")
: (await _db.GetPlayerRecordByUserId(banningAdmin.Value))?.LastSeenUserName ?? Loc.GetString("system-user");

var banDef = new ServerRoleBanDef(
null,
Expand All @@ -266,6 +273,8 @@ public async void CreateRoleBan(NetUserId? target, string? targetUsername, NetUs

var length = expires == null ? Loc.GetString("cmd-roleban-inf") : Loc.GetString("cmd-roleban-until", ("expires", expires));
_chat.SendAdminAlert(Loc.GetString("cmd-roleban-success", ("target", targetUsername ?? "null"), ("role", role), ("reason", reason), ("length", length)));
var user = targetUsername ?? "?"; // Gabystation - ban webhook
SendRoleBanWebhook(banDef, user, adminName, minutes);

if (target != null && _playerManager.TryGetSessionById(target.Value, out var session))
{
Expand Down
14 changes: 14 additions & 0 deletions Content.Shared/_Gabystation/CCVar/CVars.Gaby.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Robust.Shared.Configuration;

namespace Content.Shared._Gabystation.CCVar;

[CVarDefs]
public sealed partial class GabyCVars
{
/// <summary>
/// Discord Webhooks
/// </summary>

public static readonly CVarDef<string> BanDiscordWebhook =
CVarDef.Create("discord.ban_webhook", "", CVar.SERVERONLY | CVar.CONFIDENTIAL);
}
24 changes: 24 additions & 0 deletions Resources/Locale/pt-BR/_Gabystation/webhook/ban-webhook.ftl
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
ban-manager-notify-discord = {$admin} baniu **{$player}** por {$time} por **"{$reason}"**
ban-manager-notify-discord-perma = {$admin} baniu **{$player}** *permanentemente* por **"{$reason}"**
ban-manager-notify-discord-role = {$admin} baniu **{$player}** de {$role} por {$time} por **"{$reason}"**
ban-manager-notify-discord-role-perma = {$admin} baniu **{$player}** de {$role} *permanentemente* por **"{$reason}"**
ban-manager-notify-discord-footer = -# Round {$round} - Id: {$id}
ban-manager-notify-discord-formart-days = {$days ->
[one] dia
*[other] dias
}
ban-manager-notify-discord-formart-hours = {$hours ->
[one] hora
*[other] horas
}
ban-manager-notify-discord-formart-minutes = {$minutes ->
[one] minuto
*[other] minutos
}

0 comments on commit 60accdf

Please sign in to comment.