Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import java.io.IOException;
- import java.net.URL;
- import java.time.Duration;
- import java.util.Optional;
- /**
- * A class that gets the image from a telegram channel post
- *
- * @author t.me/Chase_22
- * @author t.me/MouamleH
- * @version 0.0.1
- */
- public class TgChannelParser {
- private static int READ_TIMEOUT = (int) Duration.ofSeconds(5).toMillis();
- private Document html;
- /**
- * @param url the post url
- * @throws IOException throws an exception if the url was not found
- * or the timeout was reached
- */
- public TgChannelParser(String url) throws IOException {
- html = Jsoup.parse(new URL(url + "?embed=1"), READ_TIMEOUT);
- }
- /**
- * @return an Optional containing the image url if the post contains an image
- */
- public Optional<String> getImageUrl() {
- Element element = html.selectFirst(".tgme_widget_message_photo_wrap");
- if (element == null) {
- element = html.selectFirst(".link_preview_image");
- }
- if (element != null) {
- String style = element.attr("style");
- String imageUrl = style.substring(style.indexOf("'") + 1, style.lastIndexOf("'"));
- return Optional.of(imageUrl);
- }
- return Optional.empty();
- }
- /**
- * @return true if the post is present, false otherwise
- */
- public boolean isPresent() {
- return !html.toString().contains("Post not found");
- }
- /**
- * @return true if the post contains an image, false otherwise
- */
- public boolean containsImage() {
- return getImageUrl().isPresent();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement