Compare commits

..

28 commits

Author SHA1 Message Date
39c186cfe4 Refactor and streamline Javalin setup, remove OpenAPI/Swagger.
Also, just general updates
Co-authored-by: Junie, sort of?
2025-04-20 23:42:34 -04:00
d2a9312410 Update Gradle wrapper to 8.13 2025-04-18 18:54:39 -04:00
b6b892da3d Refactor serialization and update null handling in ItemMapper
Replaced Jackson with kotlinx.serialization for better compatibility and added `JsonIgnoreUnknownKeys` to handle unknown fields. Introduced null-safety defaults for `Item` properties and adjusted response handling in `Main.kt` to use safe fallbacks. Updated `slf4j-simple` to version 2.0.16 in dependencies.
2025-04-18 18:50:40 -04:00
18aa2a64ac modernize gradle build 2025-02-17 17:36:14 -05:00
a839399d55 Bump CI 2025-02-17 16:33:32 -05:00
71efb3a00c updates (#23)
Reviewed-on: #23
2025-02-17 16:32:16 -05:00
cfefff1f61 Updates! And commas in /osrsitem prices 2022-07-23 12:20:18 -04:00
0ce4762f75 Add wiki link 2022-07-17 11:29:55 -04:00
6611d600bd /osrsitem command added 2022-01-24 21:59:17 -05:00
b655ccda2f Use Ubuntu 2021-12-16 11:33:41 -05:00
14d68ef36f Enable the daemon 2021-12-16 11:25:22 -05:00
c9814123b7 Updates... Pt 3 😬 2021-12-16 11:18:07 -05:00
942c088360 Updates... Pt 2 2021-12-16 10:52:45 -05:00
88930b7690 Merge pull request 'Updates!' (#22) from update into master
Reviewed-on: #22
2021-12-16 10:49:31 -05:00
e5731bc7b5 Updates! 2021-12-16 10:48:19 -05:00
69e7d9d5e3 Updates 2021-03-21 00:48:32 -04:00
ab13fac05f Reformat and dependency updates 2021-02-07 11:58:00 -05:00
0dfd5c1198 Gradle update 2021-01-31 12:13:22 -05:00
62373f636b Update gradle & deps 2021-01-09 18:16:07 -05:00
8cff76694c Version updates 2020-12-29 14:17:30 -05:00
0e6f063857 ...And Gradle 2020-11-28 10:28:35 -05:00
3e3bd9e7d2 Update versions of things 2020-11-28 10:23:16 -05:00
2f4036c8bb Update deps 2020-10-18 12:22:19 -04:00
4afc3418d7 Dep updates 2020-06-07 15:27:16 -04:00
e819cf0b3a Merge branch 'dep-update' of anthonycicc/slackbot into master 2020-03-14 10:33:21 -04:00
63455d17dd Dependency updates 2020-03-14 10:32:19 -04:00
ebc4cf9425 updated build manifest to be cool as heck 2019-12-21 11:34:30 -05:00
634f9609e5 Merge branch '0.1.4-dep' of anthonycicc/slackbot into master 2019-12-21 10:54:22 -05:00
23 changed files with 509 additions and 385 deletions

View file

@ -1,6 +1,7 @@
image: alpine/edge image: ubuntu/lts
packages: packages:
- openjdk11 - openjdk-21-jdk-headless
- rsync
secrets: secrets:
- 2c7f4f4a-a9c9-47e2-a432-b8a060d01381 - 2c7f4f4a-a9c9-47e2-a432-b8a060d01381
sources: sources:
@ -8,4 +9,14 @@ sources:
tasks: tasks:
- test: | - test: |
cd slackbot cd slackbot
./gradlew test ./gradlew test
- build: |
cd slackbot
./gradlew shadowJar
- deploy: |
cd slackbot
sshopts="ssh -o StrictHostKeyChecking=no"
ssh -o StrictHostKeyChecking=no slackbot@anthonycicchetti.com mv slackbot.jar slackbot.jar.bak-`date -I`
rsync ./build/libs/slackmemes-`cat VERSION`-all.jar slackbot@anthonycicchetti.com:slackbot.jar
- restartservice: |
ssh slackbot@anthonycicchetti.com sudo /bin/systemctl restart slackbot

3
.gitignore vendored
View file

@ -1,3 +1,4 @@
# Project exclude paths # Project exclude paths
/.gradle/ /.gradle/
/build/ /build/
/.idea/

View file

@ -1 +1 @@
0.1.4 0.4.0

View file

@ -1,10 +1,9 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins { plugins {
id("com.github.johnrengelman.shadow") version Versions.com_github_johnrengelman_shadow_gradle_plugin alias(libs.plugins.com.gradleup.shadow)
id("de.fayard.buildSrcVersions") version Versions.de_fayard_buildsrcversions_gradle_plugin alias(libs.plugins.org.jetbrains.kotlin.jvm)
kotlin("jvm") version Versions.org_jetbrains_kotlin_jvm_gradle_plugin alias(libs.plugins.org.jetbrains.kotlin.plugin.serialization)
application application
`jvm-test-suite`
} }
group = "com.anthonycicchetti" group = "com.anthonycicchetti"
@ -15,29 +14,41 @@ repositories {
} }
dependencies { dependencies {
implementation(kotlin("stdlib-jdk8")) constraints {
implementation(Libs.javalin) implementation("org.apache.logging.log4j:log4j-core:_") {
implementation(Libs.slf4j_simple) version {
implementation(Libs.jackson_databind) strictly("[2.17, 3[")
implementation(Libs.jackson_module_kotlin) prefer("2.17.0")
implementation(Libs.swagger_core) }
implementation(Libs.kotlin_openapi3_dsl) because("CVE-2021-44228, CVE-2021-45046, CVE-2021-45105: Log4j vulnerable to remote code execution and other critical security vulnerabilities")
implementation(Libs.swagger_ui) }
}
implementation(libs.javalin)
implementation(libs.slf4j.simple)
implementation(libs.slack.api.model.kotlin.extension)
implementation(libs.jackson.databind)
implementation(libs.jackson.kotlin)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.cio)
implementation(KotlinX.serialization.json)
testImplementation(Libs.junit_jupiter) testImplementation(libs.junit.jupiter)
} }
application { application {
mainClassName = "com.anthonycicchetti.slackbot.MainKt" mainClass.set("com.anthonycicchetti.slackbot.MainKt")
} }
tasks.withType<KotlinCompile> { java {
kotlinOptions.jvmTarget = "1.8" toolchain {
} languageVersion = JavaLanguageVersion.of(21)
}
tasks.withType<Test> { }
useJUnitPlatform()
testLogging { testing {
events("passed", "skipped", "failed") suites {
val test by getting(JvmTestSuite::class) {
useJUnitJupiter()
}
} }
} }

