Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Send messages using Helix API #5200

Merged
merged 4 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@
- Dev: Added signal to invalidate paint buffers of channel views without forcing a relayout. (#5123)
- Dev: Specialize `Atomic<std::shared_ptr<T>>` if underlying standard library supports it. (#5133)
- Dev: Added the `developer_name` field to the Linux AppData specification. (#5138)
- Dev: Twitch messages can be sent using Twitch's Helix API instead of IRC (disabled by default). (#5200)

## 2.4.6

Expand Down
8 changes: 8 additions & 0 deletions mocks/include/mocks/Helix.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,14 @@ class Helix : public IHelix
(FailureCallback<HelixSendShoutoutError, QString> failureCallback)),
(override));

// send message
MOCK_METHOD(
void, sendChatMessage,
(HelixSendMessageArgs args,
ResultCallback<HelixSentMessage> successCallback,
(FailureCallback<HelixSendMessageError, QString> failureCallback)),
(override));

MOCK_METHOD(void, update, (QString clientId, QString oauthToken),
(override));

Expand Down
142 changes: 127 additions & 15 deletions src/providers/twitch/TwitchIrcServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,94 @@ using namespace std::chrono_literals;

namespace {

using namespace chatterino;

const QString BTTV_LIVE_UPDATES_URL = "wss://sockets.betterttv.net/ws";
const QString SEVENTV_EVENTAPI_URL = "wss://events.7tv.io/v3";

void sendHelixMessage(const std::shared_ptr<TwitchChannel> &channel,
const QString &message, const QString &replyParentId = {})
{
getHelix()->sendChatMessage(
{
.broadcasterID = channel->roomId(),
.senderID =
getIApp()->getAccounts()->twitch.getCurrent()->getUserId(),
.message = message,
.replyParentMessageID = replyParentId,
},
[weak = std::weak_ptr(channel)](const auto &res) {
auto chan = weak.lock();
if (!chan)
{
return;
}

if (res.isSent)
{
return;
}

auto errorMessage = [&] {
if (res.dropReason)
{
return makeSystemMessage(res.dropReason->message);
}
return makeSystemMessage("Your message was not sent.");
}();
chan->addMessage(errorMessage);
},
[weak = std::weak_ptr(channel)](auto error, const auto &message) {
auto chan = weak.lock();
if (!chan)
{
return;
}

using Error = decltype(error);

auto errorMessage = [&]() -> QString {
switch (error)
{
case Error::MissingText:
return "You can't send an empty message.";
case Error::BadRequest:
return "Failed to send message: " + message;
case Error::Forbidden:
return "You are not allowed to send messages in this "
"channel.";
case Error::MessageTooLarge:
return "Your message was too long.";
case Error::UserMissingScope:
return "Missing required scope. Re-login with your "
"account and try again.";
case Error::Forwarded:
return message;
case Error::Unknown:
default:
return "Unknown error: " + message;
}
}();
chan->addMessage(makeSystemMessage(errorMessage));
});
}

/// Returns true if chat messages should be sent over Helix
bool shouldSendHelixChat()
{
switch (getSettings()->chatSendProtocol)
{
case ChatSendProtocol::Helix:
return true;
case ChatSendProtocol::Default:
case ChatSendProtocol::IRC:
return false;
default:
assert(false && "Invalid chat protocol value");
return false;
}
}

} // namespace

namespace chatterino {
Expand Down Expand Up @@ -139,13 +224,24 @@ std::shared_ptr<Channel> TwitchIrcServer::createChannel(
// no Channel's should live
// NOTE: CHANNEL_LIFETIME
std::ignore = channel->sendMessageSignal.connect(
[this, channel = channel.get()](auto &chan, auto &msg, bool &sent) {
this->onMessageSendRequested(channel, msg, sent);
[this, channel = std::weak_ptr(channel)](auto &chan, auto &msg,
bool &sent) {
auto c = channel.lock();
if (!c)
{
return;
}
this->onMessageSendRequested(c, msg, sent);
});
std::ignore = channel->sendReplySignal.connect(
[this, channel = channel.get()](auto &chan, auto &msg, auto &replyId,
bool &sent) {
this->onReplySendRequested(channel, msg, replyId, sent);
[this, channel = std::weak_ptr(channel)](auto &chan, auto &msg,
auto &replyId, bool &sent) {
auto c = channel.lock();
if (!c)
{
return;
}
this->onReplySendRequested(c, msg, replyId, sent);
});

return channel;
Expand Down Expand Up @@ -436,7 +532,8 @@ bool TwitchIrcServer::hasSeparateWriteConnection() const
// return getSettings()->twitchSeperateWriteConnection;
}

bool TwitchIrcServer::prepareToSend(TwitchChannel *channel)
bool TwitchIrcServer::prepareToSend(
const std::shared_ptr<TwitchChannel> &channel)
{
std::lock_guard<std::mutex> guard(this->lastMessageMutex_);

Expand Down Expand Up @@ -487,8 +584,9 @@ bool TwitchIrcServer::prepareToSend(TwitchChannel *channel)
return true;
}

void TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel,
const QString &message, bool &sent)
void TwitchIrcServer::onMessageSendRequested(
const std::shared_ptr<TwitchChannel> &channel, const QString &message,
bool &sent)
{
sent = false;

Expand All @@ -498,13 +596,21 @@ void TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel,
return;
}

this->sendMessage(channel->getName(), message);
if (shouldSendHelixChat())
{
sendHelixMessage(channel, message);
}
else
{
this->sendMessage(channel->getName(), message);
}

sent = true;
}

void TwitchIrcServer::onReplySendRequested(TwitchChannel *channel,
const QString &message,
const QString &replyId, bool &sent)
void TwitchIrcServer::onReplySendRequested(
const std::shared_ptr<TwitchChannel> &channel, const QString &message,
const QString &replyId, bool &sent)
{
sent = false;

Expand All @@ -514,9 +620,15 @@ void TwitchIrcServer::onReplySendRequested(TwitchChannel *channel,
return;
}

this->sendRawMessage("@reply-parent-msg-id=" + replyId + " PRIVMSG #" +
channel->getName() + " :" + message);

if (shouldSendHelixChat())
{
sendHelixMessage(channel, message, replyId);
}
else
{
this->sendRawMessage("@reply-parent-msg-id=" + replyId + " PRIVMSG #" +
channel->getName() + " :" + message);
}
sent = true;
}

Expand Down
11 changes: 6 additions & 5 deletions src/providers/twitch/TwitchIrcServer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,13 @@ class TwitchIrcServer final : public AbstractIrcServer,
bool hasSeparateWriteConnection() const override;

private:
void onMessageSendRequested(TwitchChannel *channel, const QString &message,
bool &sent);
void onReplySendRequested(TwitchChannel *channel, const QString &message,
const QString &replyId, bool &sent);
void onMessageSendRequested(const std::shared_ptr<TwitchChannel> &channel,
const QString &message, bool &sent);
void onReplySendRequested(const std::shared_ptr<TwitchChannel> &channel,
const QString &message, const QString &replyId,
bool &sent);

bool prepareToSend(TwitchChannel *channel);
bool prepareToSend(const std::shared_ptr<TwitchChannel> &channel);

std::mutex lastMessageMutex_;
std::queue<std::chrono::steady_clock::time_point> lastMessagePleb_;
Expand Down
88 changes: 88 additions & 0 deletions src/providers/twitch/api/Helix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2840,6 +2840,94 @@ void Helix::sendShoutout(
.execute();
}

// https://dev.twitch.tv/docs/api/reference/#send-chat-message
void Helix::sendChatMessage(
HelixSendMessageArgs args, ResultCallback<HelixSentMessage> successCallback,
FailureCallback<HelixSendMessageError, QString> failureCallback)
{
using Error = HelixSendMessageError;

QJsonObject json{{
{"broadcaster_id", args.broadcasterID},
{"sender_id", args.senderID},
{"message", args.message},
}};
if (!args.replyParentMessageID.isEmpty())
{
json["reply_parent_message_id"] = args.replyParentMessageID;
}

this->makePost("chat/messages", {})
.json(json)
.onSuccess([successCallback](const NetworkResult &result) {
if (result.status() != 200)
{
qCWarning(chatterinoTwitch)
<< "Success result for sending chat message was "
<< result.formatError() << "but we expected it to be 200";
}
auto json = result.parseJson();

successCallback(HelixSentMessage(
json.value("data").toArray().at(0).toObject()));
})
.onError([failureCallback](const NetworkResult &result) -> void {
if (!result.status())
{
failureCallback(Error::Unknown, result.formatError());
return;
}

const auto obj = result.parseJson();
auto message =
obj["message"].toString(u"Twitch internal server error"_s);

switch (*result.status())
{
case 400: {
failureCallback(Error::Unknown, message);
}
break;

case 401: {
if (message.startsWith("User access token requires the",
Qt::CaseInsensitive))
{
failureCallback(Error::UserMissingScope, message);
}
else
{
failureCallback(Error::Forwarded, message);
}
}
break;

case 403: {
failureCallback(Error::Forbidden, message);
}
break;

case 422: {
failureCallback(Error::MessageTooLarge, message);
}
break;

case 500: {
failureCallback(Error::Unknown, message);
}
break;

default: {
qCWarning(chatterinoTwitch)
<< "Helix send chat message, unhandled error data:"
<< result.formatError() << result.getData() << obj;
failureCallback(Error::Unknown, message);
}
}
})
.execute();
}

NetworkRequest Helix::makeRequest(const QString &url, const QUrlQuery &urlQuery,
NetworkRequestType type)
{
Expand Down
Loading
Loading