Skip to content

Commit

Permalink
Merge pull request #3 from imi-tat0r/CS2-Tags-fix
Browse files Browse the repository at this point in the history
Retreiving chat via global command handler
  • Loading branch information
imi-tat0r committed Feb 12, 2024
2 parents a4d30dc + 4fbf99c commit 682236d
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 53 deletions.
131 changes: 84 additions & 47 deletions DiscordChat/DiscordService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using Discord;
using Discord.WebSocket;
using DiscordChat.Extensions;
using DiscordChat.Helper;
using Microsoft.Extensions.Hosting;

namespace DiscordChat;
Expand All @@ -25,7 +27,6 @@ protected override Task ExecuteAsync(CancellationToken stoppingToken)
Console.WriteLine("[DiscordChatSync] Starting DiscordService");
return Initialize(stoppingToken);
}

public override async Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("[DiscordChatSync] Stopping DiscordService");
Expand Down Expand Up @@ -80,7 +81,6 @@ private async Task Initialize(CancellationToken stoppingToken)

Console.WriteLine("[DiscordChatSync] Why are we here? Just to suffer?");
}

private async Task Ready()
{
Console.WriteLine("[DiscordChatSync] Ready?");
Expand All @@ -92,7 +92,7 @@ private async Task Ready()
{
// update info
await _client.SetStatusAsync(UserStatus.Online);
await _client.SetCustomStatusAsync($"Syncing chat messages");
await _client.SetGameAsync($"Syncing chat messages");

Console.WriteLine("[DiscordChatSync] Ready!");
}
Expand All @@ -101,11 +101,8 @@ private async Task Ready()
Console.WriteLine("[DiscordChatSync] Exception in Ready: " + ex.Message);
}
}