3
buildSrc/.gitignore vendored
View file

@ -1,3 +0,0 @@
.gradle/
build/

View file

@ -1,6 +0,0 @@
plugins {
`kotlin-dsl`
}
repositories {
jcenter()
}

View file

@ -1,77 +0,0 @@
import kotlin.String
/**
* Generated by https://github.com/jmfayard/buildSrcVersions
*
* Update this file with
* `$ ./gradlew buildSrcVersions`
*/
object Libs {
/**
* https://kotlinlang.org/
*/
const val kotlin_scripting_compiler_embeddable: String =
"org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:" +
Versions.org_jetbrains_kotlin
/**
* https://kotlinlang.org/
*/
const val kotlin_stdlib_jdk8: String = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:" +
Versions.org_jetbrains_kotlin
const val com_github_johnrengelman_shadow_gradle_plugin: String =
"com.github.johnrengelman.shadow:com.github.johnrengelman.shadow.gradle.plugin:" +
Versions.com_github_johnrengelman_shadow_gradle_plugin
const val de_fayard_buildsrcversions_gradle_plugin: String =
"de.fayard.buildSrcVersions:de.fayard.buildSrcVersions.gradle.plugin:" +
Versions.de_fayard_buildsrcversions_gradle_plugin
const val org_jetbrains_kotlin_jvm_gradle_plugin: String =
"org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin:" +
Versions.org_jetbrains_kotlin_jvm_gradle_plugin
/**
* https://github.com/FasterXML/jackson-module-kotlin
*/
const val jackson_module_kotlin: String =
"com.fasterxml.jackson.module:jackson-module-kotlin:" + Versions.jackson_module_kotlin
/**
* https://github.com/derveloper/kotlin-openapi3-dsl
*/
const val kotlin_openapi3_dsl: String = "cc.vileda:kotlin-openapi3-dsl:" +
Versions.kotlin_openapi3_dsl
/**
* http://github.com/FasterXML/jackson
*/
const val jackson_databind: String = "com.fasterxml.jackson.core:jackson-databind:" +
Versions.jackson_databind
/**
* https://junit.org/junit5/
*/
const val junit_jupiter: String = "org.junit.jupiter:junit-jupiter:" + Versions.junit_jupiter
/**
* http://www.slf4j.org
*/
const val slf4j_simple: String = "org.slf4j:slf4j-simple:" + Versions.slf4j_simple
/**
* https://github.com/swagger-api/swagger-core
*/
const val swagger_core: String = "io.swagger.core.v3:swagger-core:" + Versions.swagger_core
/**
* http://webjars.org
*/
const val swagger_ui: String = "org.webjars:swagger-ui:" + Versions.swagger_ui
/**
* https://javalin.io
*/
const val javalin: String = "io.javalin:javalin:" + Versions.javalin
}

