From 4217f56c11ef827d6afa7c9b36c310f6421bf5f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wieland=20Sch=C3=B6bl?= Date: Thu, 13 Aug 2020 20:08:58 +0200 Subject: [PATCH] initial commit --- .gitignore | 6 + build.gradle | 29 ++++ gradle.properties | 1 + gradlew | 172 +++++++++++++++++++++++ gradlew.bat | 84 +++++++++++ settings.gradle | 2 + src/main/kotlin/Admin.kt | 122 ++++++++++++++++ src/main/kotlin/Bot.kt | 19 +++ src/main/kotlin/Channels.kt | 87 ++++++++++++ src/main/kotlin/Cli.kt | 57 ++++++++ src/main/kotlin/DataIO.kt | 18 +++ src/main/kotlin/Main.kt | 34 +++++ src/main/kotlin/extensions/Color.kt | 11 ++ src/main/kotlin/model/BlogPostPreview.kt | 25 ++++ src/main/kotlin/web/BlogPostParser.kt | 24 ++++ src/main/kotlin/web/SiteWatcher.kt | 36 +++++ 16 files changed, 727 insertions(+) create mode 100644 .gitignore create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/kotlin/Admin.kt create mode 100644 src/main/kotlin/Bot.kt create mode 100644 src/main/kotlin/Channels.kt create mode 100644 src/main/kotlin/Cli.kt create mode 100644 src/main/kotlin/DataIO.kt create mode 100644 src/main/kotlin/Main.kt create mode 100644 src/main/kotlin/extensions/Color.kt create mode 100644 src/main/kotlin/model/BlogPostPreview.kt create mode 100644 src/main/kotlin/web/BlogPostParser.kt create mode 100644 src/main/kotlin/web/SiteWatcher.kt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a1e41f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +servers.json +admin.json +/build +/.gradle +/gradle +/.idea \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..48b8fdd --- /dev/null +++ b/build.gradle @@ -0,0 +1,29 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' version '1.3.61' + id 'org.jetbrains.kotlin.plugin.serialization' version '1.3.61' +} + +group 'de.wulkanat' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() + jcenter() +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" + + compile 'net.dv8tion:JDA:4.2.0_189' + compile 'org.jsoup:jsoup:1.13.1' + compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0" +} + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +apply plugin: 'kotlinx-serialization' diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..29e08e8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..af6708f --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6d57edc --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..71bac74 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'HytaleUpdateBot' + diff --git a/src/main/kotlin/Admin.kt b/src/main/kotlin/Admin.kt new file mode 100644 index 0000000..505eab2 --- /dev/null +++ b/src/main/kotlin/Admin.kt @@ -0,0 +1,122 @@ +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonConfiguration +import net.dv8tion.jda.api.EmbedBuilder +import net.dv8tion.jda.api.JDA +import net.dv8tion.jda.api.entities.MessageEmbed +import net.dv8tion.jda.api.entities.User +import java.awt.Color + +object Admin { + val userId: Long + val token: String + val updateMs: Long + + init { + val admin = Json(JsonConfiguration.Stable).parse(AdminFile.serializer(), ADMIN_FILE.readText()) + userId = admin.adminId + token = admin.token + updateMs = admin.updateMs + } + + var jda: JDA? = null + set(value) { + field = value + + admin = value?.retrieveUserById(userId)?.complete() + if (admin == null) { + kotlin.io.println("Connection to Admin failed!") + } else { + kotlin.io.println("Connected to ${admin!!.name}. No further errors will be printed here.") + } + } + private var admin: User? = null + + fun println(msg: String) { + sendDevMessage( + EmbedBuilder() + .setTitle(msg) + .setColor(Color.WHITE) + .build(), + msg + ) + } + + fun printlnBlocking(msg: String) { + senDevMessageBlocking( + EmbedBuilder() + .setTitle(msg) + .setColor(Color.WHITE) + .build(), + msg + ) + } + + fun error(msg: String, error: Exception) { + sendDevMessage( + EmbedBuilder() + .setTitle(msg) + .setDescription(error.message) + .setColor(Color.RED) + .build() + , "$msg\n\n${error.message}" + ) + } + + fun errorBlocking(msg: String, error: Exception) { + senDevMessageBlocking( + EmbedBuilder() + .setTitle(msg) + .setDescription(error.message) + .setColor(Color.RED) + .build() + , "$msg\n\n${error.message}" + ) + } + + fun warning(msg: String) { + sendDevMessage( + EmbedBuilder() + .setTitle(msg) + .setColor(Color.YELLOW) + .build(), + msg + ) + } + + fun ready() { + sendDevMessage( + EmbedBuilder() + .setTitle("Now watching for new Hytale Blogposts every ${updateMs/1000}s") + .setDescription(Channels.getServerNames().joinToString("\n")) + .setColor(Color.GREEN) + .build(), + "Now watching for new Hytale BlogPosts" + ) + } + + fun silent(msg: String) { + kotlin.io.println(msg) + } + + private fun senDevMessageBlocking(messageEmbed: MessageEmbed, fallback: String) { + val devChannel = admin?.openPrivateChannel() ?: kotlin.run { + kotlin.io.println(fallback) + return + } + + devChannel.queue { + it.sendMessage(messageEmbed).complete() + } + } + + private fun sendDevMessage(messageEmbed: MessageEmbed, fallback: String) { + val devChannel = admin?.openPrivateChannel() ?: kotlin.run { + kotlin.io.println(fallback) + return + } + + devChannel.queue { + it.sendMessage(messageEmbed).queue() + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/Bot.kt b/src/main/kotlin/Bot.kt new file mode 100644 index 0000000..668eb1c --- /dev/null +++ b/src/main/kotlin/Bot.kt @@ -0,0 +1,19 @@ +import net.dv8tion.jda.api.events.message.MessageReceivedEvent +import net.dv8tion.jda.api.hooks.ListenerAdapter + +class Bot : ListenerAdapter() { + override fun onMessageReceived(event: MessageReceivedEvent) { + val message = event.message + + if (message.contentRaw == "!ping") { + val channel = message.channel + val time = System.currentTimeMillis() + + channel.sendMessage("Pong!") + .queue { + it.editMessageFormat("Pong: %d ms", System.currentTimeMillis() - time) + .queue() + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/Channels.kt b/src/main/kotlin/Channels.kt new file mode 100644 index 0000000..9b1e4c7 --- /dev/null +++ b/src/main/kotlin/Channels.kt @@ -0,0 +1,87 @@ +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonConfiguration +import kotlinx.serialization.list +import net.dv8tion.jda.api.JDA +import net.dv8tion.jda.api.Permission +import net.dv8tion.jda.api.entities.MessageEmbed +import net.dv8tion.jda.api.entities.TextChannel + +object Channels { + var jda: JDA? = null + val json = Json(JsonConfiguration.Stable) + + /** + * List of (ServerID, ChannelID) + */ + val channels: MutableList = + json.parse(DiscordChannel.serializer().list, SERVERS_FILE.readText()).toMutableList() + + fun sentToAll(messageEmbed: MessageEmbed) { + if (jda == null) + return + + for (channel_pair in channels) { + val channel = jda!!.getTextChannelById(channel_pair.id) ?: continue + + if (channel_pair.mentionedRole != null) { + val message = if (channel_pair.mentionedRole == "everyone") { + "New Blogpost @everyone" + } else { + "New Blogpost <@&${channel_pair.mentionedRole}>" + } + channel.sendMessage(message).queue() + } + channel.sendMessage(messageEmbed).queue() + } + } + + fun checkEveryonePermission() { + for (channel_pair in channels) { + val channel = jda!!.getTextChannelById(channel_pair.id) ?: continue + + if (channel_pair.mentionedRole == "everyone" && + channel.guild.selfMember.hasPermission(Permission.MESSAGE_MENTION_EVERYONE) + ) { + Admin.warning("Cannot mention everyone on ${channel.guild.name}") + } else if (channel.guild.selfMember.hasPermission(Permission.MESSAGE_WRITE)) { + Admin.warning("Cannot send any messages on ${channel.guild.name}") + } + + } + } + + fun getServerNames(): List { + if (jda == null) + return listOf() + + return channels.map { + val channel = jda!!.getTextChannelById(it.id) + if (channel == null) { + Admin.warning("Channel ${it.id} is no longer active!") + return@map "**${it.id}** *(inactive)*" + } + + val role = if (it.mentionedRole == null) { + "" + } else if (it.mentionedRole == "everyone") { + " @everyone" + } else { + " @${channel.guild.getRoleById(it.mentionedRole)?.name}" + } + "**${channel.guild.name}**\n#${channel.name}${role}" + } + } + + fun testServerId(id: Long): TextChannel? { + return jda?.getTextChannelById(id) + } + + fun addChannel(id: Long, role: String?) { + channels.add(DiscordChannel(id, role)) + saveChannels() + } + + private fun saveChannels() { + SERVERS_FILE.writeText(json.stringify(DiscordChannel.serializer().list, channels)) + } +} \ No newline at end of file diff --git a/src/main/kotlin/Cli.kt b/src/main/kotlin/Cli.kt new file mode 100644 index 0000000..af72a85 --- /dev/null +++ b/src/main/kotlin/Cli.kt @@ -0,0 +1,57 @@ +import model.BlogPostPreview +import net.dv8tion.jda.api.events.message.MessageReceivedEvent +import net.dv8tion.jda.api.hooks.ListenerAdapter +import web.SiteWatcher +import kotlin.system.exitProcess + +class Cli : ListenerAdapter() { + override fun onMessageReceived(event: MessageReceivedEvent) { + val msg = event.message.contentRaw + if (event.author.idLong != Admin.userId || + !msg.startsWith("%!") + ) { + return + } + val command = msg.removePrefix("%!").split(" ") + + try { + when (command[0]) { + "stop" -> exitProcess(1) + "fakeUpdate" -> { + SiteWatcher.newestBlog = BlogPostPreview( + title = "FakePost", + imgUrl = "", + fullPostUrl = "", + author = "wulkanat", + date = "now", + description = "Lorem Ipsum" + ) + + Admin.println("Posting on next update cycle.") + } + "addChannel" -> { + val channel = command[1].toLong() + var role: String? = null + if (command.size == 3) { + role = command[2] + } + val serverChannel = Channels.testServerId(channel) + val roleName = serverChannel?.guild?.getRoleById(role ?: "") + + if (serverChannel != null) { + if (roleName != null || role == null || role == "everyone") { + Channels.addChannel(channel, role) + Admin.println("Added server '${serverChannel.name}' for role '${roleName ?: role}'") + } else { + Admin.warning("Unknown Role ID") + } + } else { + Admin.warning("Unknown Channel ID") + } + } + } + } catch (e: ArrayIndexOutOfBoundsException) { + // noop + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/DataIO.kt b/src/main/kotlin/DataIO.kt new file mode 100644 index 0000000..98a53f9 --- /dev/null +++ b/src/main/kotlin/DataIO.kt @@ -0,0 +1,18 @@ +import kotlinx.serialization.Serializable +import java.io.File + +@Serializable +data class DiscordChannel( + val id: Long, + val mentionedRole: String? = null +) + +@Serializable +data class AdminFile( + val adminId: Long, + val token: String, + val updateMs: Long +) + +val SERVERS_FILE = File("servers.json") +val ADMIN_FILE = File("admin.json") diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt new file mode 100644 index 0000000..6a2a59f --- /dev/null +++ b/src/main/kotlin/Main.kt @@ -0,0 +1,34 @@ +import net.dv8tion.jda.api.JDABuilder +import net.dv8tion.jda.api.entities.Activity +import net.dv8tion.jda.api.requests.GatewayIntent +import web.SiteWatcher +import kotlin.concurrent.timer + +fun main() { + // TODO: move toke into file + val builder = JDABuilder.createLight(Admin.token, + GatewayIntent.GUILD_MESSAGES, GatewayIntent.DIRECT_MESSAGES) + .addEventListeners(Bot()) + .setActivity(Activity.watching("for new Blogposts")) + .build() + + builder.addEventListener(Cli()) + builder.awaitReady() + + Channels.jda = builder + Admin.jda = builder + Admin.ready() + + Runtime.getRuntime().addShutdownHook(object : Thread() { + override fun run() { + println("Shutting down...") + Admin.printlnBlocking("Shutting down") + } + }) + + timer("Updater", daemon = true, initialDelay = 0L, period = Admin.updateMs) { + if (SiteWatcher.hasNewBlogPost()) { + Channels.sentToAll(SiteWatcher.newestBlog!!.toMessageEmbed()) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/extensions/Color.kt b/src/main/kotlin/extensions/Color.kt new file mode 100644 index 0000000..8455564 --- /dev/null +++ b/src/main/kotlin/extensions/Color.kt @@ -0,0 +1,11 @@ +package extensions + +import java.awt.Color + +fun hex2Rgb(colorStr: String): Color { + return Color( + Integer.valueOf(colorStr.substring(1, 3), 16), + Integer.valueOf(colorStr.substring(3, 5), 16), + Integer.valueOf(colorStr.substring(5, 7), 16) + ) +} \ No newline at end of file diff --git a/src/main/kotlin/model/BlogPostPreview.kt b/src/main/kotlin/model/BlogPostPreview.kt new file mode 100644 index 0000000..ac2bd80 --- /dev/null +++ b/src/main/kotlin/model/BlogPostPreview.kt @@ -0,0 +1,25 @@ +package model + +import net.dv8tion.jda.api.EmbedBuilder +import net.dv8tion.jda.api.entities.MessageEmbed +import extensions.hex2Rgb + +data class BlogPostPreview( + val title: String, + val description: String, + val date: String, + val author: String, + val imgUrl: String, + val fullPostUrl: String +) { + fun toMessageEmbed(): MessageEmbed { + return EmbedBuilder() + .setTitle(this.title, this.fullPostUrl) + .setDescription(this.description) + .setAuthor(this.author) + .setThumbnail(this.imgUrl) + .setFooter(this.date, "https://www.hytale.com/static/images/logo-h.png") + .setColor(hex2Rgb("#337fb0")) + .build() + } +} \ No newline at end of file diff --git a/src/main/kotlin/web/BlogPostParser.kt b/src/main/kotlin/web/BlogPostParser.kt new file mode 100644 index 0000000..663d4c7 --- /dev/null +++ b/src/main/kotlin/web/BlogPostParser.kt @@ -0,0 +1,24 @@ +package web + +import model.BlogPostPreview +import org.jsoup.nodes.Document +import org.jsoup.nodes.Element + +object BlogPostParser { + fun getFistBlog(doc: Document): BlogPostPreview { + val posts = doc.getElementsByClass("postWrapper") + return parseBlog(posts.first()) + } + + private fun parseBlog(elm: Element): BlogPostPreview { + + return BlogPostPreview( + title = elm.getElementsByClass("post__details__heading").first().text(), + imgUrl = elm.getElementsByClass("post__image__frame").first().child(0).attr("src"), + fullPostUrl = elm.child(0).absUrl("href"), + date = elm.getElementsByClass("post__details__meta__date").first().text(), + author = elm.getElementsByClass("post__details__meta__author").first().text(), + description = elm.getElementsByClass("post__details__body").first().text() + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/web/SiteWatcher.kt b/src/main/kotlin/web/SiteWatcher.kt new file mode 100644 index 0000000..8ec1a84 --- /dev/null +++ b/src/main/kotlin/web/SiteWatcher.kt @@ -0,0 +1,36 @@ +package web + +import model.BlogPostPreview +import org.jsoup.Jsoup +import java.io.IOException + +object SiteWatcher { + private const val BLOG_INDEX_URL = "https://www.hytale.com/news" + var newestBlog: BlogPostPreview? = null + + fun hasNewBlogPost(): Boolean { + Admin.silent("Updating...") + + try { + val doc = Jsoup.connect(BLOG_INDEX_URL).get() + val newBlog = BlogPostParser.getFistBlog(doc) + + if (newestBlog == newBlog) { + return false + } + + if (newestBlog == null) { + newestBlog = newBlog + return false + } else { + newestBlog = newBlog + } + } catch (e: IOException) { + Admin.error("Connection to Hytale Server failed", e) + + return false + } + + return true + } +} \ No newline at end of file