Skip to content

Instantly share code, notes, and snippets.

@3ventic
Created November 4, 2019 19:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3ventic/d36dbd535eaddffae026bd03a66b352c to your computer and use it in GitHub Desktop.
Save 3ventic/d36dbd535eaddffae026bd03a66b352c to your computer and use it in GitHub Desktop.
Standalone C# message parser class for Twitch Messaging Interface (TMI)
using System.Collections.Generic;
using System.Text;
/*****************************************************************************
MIT License
Copyright (c) 2019 Werner Vänttinen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*****************************************************************************/
#nullable enable
namespace TwitchIrc
{
public enum IrcCommand
{
Unknown,
PrivMsg,
Notice,
Ping,
Pong,
Join,
Part,
HostTarget,
ClearChat,
UserState,
GlobalUserState,
Nick,
Pass,
Cap,
RPL_001,
RPL_002,
RPL_003,
RPL_004,
RPL_353,
RPL_366,
RPL_372,
RPL_375,
RPL_376,
Whisper,
RoomState,
Reconnect,
UserNotice,
ClearMsg
}
/// <summary>
/// IRC PRIVMSG information
/// </summary>
public struct IrcMessage
{
private readonly int hashCode;
/// <summary>
/// The first command parameter, which for PRIVMSG and many other commands will contain the channel name.
/// </summary>
public readonly string? Channel => Parameters != null && Parameters.Length > 0 ? Parameters[0] : null;
/// <summary>
/// Message body. This is equivalent to the Trailing part of the message.
/// </summary>
public readonly string? MessageBody => Trailing;
/// <summary>
/// Trailing part of the message.
/// </summary>
public readonly string? Trailing => Parameters != null && Parameters.Length > 1 ? Parameters[^1] : null;
/// <summary>
/// All the command parameters, including the trailing part of the message, if one exists.
/// </summary>
public readonly string[] Parameters;
/// <summary>
/// The user responsible for the message. Null for server messages.
/// </summary>
public readonly string? User;
/// <summary>
/// Hostmask of the user, e.g. 3v!3v@3v.tmi.twitch.tv
/// </summary>
public readonly string Hostmask;
/// <summary>
/// Raw Command
/// </summary>
public readonly IrcCommand Command;
/// <summary>
/// IRCv3 tags
/// </summary>
public readonly Dictionary<string, string> Tags;
/// <summary>
/// Create an IrcMessage
/// </summary>
/// <param name="command">IRC Command</param>
/// <param name="parameters">Command params</param>
/// <param name="hostmask">User</param>
/// <param name="tags">IRCv3 message tags</param>
public IrcMessage(IrcCommand command, string[] parameters, string hostmask, Dictionary<string, string>? tags = null)
{
if (tags == null)
{
tags = new Dictionary<string, string>();
}
int idx = hostmask.IndexOf('!');
User = idx != -1 ? hostmask.Substring(0, idx) : null;
Hostmask = hostmask;
Parameters = parameters;
Command = command;
Tags = tags;
hashCode = $"{command}.{string.Join(',', parameters)}.{hostmask}.{tags?.GetHashCode()}".GetHashCode();
}
public new string ToString()
{
var raw = new StringBuilder(32);
if (Tags != null)
{
string[] tags = new string[Tags.Count];
int i = 0;
foreach (KeyValuePair<string, string> tag in Tags)
{
tags[i] = tag.Key + "=" + tag.Value;
++i;
}
if (tags.Length > 0)
{
raw.Append("@").Append(string.Join(";", tags)).Append(" ");
}
}
if (Hostmask != null && Hostmask.Length > 0)
{
raw.Append(":").Append(Hostmask).Append(" ");
}
raw.Append(Command.ToString().ToUpper().Replace("RPL_", ""));
if (Parameters.Length > 0)
{
if (Parameters[0] != null && Parameters[0].Length > 0)
{
raw.Append(" ").Append(Parameters[0]);
}
if (Parameters.Length > 1 && Parameters[1] != null && Parameters[1].Length > 0)
{
raw.Append(" :").Append(Parameters[1]);
}
}
return raw.ToString();
}
private enum ParserState
{
STATE_NONE,
STATE_V3,
STATE_PREFIX,
STATE_COMMAND,
STATE_PARAM,
STATE_TRAILING
};
/// <summary>
/// Builds an IrcMessage from a raw string
/// </summary>
/// <param name="raw">Raw IRC message</param>
/// <returns>IrcMessage object</returns>
public static IrcMessage FromRawMessage(string raw)
{
var tagDict = new Dictionary<string, string>();
ParserState state = ParserState.STATE_NONE;
int[] starts = new int[] { 0, 0, 0, 0, 0, 0 };
int[] lens = new int[] { 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < raw.Length; ++i)
{
lens[(int)state] = i - starts[(int)state] - 1;
if (state == ParserState.STATE_NONE && raw[i] == '@')
{
state = ParserState.STATE_V3;
starts[(int)state] = ++i;
int start = i;
string? key = null;
for (; i < raw.Length; ++i)
{
if (raw[i] == '=')
{
key = raw[start..i];
start = i + 1;
}
else if (raw[i] == ';')
{
if (key == null)
tagDict[raw[start..i]] = "1";
else
tagDict[key] = raw[start..i];
start = i + 1;
}
else if (raw[i] == ' ')
{
if (key == null)
tagDict[raw[start..i]] = "1";
else
tagDict[key] = raw[start..i];
break;
}
}
}
else if (state < ParserState.STATE_PREFIX && raw[i] == ':')
{
state = ParserState.STATE_PREFIX;
starts[(int)state] = ++i;
}
else if (state < ParserState.STATE_COMMAND)
{
state = ParserState.STATE_COMMAND;
starts[(int)state] = i;
}
else if (state < ParserState.STATE_TRAILING && raw[i] == ':')
{
state = ParserState.STATE_TRAILING;
starts[(int)state] = ++i;
break;
}
else if (state == ParserState.STATE_COMMAND)
{
state = ParserState.STATE_PARAM;
starts[(int)state] = i;
}
while (i < raw.Length && raw[i] != ' ')
++i;
}
lens[(int)state] = raw.Length - starts[(int)state];
string cmd = raw.Substring(starts[(int)ParserState.STATE_COMMAND], lens[(int)ParserState.STATE_COMMAND]);
IrcCommand command = IrcCommand.Unknown;
switch (cmd)
{
case "PRIVMSG":
command = IrcCommand.PrivMsg;
break;
case "NOTICE":
command = IrcCommand.Notice;
break;
case "PING":
command = IrcCommand.Ping;
break;
case "PONG":
command = IrcCommand.Pong;
break;
case "HOSTTARGET":
command = IrcCommand.HostTarget;
break;
case "CLEARCHAT":
command = IrcCommand.ClearChat;
break;
case "USERSTATE":
command = IrcCommand.UserState;
break;
case "GLOBALUSERSTATE":
command = IrcCommand.GlobalUserState;
break;
case "NICK":
command = IrcCommand.Nick;
break;
case "JOIN":
command = IrcCommand.Join;
break;
case "PART":
command = IrcCommand.Part;
break;
case "PASS":
command = IrcCommand.Pass;
break;
case "CAP":
command = IrcCommand.Cap;
break;
case "001":
command = IrcCommand.RPL_001;
break;
case "002":
command = IrcCommand.RPL_002;
break;
case "003":
command = IrcCommand.RPL_003;
break;
case "004":
command = IrcCommand.RPL_004;
break;
case "353":
command = IrcCommand.RPL_353;
break;
case "366":
command = IrcCommand.RPL_366;
break;
case "372":
command = IrcCommand.RPL_372;
break;
case "375":
command = IrcCommand.RPL_375;
break;
case "376":
command = IrcCommand.RPL_376;
break;
case "WHISPER":
command = IrcCommand.Whisper;
break;
case "RECONNECT":
command = IrcCommand.Reconnect;
break;
case "ROOMSTATE":
command = IrcCommand.RoomState;
break;
case "USERNOTICE":
command = IrcCommand.UserNotice;
break;
case "CLEARMSG":
command = IrcCommand.ClearMsg;
break;
}
string parameters = raw.Substring(starts[(int)ParserState.STATE_PARAM], lens[(int)ParserState.STATE_PARAM]);
string message = raw.Substring(starts[(int)ParserState.STATE_TRAILING], lens[(int)ParserState.STATE_TRAILING]);
string hostmask = raw.Substring(starts[(int)ParserState.STATE_PREFIX], lens[(int)ParserState.STATE_PREFIX]);
return new IrcMessage(command, new string[] { parameters, message }, hostmask, tagDict);
}
public override bool Equals(object? obj) => obj is IrcMessage o && o.ToString() == ToString();
public override int GetHashCode() => hashCode;
public static bool operator ==(IrcMessage left, IrcMessage right) => left.Equals(right);
public static bool operator !=(IrcMessage left, IrcMessage right) => !(left == right);
}
}
#nullable restore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment