summaryrefslogtreecommitdiff
path: root/bot/src/irc/message.hpp
blob: d0882fbdd452637a791752de19f65b93a0f385d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#pragma once

#include <functional>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <vector>

#include "../utils/string.hpp"

namespace bot {
  namespace irc {
    enum MessageType { Privmsg, Ping, Notice };
    std::optional<MessageType> define_message_type(const std::string &msg);

    struct IRCMessage {
        std::map<std::string, std::string> tags;
        std::string prefix, nick, command;
        std::vector<std::string> params;

        static std::optional<IRCMessage> from_string(std::string msg);
    };

    struct MessageSender {
        std::string login;
        std::string display_name;
        int id;

        std::map<std::string, std::string> badges;

        // More fields will be here
    };

    struct MessageSource {
        std::string login;
        int id;
    };

    template <MessageType T>
    struct Message;

    template <>
    struct Message<MessageType::Privmsg> {
        MessageSender sender;
        MessageSource source;
        std::string message;
    };

    template <MessageType T>
    std::optional<Message<T>> parse_message(const IRCMessage &msg) {
      if (T == MessageType::Privmsg && msg.command == "PRIVMSG") {
        MessageSender sender;
        MessageSource source;

        sender.login = msg.nick;
        sender.display_name = msg.tags.at("display-name");
        sender.id = std::stoi(msg.tags.at("user-id"));
        for (const std::string &badge :
             utils::string::split_text(msg.tags.at("badges"), ',')) {
          auto b = utils::string::split_text_n(badge, "/", 1);
          sender.badges.insert_or_assign(b[0], b[1]);
        }

        source.login = msg.params.front();
        if (source.login[0] == '#') {
          source.login = source.login.substr(1);
        }
        source.id = std::stoi(msg.tags.at("room-id"));

        Message<MessageType::Privmsg> message;
        message.sender = sender;
        message.source = source;
        message.message = msg.params.at(1);

        return message;
      }

      return std::nullopt;
    }

    template <MessageType T>
    struct MessageHandler;

    template <>
    struct MessageHandler<MessageType::Privmsg> {
        using fn = std::function<void(Message<Privmsg> message)>;
    };

  }
}