TwitchLib / TwitchLib.PubSub

PubSub component of TwitchLib.
38 stars 51 forks source link

Unhandled Message JSON #98

Open Omsad opened 3 years ago

Omsad commented 3 years ago

When processing the following json a null reference exception is thrown.

{
   "type":"MESSAGE",
   "data":{
      "topic":"chat_moderator_actions.80153562.80153562",
      "message":"{\"type\":\"channel_terms_action\",\"data\":{\"type\":\"add_permitted_term\",\"id\":\"REMOVED\",\"text\":\"crazy ur crazy\",\"requester_id\":\"REMOVED\",\"requester_login\":\"REMOVED\",\"channel_id\":\"REMOVED\",\"expires_at\":\"2021-08-19T06:13:40.169705384Z\",\"updated_at\":\"2021-08-19T05:13:40.169704026Z\",\"from_automod\":true}}"
   }
}

There aren't the created_by, created_by_user_id or target_user_id properties, which means a null reference exception is being thrown by the ChatModeratorActions constructor.

So I've changed the constructor of ChatModeratorActions to:

public ChatModeratorActions(string jsonStr)
{
    var json = JObject.Parse(jsonStr).SelectToken("data");
    Type = json.SelectToken("type")?.ToString();
    ModerationAction = json.SelectToken("moderation_action")?.ToString();
    if (json.SelectToken("args") != null)
        foreach (var arg in json.SelectToken("args"))
            Args.Add(arg.ToString());
    CreatedBy = json.SelectToken("created_by")?.ToString();
    CreatedByUserId = json.SelectToken("created_by_user_id")?.ToString();
    TargetUserId = json.SelectToken("target_user_id")?.ToString();
}

E.g. added ? to json.SelectToken("created_by") etc... The above will then parse but you have to modify the message case in the switch statement to handle that the ModerationAction is null, e.g. update:

case "chat_moderator_actions":
...
switch (cma?.ModerationAction.ToLower())

to

case "chat_moderator_actions":
...
switch (cma?.ModerationAction?.ToLower())

It will then go through the UnaccountedFor handler rather than throwing the exception.