Skip to content

Start Reading from a channel

Brandon Smith edited this page Jul 25, 2021 · 4 revisions

First we need to establish a TwitchIRC Client. This client will allow us to communicate with the TwitchChat API.

Which we need to have some information first:

// File loading approach to enter in the oauth information.
TwitchIRC::TwitchIRC *twitchIRC = TwitchIRC::TwitchIRC::LoadFromFile("twitch.secret");

// Direct Approach to entering in the oauth information.
// Note: Username must be lowercase, and be exactly the same as the username that twitch displays.
// https://dev.twitch.tv/docs/irc/guide
TwitchIRC::TwitchIRC twitchIRC = TwitchIRC::TwitchIRC("Enter OAuth Token Here", "username");

After we initialize our TwitchIRC client, we want to setup some callbacks that the sdk can integrate with your code.

// Our listening callback.
void HandleRecv(TwitchIRC::Message _message)
{
    printf("<#%s> %s : %s\n", _message.GetChannelID().c_str(), _message.GetAuthor().GetUsername().c_str(), _message.GetString().c_str());
}
// Notifying twitchIRC of this callback.
// Note: `->` could be `.` depends on how the TwitchIRC class is initialized by value or by pointer.
twitchIRC->SetReceiveMessageCallback(HandleRecv);

Though we aren't just done yet, we need to join a channel, and connect to the irc server.

// Direct our TwitchIRC Client to this channel.
twitchIRC->Connect("channelname");

// Ensure that we are still connected.
while (twitchIRC->IsConnected())
{
    // Keep the network alive, and updating the callbacks.
    twitchIRC->Poll();
}

Full Solution:

#include "twitchirc.h"
#include <iostream>

// Listen to the incoming messages.
void HandleRecv(TwitchIRC::Message _message)
{
    printf("<#%s> %s : %s\n", _message.GetChannelID().c_str(), _message.GetAuthor().GetUsername().c_str(), _message.GetString().c_str());
}

int main()
{
    // Load the TwitchIRC OAuth information from a file.
    TwitchIRC::TwitchIRC twitchIRC = TwitchIRC::TwitchIRC::LoadFromFile("twitch.secret");

    if (twitchIRC != nullptr)
    {
        // Setup our callback.
        twitchIRC->SetReceiveMessageCallback(HandleRecv);

        // Direct our TwitchIRC Client to this channel.
        twitchIRC->Connect("ludwig");

        // Ensure that we are still connected.
        while (twitchIRC->IsConnected())
        {
            // Keep the network alive, and updating the callbacks.
            twitchIRC->Poll();
        }
        return 0;
    }

    return 1;
}
Clone this wiki locally