Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import org.jibble.pircbot.PircBot;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import org.jsoup.Connection;
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import org.jsoup.select.Elements;
- public class InfoBot extends PircBot {
- private final Pattern urlPattern;
- public InfoBot() throws Exception {
- this.urlPattern = Pattern.compile("(https?://[^\\s]+)");
- this.setName("ExampleBot");
- this.setVerbose(true);
- this.connect("irc.efnet.nl");
- this.joinChannel("#example");
- }
- public void onMessage(final String channel, final String sender, final String login, final String hostname, final String message) {
- final Matcher matcher = this.urlPattern.matcher(message);
- while (matcher.find()) {
- final String match = matcher.group();
- try {
- final Connection connection = Jsoup.connect(match);
- final Document document = connection.get();
- final Elements elements = document.select("link[type=application/json+oembed]");
- final Element element = elements.first();
- final String href = element.attr("href");
- final URL url = new URL(href);
- final URLConnection urlConnection = url.openConnection();
- final InputStream inputStream = urlConnection.getInputStream();
- final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
- final JSONParser parser = new JSONParser();
- final JSONObject object = (JSONObject) parser.parse(inputStreamReader);
- final String authorName = (String) object.get("author_name");
- final String providerName = (String) object.get("provider_name");
- final String title = (String) object.get("title");
- final String type = (String) object.get("type");
- final String post = String.format("%s %s by %s: %s", providerName, type, authorName, title);
- this.sendMessage(channel, post);
- } catch (final Exception exception) {
- exception.printStackTrace();
- }
- }
- }
- public static void main(final String[] args) throws Exception {
- final InfoBot infoBot = new InfoBot();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement