use of com.sx4.bot.entities.twitch.TwitchStreamer in project Sx4 by sx4-discord-bot.
the class TwitchNotificationCommand method preview.
@Command(value = "preview", description = "Preview a twitch notification")
@CommandId(503)
@Examples({ "twitch notification preview 5e45ce6d3688b30ee75201ae" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void preview(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
Document data = event.getMongo().getTwitchNotification(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), Projections.include("streamerId", "message"));
if (data == null) {
event.replyFailure("I could not find that notification").queue();
return;
}
String streamerId = data.getString("streamerId");
Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?id=" + streamerId).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getBot().getConfig().getTwitchClientId()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
List<Document> entries = json.getList("data", Document.class);
if (entries.isEmpty()) {
event.replyFailure("The twitch streamer for that notification no longer exists").queue();
return;
}
Document entry = entries.get(0);
Document message = new JsonFormatter(data.get("message", TwitchManager.DEFAULT_MESSAGE)).addVariable("stream", new TwitchStream("0", TwitchStreamType.LIVE, "https://cdn.discordapp.com/attachments/344091594972069888/969319515714371604/twitch-test-preview.png", "Preview Title", "Preview Game", OffsetDateTime.now())).addVariable("streamer", new TwitchStreamer(entry.getString("id"), entry.getString("display_name"), entry.getString("login"))).parse();
try {
MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(message).build()).queue();
} catch (IllegalArgumentException e) {
event.replyFailure(e.getMessage()).queue();
}
});
}
use of com.sx4.bot.entities.twitch.TwitchStreamer in project Sx4 by sx4-discord-bot.
the class TwitchEndpoint method postTwitch.
@POST
@Path("twitch")
public Response postTwitch(final String body, @HeaderParam("Twitch-Eventsub-Message-Id") String messageId, @HeaderParam("Twitch-Eventsub-Message-Timestamp") String timestamp, @HeaderParam("Twitch-Eventsub-Message-Signature") String signature, @HeaderParam("Twitch-Eventsub-Message-Type") String type) {
String hash;
try {
hash = "sha256=" + HmacUtility.getSignatureHex(this.bot.getConfig().getTwitchEventSecret(), messageId + timestamp + body, HmacUtility.HMAC_SHA256);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
return Response.status(500).build();
}
if (!hash.equals(signature)) {
return Response.status(401).build();
}
if (!this.messageIds.add(messageId)) {
return Response.status(204).build();
}
Document data = Document.parse(body);
Document subscription = data.get("subscription", Document.class);
TwitchSubscriptionType subscriptionType = TwitchSubscriptionType.fromIdentifier(subscription.getString("type"));
if (subscriptionType == null) {
return Response.status(204).build();
}
if (type.equals("webhook_callback_verification")) {
Document subscriptionData = new Document("subscriptionId", subscription.getString("id")).append("streamerId", subscription.getEmbedded(List.of("condition", "broadcaster_user_id"), String.class)).append("type", subscriptionType.getId());
this.bot.getMongo().insertTwitchSubscription(subscriptionData).whenComplete(MongoDatabase.exceptionally());
return Response.ok(data.getString("challenge")).build();
}
if (subscriptionType == TwitchSubscriptionType.ONLINE) {
Document event = data.get("event", Document.class);
String streamId = event.getString("id");
String streamerName = event.getString("broadcaster_user_name");
String streamerId = event.getString("broadcaster_user_id");
String streamerLogin = event.getString("broadcaster_user_login");
TwitchStreamType streamType = TwitchStreamType.fromIdentifier(event.getString("type"));
OffsetDateTime streamStart = OffsetDateTime.parse(event.getString("started_at"));
Request request = new Request.Builder().url("https://api.twitch.tv/helix/streams?user_id=" + streamerId).addHeader("Authorization", "Bearer " + this.bot.getTwitchConfig().getToken()).addHeader("Client-Id", this.bot.getConfig().getTwitchClientId()).build();
this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
Document stream = json.getList("data", Document.class).stream().filter(d -> d.getString("type").equals(streamType.getIdentifier())).findFirst().orElse(null);
if (stream == null) {
System.err.println("Failed to retrieve stream data for streamer id: " + streamerId);
return;
}
String query = "?" + this.random.nextString(5) + "=" + this.random.nextString(5);
String title = stream.getString("title");
String game = stream.getString("game_name");
String preview = "https://static-cdn.jtvnw.net/previews-ttv/live_user_" + streamerLogin + "-1320x744.png" + query;
this.bot.getTwitchManager().onEvent(new TwitchStreamStartEvent(new TwitchStream(streamId, streamType, preview, title, game, streamStart), new TwitchStreamer(streamerId, streamerName, streamerLogin)));
});
} else if (subscriptionType == TwitchSubscriptionType.REVOCATION) {
String status = subscription.getString("status");
if (status.equals("user_removed")) {
this.bot.getMongo().deleteManyTwitchNotifications(Filters.eq("streamerId", subscription.getEmbedded(List.of("condition", "broadcaster_user_id"), String.class))).whenComplete(MongoDatabase.exceptionally());
}
}
return Response.status(204).build();
}
use of com.sx4.bot.entities.twitch.TwitchStreamer in project Sx4 by sx4-discord-bot.
the class TwitchNotificationCommand method list.
@Command(value = "list", description = "View all the twitch notifications you have setup throughout your server")
@CommandId(502)
@Examples({ "twitch notification list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
List<Document> notifications = event.getMongo().getTwitchNotifications(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("streamerId", "channelId", "message")).into(new ArrayList<>());
if (notifications.isEmpty()) {
event.replyFailure("You have no notifications setup in this server").queue();
return;
}
List<String> streamers = notifications.stream().map(d -> d.getString("streamerId")).distinct().collect(Collectors.toList());
int size = streamers.size();
List<CompletableFuture<Map<String, TwitchStreamer>>> futures = new ArrayList<>();
for (int i = 0; i < Math.ceil(size / 100D); i++) {
List<String> splitStreamers = streamers.subList(i * 100, Math.min((i + 1) * 100, size));
String ids = String.join("&id=", splitStreamers);
Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?id=" + ids).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getBot().getConfig().getTwitchClientId()).build();
CompletableFuture<Map<String, TwitchStreamer>> future = new CompletableFuture<>();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
List<Document> entries = json.getList("data", Document.class);
Map<String, TwitchStreamer> names = new HashMap<>();
for (Document entry : entries) {
String id = entry.getString("id");
names.put(id, new TwitchStreamer(id, entry.getString("display_name"), entry.getString("login")));
}
future.complete(names);
});
futures.add(future);
}
FutureUtility.allOf(futures).whenComplete((maps, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Map<String, TwitchStreamer> names = new HashMap<>();
for (Map<String, TwitchStreamer> map : maps) {
names.putAll(map);
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), notifications).setSelect().setAuthor("Twitch Notifications", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
TwitchStreamer streamer = names.get(data.getString("streamerId"));
return String.format("%s - [%s](%s)", data.getObjectId("_id").toHexString(), streamer == null ? "Unknown" : streamer.getName(), streamer == null ? "https://twitch.tv" : streamer.getUrl());
});
paged.execute(event);
});
}
Aggregations