Skip to content

Commit

Permalink
Merge pull request #134 from nwesterhausen/dev
Browse files Browse the repository at this point in the history
non-player shouts
  • Loading branch information
nwesterhausen authored Nov 19, 2022
2 parents 974e57b + 88dc504 commit a6bdf5e
Show file tree
Hide file tree
Showing 14 changed files with 101 additions and 25 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cSpell.words": ["Leaderboard", "leaderboards"]
}
6 changes: 6 additions & 0 deletions Metadata/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ A full changelog for reference.

## History

### Version 2.0.4

Features:

- Adds a config option to enable sending non-player shouts to Discord. This is in the main config file and disabled by default.

### Version 2.0.3

Other Changes:
Expand Down
2 changes: 1 addition & 1 deletion Metadata/DiscordConnector-Nexus.readme
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
DISCORD CONNECTOR - 2.0.1
DISCORD CONNECTOR - 2.0.4
Connect your Valheim server to a Discord Webhook. Works for both dedicated and client-hosted servers. (Visit the github repo for a how-to guide.)

:: REQUIREMENTS ::
Expand Down
6 changes: 6 additions & 0 deletions Metadata/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ See the [current roadmap](https://github.com/nwesterhausen/valheim-discordconnec

## Changelog

### Version 2.0.4

Features:

- Adds a config option to enable sending non-player shouts to Discord. This is in the main config file and disabled by default.

### Version 2.0.3

Other Changes:
Expand Down
2 changes: 1 addition & 1 deletion Metadata/manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "DiscordConnector",
"version_number": "2.0.3",
"version_number": "2.0.4",
"website_url": "https://discordconnector.valheim.nwest.games/",
"description": "Connects your Valheim server to a Discord webhook. Works for both dedicated and client-hosted servers.",
"dependencies": ["denikson-BepInExPack_Valheim-5.4.1901"]
Expand Down
2 changes: 1 addition & 1 deletion Metadata/thunderstore.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ schemaVersion = "0.0.1"
[package]
namespace = "nwesterhausen"
name = "DiscordConnector"
versionNumber = "2.0.3"
versionNumber = "2.0.4"
description = "Connects your Valheim server to a Discord webhook. Works for both dedicated and client-hosted servers."
websiteUrl = "https://discordconnector.valheim.nwest.games/"
containsNsfwContent = false
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
[![Docs](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/docs.yml/badge.svg)](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/docs.yml)
[![Build](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/dotnet.yml/badge.svg)](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/dotnet.yml)
[![Publish](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/publish.yml/badge.svg)](https://github.com/nwesterhausen/valheim-discordconnector/actions/workflows/publish.yml)
[![GitHub release (latest by date)](https://img.shields.io/github/v/release/nwesterhausen/valheim-discordconnector?label=Github%20Release&style=flat&labelColor=%2332393F)](https://github.com/nwesterhausen/valheim-discordconnector/releases/latest)
[![Thunderstore.io](https://img.shields.io/badge/Thunderstore.io-2.0.4-%23375a7f?style=flat&labelColor=%2332393F)](https://valheim.thunderstore.io/package/nwesterhausen/DiscordConnector/)
[![NexusMods](https://img.shields.io/badge/NexusMods-2.0.4-%23D98F40?style=flat&labelColor=%2332393F)](https://www.nexusmods.com/valheim/mods/1551/)

Connect your Valheim server to Discord. ([See website for installation or configuration instructions](https://discordconnector.valheim.nwest.games/)). This plugin is largely based on [valheim-discord-notifier](https://github.com/aequasi/valheim-discord-notifier), but this plugin supports randomized messages, muting players, and Discord message embeds.

Plugin available on [Thunderstore.io](https://valheim.thunderstore.io/package/nwesterhausen/DiscordConnector/), [NexusMods](https://www.nexusmods.com/valheim/mods/1551/), and [Mod Vault](https://modvault.xyz/viewmod/132).

## Plugin Details

See [the README](Metadata/README.md) for the plugin.
Expand Down
6 changes: 6 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ A full changelog

## History

### Version 2.0.4

Features:

- Adds a config option to enable sending non-player shouts to Discord. This is in the main config file and disabled by default.

### Version 2.0.3

Other Changes:
Expand Down
1 change: 1 addition & 0 deletions docs/configuration-details.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Filename `games.nwest.valheim.discordconnector.cfg`
| Leaderboard update interval | 600 | Time in minutes between each leaderboard update sent to Discord. |
| Announce Player Firsts | true | Disable this setting to disable all extra announcements the first time each player does something. (Overwrites any individual setting.) |
| How many places to list in the top ranking leaderboards | 3 | Set how many places (1st, 2nd, 3rd by default) to display when sending the ranked leaderboard. |
| Send Non-Player Shouts to Discord | false | Enable this setting to have shouts which are performed by other mods/the server/non-players to be sent to Discord as well. |

!!! info "Stat Collection Details"

Expand Down
45 changes: 27 additions & 18 deletions src/Config/MainConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,29 @@ internal class MainConfig
// Main Settings
private ConfigEntry<string> webhookUrl;
private ConfigEntry<bool> discordEmbedMessagesToggle;
private ConfigEntry<string> mutedDiscordUserlist;
private ConfigEntry<string> mutedDiscordUserlistRegex;
private ConfigEntry<string> mutedDiscordUserList;
private ConfigEntry<string> mutedDiscordUserListRegex;
private ConfigEntry<bool> statsAnnouncementToggle;
private ConfigEntry<int> statsAnnouncementPeriod;
private ConfigEntry<bool> colectStatsToggle;
private ConfigEntry<bool> collectStatsToggle;
private ConfigEntry<bool> sendPositionsToggle;
private ConfigEntry<bool> announcePlayerFirsts;
private ConfigEntry<int> numberRankingsListed;
private ConfigEntry<string> playerLookupPreference;
private ConfigEntry<bool> allowNonPlayerShoutLogging;

public MainConfig(ConfigFile configFile)
{
config = configFile;
LoadConfig();
mutedPlayers = new List<string>(mutedDiscordUserlist.Value.Split(';'));
if (String.IsNullOrEmpty(@mutedDiscordUserlistRegex.Value))
mutedPlayers = new List<string>(mutedDiscordUserList.Value.Split(';'));
if (String.IsNullOrEmpty(mutedDiscordUserListRegex.Value))
{
mutedPlayersRegex = new Regex(@"a^");
}
else
{
mutedPlayersRegex = new Regex(@mutedDiscordUserlistRegex.Value);
mutedPlayersRegex = new Regex(mutedDiscordUserListRegex.Value);
}
}

Expand All @@ -52,14 +53,14 @@ public void ReloadConfig()
config.Reload();
config.Save();

mutedPlayers = new List<string>(mutedDiscordUserlist.Value.Split(';'));
if (String.IsNullOrEmpty(@mutedDiscordUserlistRegex.Value))
mutedPlayers = new List<string>(mutedDiscordUserList.Value.Split(';'));
if (String.IsNullOrEmpty(mutedDiscordUserListRegex.Value))
{
mutedPlayersRegex = new Regex(@"a^");
}
else
{
mutedPlayersRegex = new Regex(@mutedDiscordUserlistRegex.Value);
mutedPlayersRegex = new Regex(mutedDiscordUserListRegex.Value);
}
}

Expand All @@ -77,13 +78,13 @@ private void LoadConfig()
false,
"Enable this setting to use embeds in the messages sent to Discord. Currently this will affect the position details for the messages.");

mutedDiscordUserlist = config.Bind<string>(MAIN_SETTINGS,
mutedDiscordUserList = config.Bind<string>(MAIN_SETTINGS,
"Ignored Players",
"",
"It may be that you have some players that you never want to send Discord messages for. Adding a player name to this list will ignore them." + Environment.NewLine +
"Format should be a semicolon-separated list: Stuart;John McJohnny;Weird-name1");

mutedDiscordUserlistRegex = config.Bind<string>(MAIN_SETTINGS,
mutedDiscordUserListRegex = config.Bind<string>(MAIN_SETTINGS,
"Ignored Players (Regex)",
"",
"It may be that you have some players that you never want to send Discord messages for. This option lets you provide a regular expression to filter out players if their name matches." + Environment.NewLine +
Expand All @@ -94,7 +95,7 @@ private void LoadConfig()
true,
"Disable this setting to disable any positions/coordinates being sent with messages (e.g. players deaths or players joining/leaving). (Overwrites any individual setting.)");

colectStatsToggle = config.Bind<bool>(MAIN_SETTINGS,
collectStatsToggle = config.Bind<bool>(MAIN_SETTINGS,
"Collect Player Stats",
true,
"Disable this setting to disable all stat collection. (Overwrites any individual setting.)");
Expand All @@ -109,7 +110,7 @@ private void LoadConfig()
"Player Stats Notifications Period",
600,
"Set the number of minutes between a leader board announcement sent to discord." + Environment.NewLine +
"This time starts when the server is started. Default is set to 10 hours (600 mintues).");
"This time starts when the server is started. Default is set to 10 hours (600 minutes).");

announcePlayerFirsts = config.Bind<bool>(MAIN_SETTINGS,
"Announce Player Firsts",
Expand All @@ -131,6 +132,12 @@ private void LoadConfig()
RetrievalDiscernmentMethods.ByNameAndSteamID
})));

allowNonPlayerShoutLogging = config.Bind<bool>(MAIN_SETTINGS,
"Send Non-Player Shouts to Discord",
false,
"Enable this setting to have shouts which are performed by other mods/the server/non-players to be sent to Discord as well." + Environment.NewLine +
"Note: These are still subject to censure by the muted player regex and list.");


config.Save();
}
Expand All @@ -141,31 +148,33 @@ public string ConfigAsJson()
jsonString += "\"discord\":{";
jsonString += $"\"webhook\":\"{(string.IsNullOrEmpty(WebHookURL) ? "unset" : "REDACTED")}\",";
jsonString += $"\"fancierMessages\":\"{DiscordEmbedsEnabled}\",";
jsonString += $"\"ignoredPlayers\":\"{mutedDiscordUserlist.Value}\",";
jsonString += $"\"ignoredPlayersRegex\":\"{mutedDiscordUserlistRegex.Value}\"";
jsonString += $"\"ignoredPlayers\":\"{mutedDiscordUserList.Value}\",";
jsonString += $"\"ignoredPlayersRegex\":\"{mutedDiscordUserListRegex.Value}\"";
jsonString += "},";
jsonString += $"\"periodicLeaderboardEnabled\":\"{StatsAnnouncementEnabled}\",";
jsonString += $"\"periodicLeaderboardPeriodSeconds\":{StatsAnnouncementPeriod},";
jsonString += $"\"colectStatsEnabled\":\"{CollectStatsEnabled}\",";
jsonString += $"\"collectStatsEnabled\":\"{CollectStatsEnabled}\",";
jsonString += $"\"sendPositionsEnabled\":\"{SendPositionsEnabled}\",";
jsonString += $"\"announcePlayerFirsts\":\"{AnnouncePlayerFirsts}\",";
jsonString += $"\"numberRankingsListed\":\"{IncludedNumberOfRankings}\",";
jsonString += $"\"playerLookupPreference\":\"{RecordRetrievalDiscernmentMethod}\"";
jsonString += $"\"playerLookupPreference\":\"{RecordRetrievalDiscernmentMethod}\",";
jsonString += $"\"allowNonPlayerShoutLogging\":\"{AllowNonPlayerShoutLogging}\"";
jsonString += "}";
return jsonString;
}

public string WebHookURL => webhookUrl.Value;
public bool StatsAnnouncementEnabled => statsAnnouncementToggle.Value;
public int StatsAnnouncementPeriod => statsAnnouncementPeriod.Value;
public bool CollectStatsEnabled => colectStatsToggle.Value;
public bool CollectStatsEnabled => collectStatsToggle.Value;
public bool DiscordEmbedsEnabled => discordEmbedMessagesToggle.Value;
public bool SendPositionsEnabled => sendPositionsToggle.Value;
public List<string> MutedPlayers => mutedPlayers;
public Regex MutedPlayersRegex => mutedPlayersRegex;
public bool AnnouncePlayerFirsts => announcePlayerFirsts.Value;
public int IncludedNumberOfRankings => numberRankingsListed.Value;
public string RecordRetrievalDiscernmentMethod => playerLookupPreference.Value;
public bool AllowNonPlayerShoutLogging => allowNonPlayerShoutLogging.Value;

}
}
1 change: 1 addition & 0 deletions src/Config/PluginConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ public void ReloadConfig(string configPath)
public string RecordRetrievalDiscernmentMethod => mainConfig.RecordRetrievalDiscernmentMethod;
public List<string> MutedPlayers => mainConfig.MutedPlayers;
public Regex MutedPlayersRegex => mainConfig.MutedPlayersRegex;
public bool AllowNonPlayerShoutLogging => mainConfig.AllowNonPlayerShoutLogging;


// Messages.Server
Expand Down
15 changes: 14 additions & 1 deletion src/MessageTransformer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using UnityEngine;
using System.Text.RegularExpressions;
using UnityEngine;

namespace DiscordConnector
{
Expand All @@ -25,6 +26,9 @@ internal static class MessageTransformer
private const string EVENT_MSG = "%EVENT_MSG%";
private const string EVENT_PLAYERS = "%PLAYERS%";
private const string N = "%N%";

private static Regex OpenCaretRegex = new Regex(@"<[\w=]+>");
private static Regex CloseCaretRegex = new Regex(@"</[\w]+>");
private static string ReplaceVariables(string rawMessage)
{
return rawMessage
Expand Down Expand Up @@ -110,5 +114,14 @@ public static string FormatLeaderboardHeader(string rawMessage, int n)
return MessageTransformer.ReplaceVariables(rawMessage)
.Replace(N, n.ToString());
}

public static string CleanCaretFormatting(string str)
{
// regex.Replace(input, sub, 1);
string result = OpenCaretRegex.Replace(str, @"", 1);
result = CloseCaretRegex.Replace(result, @"", 1);

return result;
}
}
}
30 changes: 30 additions & 0 deletions src/Patches/ChatPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,36 @@ private static void Prefix(ref GameObject go, ref long senderID, ref Vector3 pos

if (peerInstance == null || peerInstance.m_socket == null)
{
// Check if we allow non-player shouts
if (Plugin.StaticConfig.AllowNonPlayerShoutLogging)
{
// Guard against chats that aren't shouts by non-players
if (type != Talker.Type.Shout)
{
Plugin.StaticLogger.LogDebug($"Ignored ping/join/leave from non-player {user}");
return;
}

string nonplayerHostName = "";
Plugin.StaticLogger.LogDebug($"Sending shout from '{user}' to discord: '{text}'");

// Only if we are sending shouts per the config should we send the shout
if (Plugin.StaticConfig.ChatShoutEnabled)
{
string userCleaned = MessageTransformer.CleanCaretFormatting(user);
string message = MessageTransformer.FormatPlayerMessage(Plugin.StaticConfig.ShoutMessage, userCleaned, nonplayerHostName, text);

if (message.Contains("%POS%"))
{
message.Replace("%POS%", "");
}

DiscordApi.SendMessage(message);
}
// Exit the function since we sent the message
return;
}

Plugin.StaticLogger.LogInfo($"Ignored shout from {user} because they aren't a real player");
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/PluginInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal static class PluginInfo
{
public const string PLUGIN_ID = "games.nwest.valheim.discordconnector";
public const string PLUGIN_NAME = "Valheim Discord Connector";
public const string PLUGIN_VERSION = "2.0.3";
public const string PLUGIN_VERSION = "2.0.4";
public const string PLUGIN_REPO_SHORT = "github: nwesterhausen/valheim-discordconnector";
public const string PLUGIN_AUTHOR = "Nicholas Westerhausen";
}
Expand Down

0 comments on commit a6bdf5e

Please sign in to comment.