Skip to content

Link/Image previews for tags #616

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

Merged
merged 10 commits into from
Nov 16, 2022
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
4 changes: 4 additions & 0 deletions application/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ dependencies {

implementation 'io.mikael:urlbuilder:2.0.9'

implementation 'org.jsoup:jsoup:1.15.3'

implementation 'org.scilab.forge:jlatexmath:1.0.7'
implementation 'org.scilab.forge:jlatexmath-font-greek:1.0.7'
implementation 'org.scilab.forge:jlatexmath-font-cyrillic:1.0.7'
Expand All @@ -68,6 +70,8 @@ dependencies {

implementation 'com.github.freva:ascii-table:1.8.0'

implementation 'io.github.url-detector:url-detector:0.1.23'

implementation 'com.github.ben-manes.caffeine:caffeine:3.1.1'

testImplementation 'org.mockito:mockito-core:4.8.0'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
package org.togetherjava.tjbot.commands.tags;

import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.AutoCompleteQuery;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
import net.dv8tion.jda.api.utils.FileUpload;
import net.dv8tion.jda.api.utils.messages.MessageEditBuilder;

import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.commands.utils.LinkPreview;
import org.togetherjava.tjbot.commands.utils.LinkPreviews;
import org.togetherjava.tjbot.commands.utils.StringDistances;

import java.time.Instant;
import java.util.Collection;
import java.util.*;

/**
* Implements the {@code /tag} command which lets the bot respond content of a tag that has been
Expand Down Expand Up @@ -47,28 +55,6 @@ public TagCommand(TagSystem tagSystem) {
"Optionally, the user who you want to reply to", false));
}

@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
String id = event.getOption(ID_OPTION).getAsString();
OptionMapping replyToUserOption = event.getOption(REPLY_TO_USER_OPTION);

if (tagSystem.handleIsUnknownTag(id, event)) {
return;
}

ReplyCallbackAction message = event
.replyEmbeds(new EmbedBuilder().setDescription(tagSystem.getTag(id).orElseThrow())
.setFooter(event.getUser().getName() + " • used " + event.getCommandString())
.setTimestamp(Instant.now())
.setColor(TagSystem.AMBIENT_COLOR)
.build());

if (replyToUserOption != null) {
message = message.setContent(replyToUserOption.getAsUser().getAsMention());
}
message.queue();
}

@Override
public void onAutoComplete(CommandAutoCompleteInteractionEvent event) {
AutoCompleteQuery focusedOption = event.getFocusedOption();
Expand All @@ -86,4 +72,68 @@ public void onAutoComplete(CommandAutoCompleteInteractionEvent event) {

event.replyChoices(choices).queue();
}

@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
String id = event.getOption(ID_OPTION).getAsString();
OptionMapping replyToUserOption = event.getOption(REPLY_TO_USER_OPTION);

if (tagSystem.handleIsUnknownTag(id, event)) {
return;
}

String tagContent = tagSystem.getTag(id).orElseThrow();
MessageEmbed contentEmbed = new EmbedBuilder().setDescription(tagContent)
.setFooter(event.getUser().getName() + " • used " + event.getCommandString())
.setTimestamp(Instant.now())
.setColor(TagSystem.AMBIENT_COLOR)
.build();

Optional<String> replyToUserMention = Optional.ofNullable(replyToUserOption)
.map(OptionMapping::getAsUser)
.map(User::getAsMention);

List<String> links = LinkPreviews.extractLinks(tagContent)
.stream()
.limit(Message.MAX_EMBED_COUNT - 1L)
.toList();
if (links.isEmpty()) {
// No link previews
ReplyCallbackAction message = event.replyEmbeds(contentEmbed);
replyToUserMention.ifPresent(message::setContent);
message.queue();
return;
}

event.deferReply().queue();

respondWithLinkPreviews(event.getHook(), links, contentEmbed, replyToUserMention);
}

private void respondWithLinkPreviews(InteractionHook eventHook, List<String> links,
MessageEmbed contentEmbed, Optional<String> replyToUserMention) {
LinkPreviews.createLinkPreviews(links).thenAccept(linkPreviews -> {
if (linkPreviews.isEmpty()) {
// Did not find any previews
MessageEditBuilder message = new MessageEditBuilder().setEmbeds(contentEmbed);
replyToUserMention.ifPresent(message::setContent);
eventHook.editOriginal(message.build()).queue();
return;
}

Collection<MessageEmbed> embeds = new ArrayList<>();
embeds.add(contentEmbed);
embeds.addAll(linkPreviews.stream().map(LinkPreview::embed).toList());

List<FileUpload> attachments = linkPreviews.stream()
.map(LinkPreview::attachment)
.filter(Objects::nonNull)
.toList();

MessageEditBuilder message =
new MessageEditBuilder().setEmbeds(embeds).setFiles(attachments);
replyToUserMention.ifPresent(message::setContent);
eventHook.editOriginal(message.build()).queue();
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package org.togetherjava.tjbot.commands.utils;

import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.utils.FileUpload;

import javax.annotation.Nullable;

import java.io.InputStream;

/**
* Preview of a URL for display as embed in Discord.
* <p>
* If the attachment is not {@code null}, it has to be made available to the message as well, for
* example
* {@code new MessageCreateBuilder().addEmbeds(linkPreview.embed).addFiles(linkPreview.attachment)}.
*
* @param attachment the thumbnail image of the link, referenced within the embed, if present
* @param embed the embed representing the preview of the link
*/
public record LinkPreview(@Nullable FileUpload attachment, MessageEmbed embed) {
/**
* Creates a new instance of this link preview, but with the given thumbnail.
* <p>
* Any previous thumbnail is overridden and replaced.
*
* @param thumbnailName the name of the thumbnail, with extension, e.g. {@code foo.png}
* @param thumbnail the thumbnails data as raw data stream
* @return this preview, but with a thumbnail
*/
LinkPreview withThumbnail(String thumbnailName, InputStream thumbnail) {
return createWithThumbnail(embed, thumbnailName, thumbnail);
}

/**
* Creates a link preview that only has a thumbnail and no other text.
*
* @param thumbnailName the name of the thumbnail, with extension, e.g. {@code foo.png}
* @param thumbnail the thumbnails data as raw data stream
* @return the thumbnail as link preview
*/
static LinkPreview ofThumbnail(String thumbnailName, InputStream thumbnail) {
return createWithThumbnail(null, thumbnailName, thumbnail);
}

/**
* Creates a link preview that consists of the given text.
* <p>
* Use {@link #withThumbnail(String, InputStream)} to decorate the preview also with a thumbnail
* image.
*
* @param title the title of the preview, if present
* @param url the link to the resource this preview represents
* @param description the description of the preview, if present
* @return the text as link preview
*/
static LinkPreview ofText(@Nullable String title, String url, @Nullable String description) {
MessageEmbed embed =
new EmbedBuilder().setTitle(title, url).setDescription(description).build();

return new LinkPreview(null, embed);
}

private static LinkPreview createWithThumbnail(@Nullable MessageEmbed embedToDecorate,
String thumbnailName, InputStream thumbnail) {
FileUpload attachment = FileUpload.fromData(thumbnail, thumbnailName);
MessageEmbed embed =
new EmbedBuilder(embedToDecorate).setThumbnail("attachment://" + thumbnailName)
.build();

return new LinkPreview(attachment, embed);
}
}
Loading