All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.comhix.twitch.api.ChatProvider Maven / Gradle / Ivy

The newest version!
package de.comhix.twitch.api;

import de.comhix.twitch.api.data.ChatJoin;
import de.comhix.twitch.api.data.ChatMessage;
import de.comhix.twitch.api.data.ChatPart;
import de.comhix.twitch.api.irc.ChatConnector;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import org.jibble.pircbot.PircBot;

public class ChatProvider {
    public static final String TWITCH_IRC_SERVER = "irc.chat.twitch.tv";
    private String oAuthToken;
    private String name;
    private final String chatChannel;
    private ChatConnector bot;
    private boolean closed = false;

    public ChatProvider(String oAuthToken, String name, String chatChannel) {
        this.oAuthToken = oAuthToken;
        this.name = name;
        this.chatChannel = chatChannel;
    }

    private Observable getChatConnector() {
        if (bot != null) {
            return Observable.just(bot).observeOn(Schedulers.io());
        }
        return Observable.fromCallable(() -> {
            bot = new ChatConnector(name);
            bot.connect(TWITCH_IRC_SERVER, 6667, "oauth:" + oAuthToken);
            bot.joinChannel(chatChannel);
            return bot;
        }).observeOn(Schedulers.io());
    }

    public Observable onJoin() {
        checkClosed();
        return getChatConnector().flatMap(ChatConnector::onJoin);
    }

    public Observable onPart() {
        checkClosed();
        return getChatConnector().flatMap(ChatConnector::onPart);
    }

    public Observable onMessage() {
        checkClosed();
        return getChatConnector().flatMap(ChatConnector::onMessage);
    }

    public Completable sendMessage(String message) {
        checkClosed();
        return getChatConnector()
                .firstOrError()
                .doOnSuccess(chatConnector -> chatConnector.sendMessage(chatChannel, message))
                .toCompletable();
    }

    private void checkClosed(){
        if (closed) {
            throw new IllegalStateException("this TwitchApi instance is closed");
        }
    }

    void close() {
        this.closed=true;
        getChatConnector().subscribe(PircBot::disconnect);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy