Skip to content

Commit

Permalink
Merge pull request #6 from imi-tat0r/respect-chat-triggers
Browse files Browse the repository at this point in the history
Respect chat triggers
  • Loading branch information
imi-tat0r committed Feb 16, 2024
2 parents d718809 + 8ceae8f commit 374783c
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 43 deletions.
94 changes: 57 additions & 37 deletions DiscordChat/DiscordService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ 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 @@ -60,31 +61,32 @@ private async Task Initialize(CancellationToken stoppingToken)
Console.WriteLine("[DiscordChatSync] Discord token is not set. Please set it in the config file.");
return;
}

Console.WriteLine("[DiscordChatSync] Logging in");

c.Log += (msg) =>
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
};
c.Ready += Ready;
c.MessageReceived += MessageReceived;

// login and start the bot
await c.LoginAsync(TokenType.Bot, _plugin.Config.DiscordToken);
await c.StartAsync();

_client = c;

await Task.Delay(-1, stoppingToken);

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

private async Task Ready()
{
Console.WriteLine("[DiscordChatSync] Ready?");

if (_client == null)
return;

Expand All @@ -93,14 +95,15 @@ private async Task Ready()
// update info
await _client.SetStatusAsync(UserStatus.Online);
await _client.SetGameAsync($"Syncing chat messages");

Console.WriteLine("[DiscordChatSync] Ready!");
}
catch (Exception ex)
{
Console.WriteLine("[DiscordChatSync] Exception in Ready: " + ex.Message);
}
}

private Task MessageReceived(SocketMessage m)
{
// see if the author is the guild user
Expand All @@ -109,7 +112,8 @@ private Task MessageReceived(SocketMessage m)
return Task.CompletedTask;

// see if the message is from the correct channel
if (msg.Channel.Id != _plugin.Config.SyncChannelId && !_plugin.Config.AdditionalReadChannelIds.Contains(msg.Channel.Id))
if (msg.Channel.Id != _plugin.Config.SyncChannelId &&
!_plugin.Config.AdditionalReadChannelIds.Contains(msg.Channel.Id))
return Task.CompletedTask;

var roles = user.Roles.ToList();
Expand All @@ -121,32 +125,33 @@ private Task MessageReceived(SocketMessage m)
highestRole.Color.G.ToString("X2") +
highestRole.Color.B.ToString("X2")
: "#ffffff";

Server.NextWorldUpdate(() =>
{
var firstLine = $"[Discord - {msg.Channel.Name}] {ColorHelper.HexColorToChatColor(hexColor)}{user.DisplayName}{ChatColors.Default}: ";
var firstLine =
$"[Discord - {msg.Channel.Name}] {ColorHelper.HexColorToChatColor(hexColor)}{user.DisplayName}{ChatColors.Default}: ";
// replace emojis with their string counter part
// split the message by new lines
// remove any empty lines (since it would print the previous line again)
var messageSplit = Emojis.ReplaceEmojisInString(msg.CleanContent)
.Split('\n')
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToArray();
// if there's any part in the string that's >100 characters without any whitespace, we need to add a whitespace there
// if there's any part in the string that's >50 characters without any whitespace, we need to add a whitespace there
for (var i = 0; i < messageSplit.Length; i++)
messageSplit[i] = Chat.ForceBreakLongWords(messageSplit[i]);
// if we only have one line, inline the message
if (messageSplit.Length == 1)
firstLine += messageSplit[0];
Server.PrintToChatAll(firstLine);
if (messageSplit.Length <= 1)
if (messageSplit.Length <= 1)
return;
foreach (var line in messageSplit)
Server.PrintToChatAll(line);
});
Expand All @@ -157,47 +162,61 @@ private Task MessageReceived(SocketMessage m)
#endregion

#region CS2

public HookResult OnClientCommandGlobalPre(CCSPlayerController? player, CommandInfo info)
{
var command = info.GetArg(0);
if (info.ArgCount < 2)
return HookResult.Continue;

var command = info.GetArg(0);
var message = info.GetArg(1);

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

if (string.IsNullOrWhiteSpace(message))
return HookResult.Continue;

return command == "say" ?
OnSay(player, info) :
OnSayTeam(player, info);
var isChatTrigger = CoreConfig.PublicChatTrigger.Contains(message[0].ToString()) ||
CoreConfig.SilentChatTrigger.Contains(message[0].ToString());

if (_plugin.Config.IgnoreChatTriggers && isChatTrigger)
return HookResult.Continue;

return command == "say" ? OnSay(player, info) : OnSayTeam(player, info);
}

private HookResult OnSay(CCSPlayerController? player, CommandInfo info)
{
Console.WriteLine("[DiscordChatSync] OnSay");
if (!ShouldSyncMessage(info.GetArg(1), out var message))
if (!ShouldSyncMessage(info.GetArg(1), out var message))
return HookResult.Continue;

if (player != null && !player.IsPlayer())
return HookResult.Continue;

SendDiscordMessage(false, player, message);

return HookResult.Continue;
}

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

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

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

SendDiscordMessage(true, player!, message);

return HookResult.Continue;
}