View file

@ -1,54 +0,0 @@
import kotlin.String
import org.gradle.plugin.use.PluginDependenciesSpec
import org.gradle.plugin.use.PluginDependencySpec
/**
* Generated by https://github.com/jmfayard/buildSrcVersions
*
* Find which updates are available by running
* `$ ./gradlew buildSrcVersions`
* This will only update the comments.
*
* YOU are responsible for updating manually the dependency version.
*/
object Versions {
const val org_jetbrains_kotlin: String = "1.3.61" // available: "1.3.61"
const val com_github_johnrengelman_shadow_gradle_plugin: String = "5.2.0"
// available: "5.2.0"
const val de_fayard_buildsrcversions_gradle_plugin: String = "0.7.0"
const val org_jetbrains_kotlin_jvm_gradle_plugin: String = "1.3.61" // available: "1.3.61"
const val jackson_module_kotlin: String = "2.10.1" // available: "2.10.1"
const val kotlin_openapi3_dsl: String = "0.20.2"
const val jackson_databind: String = "2.10.1" // available: "2.10.1"
const val junit_jupiter: String = "5.5.2"
const val slf4j_simple: String = "1.7.30" // available: "1.7.30"
const val swagger_core: String = "2.1.0" // available: "2.1.0"
const val swagger_ui: String = "3.24.3" // available: "3.24.3"
const val javalin: String = "3.6.0" // available: "3.6.0"
/**
* Current version: "5.6.2"
* See issue 19: How to update Gradle itself?
* https://github.com/jmfayard/buildSrcVersions/issues/19
*/
const val gradleLatestVersion: String = "6.0.1"
}
/**
* See issue #47: how to update buildSrcVersions itself
* https://github.com/jmfayard/buildSrcVersions/issues/47
*/
val PluginDependenciesSpec.buildSrcVersions: PluginDependencySpec
inline get() =
id("de.fayard.buildSrcVersions").version(Versions.de_fayard_buildsrcversions_gradle_plugin)

34
gradle/libs.versions.toml Normal file
View file

@ -0,0 +1,34 @@
## Generated by $ ./gradlew refreshVersionsCatalog
[plugins]
org-jetbrains-kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
org-jetbrains-kotlin-plugin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
com-gradleup-shadow = { id = "com.gradleup.shadow", version = "9.0.0-beta12" }
[versions]
kotlin = "2.1.20"
ktor = "3.1.2"
junit-jupiter = "5.12.2"
jackson = "2.18.3"
[libraries]
javalin = "io.javalin:javalin:6.6.0"
slf4j-simple = "org.slf4j:slf4j-simple:2.0.17"
slack-api-model-kotlin-extension = "com.slack.api:slack-api-model-kotlin-extension:1.45.3"
ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" }
ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
jackson-databind = { group = "com.fasterxml.jackson.core", name = "jackson-databind", version.ref = "jackson"}
jackson-kotlin = { group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version.ref = "jackson"}
junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit-jupiter" }

Binary file not shown.

View file

@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

297
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -15,80 +15,115 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -97,92 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" 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. if ! command -v java >/dev/null 2>&1
then
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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# 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 or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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 esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=$(save "$@") # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong JAVACMD=$( cygpath --unix "$JAVACMD" )
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")" # Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi fi
# 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" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

60
gradlew.bat vendored
View file

@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@ -25,10 +27,14 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @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" "-Xms64m" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@ -37,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@ -51,48 +57,36 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail 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 :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @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% "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

View file

@ -1 +0,0 @@
rootProject.name = 'slackmemes'

19
settings.gradle.kts Normal file
View file