private Task MessageReceived(SocketMessage m)
{
Console.WriteLine("[DiscordChatSync] Message received");

// see if the author is the guild user
var author = m.Author;
if (author is not SocketGuildUser user || user.IsBot || user.IsWebhook || m is not SocketUserMessage msg)
Expand Down Expand Up @@ -153,40 +150,96 @@ private Task MessageReceived(SocketMessage m)

#region CS2

public HookResult OnPlayerChat(EventPlayerChat eventPlayerChat, GameEventInfo info)
public HookResult OnClientCommandGlobalPre(CCSPlayerController? player, CommandInfo info)
{
// account for team chat setting
if (!_plugin.Config.SyncTeamChat && eventPlayerChat.Teamonly)
var command = info.GetArg(0);

if (command != "say" && command != "say_team")
return HookResult.Continue;

var message = eventPlayerChat.Text.Trim();
return command == "say" ?
OnSay(player, info) :
OnSayTeam(player, info);
}
public HookResult OnSay(CCSPlayerController? player, CommandInfo info)
{
Console.WriteLine("[DiscordChatSync] OnSay");
Console.WriteLine(info.GetArg(1));
if (!ShouldSyncMessage(info.GetArg(1), out var message))
return HookResult.Continue;

if (!player.IsPlayer())
return HookResult.Continue;

SendDiscordMessage(false, player!, message);

return HookResult.Continue;
}
public HookResult OnSayTeam(CCSPlayerController? player, CommandInfo info)
{
Console.WriteLine("[DiscordChatSync] OnSayTeam");
Console.WriteLine(info.GetArg(1));
if (!_plugin.Config.SyncTeamChat)
return HookResult.Continue;

if (!ShouldSyncMessage(info.GetArg(1), out var message))
return HookResult.Continue;

// account for optional message prefix
if (!string.IsNullOrEmpty(_plugin.Config.MessagePrefix))
{
// ignore messages that don't start with the prefix
if (!message.StartsWith(_plugin.Config.MessagePrefix))
return HookResult.Continue;

// remove the prefix from the message
message = message[_plugin.Config.MessagePrefix.Length..].Trim();
}

// we only want to sync chat messages from players
var player = Utilities.GetPlayerFromUserid(eventPlayerChat.Userid);
if (!player.IsPlayer())
return HookResult.Continue;

SendDiscordMessage(true, player!, message);

return HookResult.Continue;
}
public void OnMapStart(string mapName)
{
// print any message to specific channel
if (_client?.GetChannel(_plugin.Config.SyncChannelId) is not IMessageChannel channel)
return;

var embed = new EmbedBuilder()
.WithAuthor("System")
.WithDescription("Changed map to " + mapName)
.WithColor(Color.Blue)
.Build();

channel.SendMessageAsync(embed: embed);
}

#endregion

#region Helpers

private bool ShouldSyncMessage(string inMessage, out string outMessage)
{
outMessage = inMessage.Trim();

// no prefix means we want all messages
if (string.IsNullOrEmpty(_plugin.Config.MessagePrefix))
return true;

// ignore messages that don't start with the prefix
if (!outMessage.StartsWith(_plugin.Config.MessagePrefix))
return false;

// remove the prefix from the message
outMessage = outMessage[_plugin.Config.MessagePrefix.Length..].Trim();

return true;
}
private void SendDiscordMessage(bool teamOnly, CCSPlayerController player, string message)
{
if (_plugin.Config.SyncChannelId == 0)
{
for (var i = 0; i < 3; i++)
Console.WriteLine("[DiscordChatSync] Sync channel id is not set. Please set it in the config file.");
return HookResult.Continue;
return;
}

// print any message to specific channel
if (_client?.GetChannel(_plugin.Config.SyncChannelId) is not IMessageChannel channel)
return HookResult.Continue;
return;

var teamColor = player.TeamNum switch
{
Expand All @@ -198,42 +251,26 @@ public HookResult OnPlayerChat(EventPlayerChat eventPlayerChat, GameEventInfo in

var discordColor = new Color(teamColor.R, teamColor.G, teamColor.B);

var chatType = "[ALL] ";
var chatType = "[ALL] - ";

if (eventPlayerChat.Teamonly)
if (teamOnly)
{
chatType = player.TeamNum switch
{
(byte)CsTeam.Terrorist => "[T] ",
(byte)CsTeam.CounterTerrorist => "[CT] ",
(byte)CsTeam.Spectator => "[Spec] ",
(byte)CsTeam.Terrorist => "[T]",
(byte)CsTeam.CounterTerrorist => "[CT]",
(byte)CsTeam.Spectator => "[Spec]",
_ => ""
};
}

var embed = new EmbedBuilder()
.WithAuthor(chatType + player.PlayerName)
.WithAuthor(chatType + " - " + player.PlayerName)
.WithDescription(message)
.WithColor(discordColor)
.Build();

channel.SendMessageAsync(embed: embed);

return HookResult.Continue;
}
public void OnMapStart(string mapName)
{
// print any message to specific channel
if (_client?.GetChannel(_plugin.Config.SyncChannelId) is not IMessageChannel channel)
return;

var embed = new EmbedBuilder()
.WithAuthor("System")
.WithDescription("Changed map to " + mapName)
.WithColor(Color.Blue)
.Build();

channel.SendMessageAsync(embed: embed);
}

#endregion
Expand Down
2 changes: 1 addition & 1 deletion DiscordChat/Extensions/PlayerControllerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ public static class PlayerControllerExtensions
{
internal static bool IsPlayer(this CCSPlayerController? player)
{
return player is { IsValid: true, IsHLTV: false, IsBot: false, UserId: not null };
return player is { IsValid: true, IsHLTV: false, IsBot: false, UserId: not null, SteamID: >0 };
}
}
2 changes: 1 addition & 1 deletion DiscordChat/Color.cs → DiscordChat/Helper/Color.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Drawing;
using CounterStrikeSharp.API.Modules.Utils;

namespace DiscordChat;
namespace DiscordChat.Helper;

public static class ColorHelper
{
Expand Down
13 changes: 9 additions & 4 deletions DiscordChat/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace DiscordChat;

public class DiscordChatSync : BasePlugin, IPluginConfig<DiscordChatSyncConfig>
{
public override string ModuleName => "DiscordChatSync";
public override string ModuleVersion => "1.0.0";
public override string ModuleName => "CS2-DiscordChatSync";
public override string ModuleVersion => "1.0.1";
public override string ModuleAuthor => "imi-tat0r";
public override string ModuleDescription => "Syncs chat messages from and to a discord channel.";
public DiscordChatSyncConfig Config { get; set; } = new();
Expand Down Expand Up @@ -42,7 +43,7 @@ public override void Load(bool hotReload)
Console.WriteLine("[DiscordChatSync] Add services to DI container");
var serviceCollection = new ServiceCollection();

serviceCollection.AddSingleton<DiscordChatSync>(this);
serviceCollection.AddSingleton(this);
serviceCollection.AddSingleton<DiscordService>();

_serviceProvider = serviceCollection.BuildServiceProvider();
Expand All @@ -51,10 +52,14 @@ public override void Load(bool hotReload)
Console.WriteLine("[DiscordChatSync] Registering event handlers");

var discordService = _serviceProvider.GetRequiredService<DiscordService>();
RegisterEventHandler<EventPlayerChat>(discordService.OnPlayerChat);
RegisterListener<Listeners.OnMapStart>(discordService.OnMapStart);
Console.WriteLine("[DiscordChatSync] Event handlers registered");

Console.WriteLine("[DiscordChatSync] Registering global command handler");

AddCommandListener(null, discordService.OnClientCommandGlobalPre);
Console.WriteLine("[DiscordChatSync] Global command handler registered");

discordService.StartAsync(new CancellationToken());

Console.WriteLine("[DiscordChatSync] Plugin loaded");
Expand Down

0 comments on commit 682236d

Please sign in to comment.