public void OnMapStart(string mapName)
{
// print any message to specific channel
Expand All @@ -220,23 +239,24 @@ public void OnMapStart(string mapName)
private bool ShouldSyncMessage(string inMessage, out string outMessage)
{
outMessage = inMessage.Trim();

if (string.IsNullOrWhiteSpace(outMessage))
return false;

// no prefix means we want all messages
if (string.IsNullOrEmpty(_plugin.Config.MessagePrefix))
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)
Expand Down Expand Up @@ -272,7 +292,7 @@ private void SendDiscordMessage(bool teamOnly, CCSPlayerController? player, stri
_ => ""
};
}

var embed = new EmbedBuilder()
.WithAuthor(chatType + (player?.PlayerName ?? "Console"))
.WithDescription(message)
Expand Down
2 changes: 1 addition & 1 deletion DiscordChat/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace DiscordChat;
public class DiscordChatSync : BasePlugin, IPluginConfig<DiscordChatSyncConfig>
{
public override string ModuleName => "CS2-DiscordChatSync";
public override string ModuleVersion => "1.0.2";
public override string ModuleVersion => "1.0.3";
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
1 change: 1 addition & 0 deletions DiscordChat/PluginConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ public class DiscordChatSyncConfig : BasePluginConfig
[JsonPropertyName("AdditionalReadChannelIds")] public List<ulong> AdditionalReadChannelIds { get; set; } = new();
[JsonPropertyName("SyncTeamChat")] public bool SyncTeamChat { get; set; }
[JsonPropertyName("MessagePrefix")] public string MessagePrefix { get; set; } = "";
[JsonPropertyName("IgnoreChatTriggers")] public bool IgnoreChatTriggers { get; set; } = true;
}
11 changes: 6 additions & 5 deletions README.MD
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# CS2 Discord Chat Sync (1.0.0)
# CS2 Discord Chat Sync (1.0.3)
![image](https://du.hurenso.hn/r/Gyc70A.png)

# About
Expand All @@ -25,17 +25,18 @@ CS2 Discord Chat Sync is a plugin for Counter-Strike 2 that syncs chat between t
![perms](https://du.hurenso.hn/r/kTDZ8O.png)
4. Add your Discord bot token and channel id to the config file
4.1. Located at `addons/counterstrikesharp/configs/plugins/DiscordChat/DiscordChat.json`
4. Restart your server~~~~
4. Restart your server

# Config
```
```json
{
"DiscordToken": "", // your discord bot token
"SyncChannelId": 0, // the channel id to sync from and to
"AdditionalReadChannelIds": [], // additional channels to read from (for news and announcements)
"SyncTeamChat": false, // if false, team chat will not be synced
"MessagePrefix": "", // if empty, no prefix is needed
"ConfigVersion": 1
"MessagePrefix": "", // only messages starting with the prefix will be synced
"IgnoreChatTriggers": true // chat and silent triggers from core config will be ignored
"ConfigVersion": 1, // do not change
}
```

Expand Down

0 comments on commit 374783c

Please sign in to comment.