@ -0,0 +1,19 @@
rootProject.name = "slackmemes"
pluginManagement {
repositories {
gradlePluginPortal()
}
plugins {
id("de.fayard.refreshVersions") version "0.60.5"
}
}
plugins {
id("de.fayard.refreshVersions")
}
refreshVersions {
file("build/tmp/refreshVersions").mkdirs()
versionsPropertiesFile = file("build/tmp/refreshVersions/versions.properties")
}

9
slackbot.iml Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View file

@ -1,67 +1,67 @@
package com.anthonycicchetti.slackbot package com.anthonycicchetti.slackbot
import com.anthonycicchetti.slackbot.utility.Commands import com.anthonycicchetti.slackbot.osrs.ApiItem
import com.anthonycicchetti.slackbot.utility.RespObj import com.anthonycicchetti.slackbot.osrs.getOsrsItemPrice
import com.anthonycicchetti.slackbot.utility.TextResponse import com.anthonycicchetti.slackbot.osrs.getOsrsItemByName
import com.anthonycicchetti.slackbot.utility.*
import io.javalin.http.Context import io.javalin.http.Context
import io.javalin.Javalin import io.javalin.Javalin
import io.javalin.plugin.openapi.OpenApiOptions import kotlinx.coroutines.runBlocking
import io.javalin.plugin.openapi.OpenApiPlugin
import io.javalin.plugin.openapi.dsl.document
import io.javalin.plugin.openapi.dsl.documented
import io.javalin.plugin.openapi.ui.SwaggerOptions
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.servers.Server
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.util.*
import kotlin.math.roundToInt import kotlin.math.roundToInt
fun main() { fun main() {
val logger = LoggerFactory.getLogger("main") val logger = LoggerFactory.getLogger("main")
val app = Javalin.create { config -> val app = Javalin.create { config ->
config.registerPlugin(OpenApiPlugin(createOpenApiOptions())) config.bundledPlugins.enableCors { cors -> cors.addRule { it.anyHost() } }
config.enableWebjars() config.requestLogger.http { ctx, ms ->
config.enableCorsForAllOrigins() logger.info("Took ${ms.roundToInt()} to process ${ctx.req().requestURL}")
config.requestLogger {ctx, ms -> }
logger.info("Took ${ms.roundToInt()} to process ${ctx.req.requestURL}")
}
}.start(7000) }.start(7000)
with(app) { with(app) {
options("/*", documented(document().ignore()) {}) options("/*") {}
get("/", documented(document().ignore()) { ctx -> ctx.result("Hello World") }) get("/") { ctx -> ctx.result("Hello World") }
post("/slack/receive", documented(document().operation { post("/slack/receive") { ctx ->
it.description = "NOT DOCUMENTED. Required for slack usage" logger.info("Received request from ${ctx.req().requestURL}")
it.summary = "NOT DOCUMENTED. Required for slack usage"
}.ignore()) { ctx ->
logger.info("Received request from ${ctx.req.requestURL}")
handleSlackEvent(ctx) handleSlackEvent(ctx)
}) }
post("/api/v1/spongebob", documented(document().operation { post("/api/v1/spongebob") { ctx ->
it.description = "Responds with the ${"spongemocked".toSpongemock()} version of the string posted" logger.info("Spongemock: Received request from ${ctx.req().requestURL}")
it.summary = "POST for ${"spongemocking".toSpongemock()}"
}.body<String>().json<TextResponse>("200")) { ctx ->
logger.info("Spongemock: Received request from ${ctx.req.requestURL}")
ctx.json(TextResponse(200, ctx.body().toSpongemock())) ctx.json(TextResponse(200, ctx.body().toSpongemock()))
}) }
post("/api/v1/uppercase", documented(document().operation { post("/api/v1/uppercase") { ctx ->
it.description = "Responds with the UPPERCASED version of the string posted" logger.info("Uppercase: Received request from ${ctx.req().requestURL}")
it.summary = "POST for UPPERCASING" ctx.json(TextResponse(200, ctx.body().uppercase(Locale.getDefault())))
}.body<String>().json<TextResponse>("200")) { ctx -> }
logger.info("Uppercase: Received request from ${ctx.req.requestURL}")
ctx.json(TextResponse(200, ctx.body().toUpperCase()))
})
post("/api/v1/claptext", documented(document().operation { post("/api/v1/claptext") { ctx ->
it.description = "Responds \uD83D\uDC4F with \uD83D\uDC4F the \uD83D\uDC4F claptext \uD83D\uDC4F version" logger.info("Claptext: Received request from ${ctx.req().requestURL}")
it.summary = "POST \uD83D\uDC4F for \uD83D\uDC4F claptext"
}.body<String>().json<TextResponse>("200")) {ctx ->
logger.info("Claptext: Received request from ${ctx.req.requestURL}")
ctx.json(TextResponse(200, ctx.body().toClapText())) ctx.json(TextResponse(200, ctx.body().toClapText()))
}) }
post("/api/v1/osrsitem") { ctx ->
runBlocking {
logger.info("OSRS Item: Received request for ${ctx.body()}")
val item: ApiItem? = getOsrsItemByName(ctx.body())
if (item == null) {
ctx.json(notFoundItem)
} else {
val itemPrices = getOsrsItemPrice(item)
ctx.json(
(BlockResponse(
200, item.name,
itemPrices.high ?: Int.MAX_VALUE,
itemPrices.low ?: Int.MIN_VALUE
))
)
}
}
}
} }
@ -98,6 +98,7 @@ private fun String?.processToCommand(): Commands {
"/spongemock2" -> Commands.Spongebob "/spongemock2" -> Commands.Spongebob
"/uppercase" -> Commands.Uppercase "/uppercase" -> Commands.Uppercase
"/clapback" -> Commands.Claptext "/clapback" -> Commands.Claptext
"/osrsitem" -> Commands.OsrsItem
else -> Commands.Error else -> Commands.Error
} }
} }
@ -109,12 +110,31 @@ private fun sendResponse(ctx: Context, respObj: RespObj) {
Commands.Spongebob -> { Commands.Spongebob -> {
put("text", respObj.text.toSpongemock()); put("response_type", "in_channel") put("text", respObj.text.toSpongemock()); put("response_type", "in_channel")
} }
Commands.Uppercase -> { Commands.Uppercase -> {
put("text", respObj.text.toUpperCase()); put("response_type", "in_channel") put("text", respObj.text.uppercase(Locale.getDefault())); put("response_type", "in_channel")
} }
Commands.Claptext -> { Commands.Claptext -> {
put("text", respObj.text.toClapText()); put("response_type", "in_channel") put("text", respObj.text.toClapText()); put("response_type", "in_channel")
} }
Commands.OsrsItem -> runBlocking {
val item = getOsrsItemByName(respObj.text)
val itemPricesBlock: BlockResponse = if (item == null) {
notFoundItem
} else {
val itemPrices = getOsrsItemPrice(item)
BlockResponse(200, item.name,
itemPrices.high ?: Int.MAX_VALUE,
itemPrices.low ?: Int.MIN_VALUE
)
}
val logger = LoggerFactory.getLogger("sendResponse")
logger.info(itemPricesBlock.response)
put("blocks", itemPricesBlock.response); put("response_type", "in_channel")
}
Commands.Error -> { Commands.Error -> {
put("text", respObj.text); put("response_type", "ephemeral") put("text", respObj.text); put("response_type", "ephemeral")
} }
@ -122,16 +142,4 @@ private fun sendResponse(ctx: Context, respObj: RespObj) {
} }
ctx.json(returnMap) ctx.json(returnMap)
}
private fun createOpenApiOptions(): OpenApiOptions {
val o = {
OpenAPI()
.info(Info().version("0.1.2").description("Slackbot Open API documentation"))
.addServersItem(Server().url("https://acicchetti.dev/"))
}
return OpenApiOptions(o)
.path("/swagger-docs")
.swagger(SwaggerOptions("/swagger").title("Slackbot Swagger Docs"))
} }

View file

@ -2,21 +2,22 @@ package com.anthonycicchetti.slackbot
fun String.toSpongemock(): String { fun String.toSpongemock(): String {
return this return this
.split(' ') .split(' ').joinToString(" ") { word ->
.map { word ->
word.mapIndexed { index, char -> word.mapIndexed { index, char ->
if (!index.isOdd()) { if (!index.isOdd()) {
char.toUpperCase() char.uppercaseChar()
} else { } else {
char.toLowerCase() char.lowercaseChar()
} }
}.joinToString("") }.joinToString("")
}.joinToString(" ") }
} }
fun String.toClapText(): String { fun String.toClapText(): String {
with(this with(
.split(' ')) { this
.split(' ')
) {
if (this.size == 1) { if (this.size == 1) {
return "\uD83D\uDC4F ${this[0]} \uD83D\uDC4F" return "\uD83D\uDC4F ${this[0]} \uD83D\uDC4F"
} }

View file

@ -0,0 +1,83 @@
package com.anthonycicchetti.slackbot.osrs
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonIgnoreUnknownKeys
import org.slf4j.Logger
import org.slf4j.LoggerFactory
val logger: Logger by lazy { LoggerFactory.getLogger("ItemMapper") }
val client = HttpClient(CIO) {
install(UserAgent) {
agent = "private_slackbot - @AnthonyCicc"
}
}
suspend fun getItemList(): List<ApiItem> {
val response = client.get("https://prices.runescape.wiki/api/v1/osrs/mapping")
return when (response.status.value) {
in 200..299 -> {
logger.info("Got item mappings")
Json.decodeFromString(response.body())
}
else -> {
logger.info("Could not get item mappings")
emptyList()
}
}
}
suspend fun getOsrsItemByName(itemName: String): ApiItem? =
getItemList().firstOrNull { item: ApiItem -> item.name.lowercase() == itemName.lowercase() }
suspend fun getOsrsItemPrice(item: ApiItem): Item {
val response = client
.get("https://prices.runescape.wiki/api/v1/osrs/latest")
return when (response.status.value) {
in 200..299 -> {
val r: Resp = Json.decodeFromString(response.body())
r.data.getOrDefault(item.id.toString(), Item())
}
else -> {
logger.warn("Couldn't find Item with ID ${item.id}")
Item()
}
}
}
@Serializable
private data class Resp(
val data: Map<String, Item> = emptyMap(),
)
@Serializable
data class Item(
val low: Int? = 0,
val lowTime: Long? = 0L,
val high: Int? = 0,
val highTime: Long? = 0L,
)
@OptIn(ExperimentalSerializationApi::class)
@Serializable
@JsonIgnoreUnknownKeys
data class ApiItem(
val examine: String = "Empty Examine Text",
val id: Int = 0,
val members: Boolean = false,
val lowalch: Int = 0,
val limit: Int = 0,
val highalch: Int = 0,
val name: String = "Empty Name",
val value: Int = 0,
)

View file

@ -0,0 +1,27 @@
package com.anthonycicchetti.slackbot.utility
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.ObjectMapper
import com.slack.api.model.kotlin_extension.block.withBlocks
import java.text.NumberFormat
data class BlockResponse(val status: Int = 200, val itemName: String, val highVal: Int, val lowVal: Int) {
val response: String
init {
val mapper = ObjectMapper()
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
val resp = run {
withBlocks {
section { markdownText("Item Found: ${itemName}") }
divider()
section { markdownText(":chart_with_upwards_trend:: ${NumberFormat.getNumberInstance().format(highVal)}") }
section { markdownText(":chart_with_downwards_trend:: ${NumberFormat.getNumberInstance().format(lowVal)}") }
divider()
section { markdownText("<https://oldschool.runescape.wiki/?search=${itemName.replace(' ', '+')}&title=Special%3ASearch&go=Go|Wiki Search>")}
}
}
response = mapper.writeValueAsString(resp)
}
}
val notFoundItem = BlockResponse(200, "Item Not Found", 0, 0 )

View file

@ -12,5 +12,6 @@ sealed class Commands {
object Spongebob : Commands() object Spongebob : Commands()
object Uppercase : Commands() object Uppercase : Commands()
object Claptext : Commands() object Claptext : Commands()
object OsrsItem : Commands()
object Error : Commands() object Error : Commands()
} }

View file

@ -66,7 +66,8 @@ internal class TransformationsTest {
@Test @Test
fun `Claptext works with multiple words`() { fun `Claptext works with multiple words`() {
val actual = "Find a dentist in Boston your a grown man" val actual = "Find a dentist in Boston your a grown man"
val expected = "Find \uD83D\uDC4F a \uD83D\uDC4F dentist \uD83D\uDC4F in \uD83D\uDC4F Boston \uD83D\uDC4F your \uD83D\uDC4F a \uD83D\uDC4F grown \uD83D\uDC4F man" val expected =
"Find \uD83D\uDC4F a \uD83D\uDC4F dentist \uD83D\uDC4F in \uD83D\uDC4F Boston \uD83D\uDC4F your \uD83D\uDC4F a \uD83D\uDC4F grown \uD83D\uDC4F man"
assertEquals(expected, actual.toClapText()) assertEquals(expected, actual.toClapText())
} }