This commit is contained in:
moonleay 2023-11-25 21:59:17 +01:00
commit d57a05cc84
Signed by: moonleay
GPG key ID: 82667543CCD715FB
34 changed files with 2631 additions and 0 deletions

7
.dockerignore Normal file
View file

@ -0,0 +1,7 @@
data/
/data/
data
.idea/
/.idea/
.idea

46
.gitignore vendored Normal file
View file

@ -0,0 +1,46 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
.idea
data/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

15
Dockerfile Normal file
View file

@ -0,0 +1,15 @@
FROM openjdk:17-jdk-slim AS build
WORKDIR /app
ADD . /app
RUN rm -rf /app/run
RUN ./gradlew shadowJar
FROM openjdk:17-jdk-slim AS run
COPY --from=build /app/build/libs/*-all.jar app.jar
CMD ["java", "-jar", "app.jar"]

248
build.gradle.kts Normal file
View file

@ -0,0 +1,248 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import org.jetbrains.gradle.ext.ProjectSettings
import org.jetbrains.gradle.ext.TaskTriggersConfig
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.9.10"
id("com.github.johnrengelman.shadow") version "8.1.1"
id("org.jetbrains.gradle.plugin.idea-ext") version "1.1.7"
`maven-publish`
}
//lilJudd version 2
val ownerID = 372703841151614976L
group = "net.moonleay.bedge"
version = System.getenv("CI_COMMIT_TAG")?.let { "$it-${System.getenv("CI_COMMIT_SHORT_SHA")}-prod" }
?: System.getenv("CI_COMMIT_SHORT_SHA")?.let { "$it-dev" }
?: "0.0.4"
val kordver = "1.5.9-SNAPSHOT"
val coroutinesver = "1.7.3"
val ktorver = "2.3.5"
val exposedver = "0.43.0"
val postgresver = "42.6.0"
val krontabver = "2.2.1"
val mavenArtifact = "Bedge"
project.base.archivesName.set(mavenArtifact)
repositories {
mavenCentral()
maven {
name = "Gitlab"
val projectId = System.getenv("CI_PROJECT_ID")
val apiV4 = System.getenv("CI_API_V4_URL")
url = uri("https://$apiV4/projects/$projectId/packages/maven")
authentication {
create("header", HttpHeaderAuthentication::class.java) {
if (System.getenv("CI_JOB_TOKEN") != null) {
credentials(HttpHeaderCredentials::class) {
name = "Job-Token"
value = System.getenv("CI_JOB_TOKEN")
}
} else if (project.hasProperty("myGitlabToken")) {
credentials(HttpHeaderCredentials::class) {
name = "Private-Token"
value = project.ext["myGitlabToken"] as String
}
} else {
credentials(HttpHeaderCredentials::class) {
name = "none"
value = ""
}
}
}
}
}
maven {
name = "sonatype"
url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots")
}
maven {
name = "sonatype 2"
url = uri("https://oss.sonatype.org/content/repositories/snapshots")
}
}
val shadow by configurations.getting
val implementation by configurations.getting
implementation.extendsFrom(shadow)
dependencies {
//Discord
shadow("com.kotlindiscord.kord.extensions:kord-extensions:$kordver")
//Coroutines
shadow("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesver")
//Logging
shadow("org.slf4j:slf4j-api:2.0.3")
shadow("org.slf4j:slf4j-simple:2.0.3")
//Database
shadow("org.jetbrains.exposed:exposed-core:$exposedver")
shadow("org.jetbrains.exposed:exposed-dao:$exposedver")
shadow("org.jetbrains.exposed:exposed-jdbc:$exposedver")
shadow("org.postgresql:postgresql:$postgresver")
//Krontab
shadow("dev.inmo:krontab:$krontabver")
shadow("io.ktor:ktor-client-core-jvm:2.3.5")
shadow("io.ktor:ktor-client-cio-jvm:2.3.5")
}
val targetJavaVersion = 17
val templateSrc = project.rootDir.resolve("src/main/templates")
val templateDest = project.projectDir.resolve("build/generated/templates")
val templateProps = mapOf(
"version" to project.version as String,
"ownerID" to ownerID,
"kordversion" to kordver,
"coroutinesversion" to coroutinesver,
"ktorversion" to ktorver,
"exposedversion" to exposedver,
"postgresversion" to postgresver,
"krontabversion" to krontabver
)
tasks {
create<Copy>("generateTemplates") {
filteringCharset = "UTF-8"
inputs.properties(templateProps)
from(templateSrc)
expand(templateProps)
into(templateDest)
}
withType<Jar> {
manifest {
attributes["Main-Class"] = "net.moonleay.bedge.MainKt"
}
// To add all of the dependencies
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
})
duplicatesStrategy = DuplicatesStrategy.INCLUDE
dependsOn("generateTemplates", "processResources")
}
withType<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar> {
configurations = listOf(shadow)
dependsOn("generateTemplates", "processResources")
}
withType<JavaCompile> {
// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
// If Javadoc is generated, this must be specified in that task too.
options.encoding = "UTF-8"
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible) {
options.release.set(targetJavaVersion)
}
dependsOn("generateTemplates", "processResources")
}
withType<KotlinCompile> {
kotlinOptions.jvmTarget = targetJavaVersion.toString()
dependsOn("generateTemplates", "processResources")
}
withType<Jar> {
from("LICENSE") {
rename { "${it}_${project.base.archivesName.get()}" }
}
archiveBaseName.set(mavenArtifact)
dependsOn("generateTemplates", "processResources")
}
}
java {
val javaVersion = JavaVersion.toVersion(targetJavaVersion)
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion.set(JavaLanguageVersion.of(targetJavaVersion))
}
withSourcesJar()
}
sourceSets {
main {
java {
srcDir(templateDest)
}
}
}
publishing {
publications {
create<MavenPublication>("mavenJava") {
version = project.version as String
artifactId = mavenArtifact
from(components["java"])
}
}
repositories {
if (System.getenv("CI_JOB_TOKEN") != null) {
maven {
name = "GitLab"
val projectId = System.getenv("CI_PROJECT_ID")
val apiV4 = System.getenv("CI_API_V4_URL")
url = uri("$apiV4/projects/$projectId/packages/maven")
authentication {
create("token", HttpHeaderAuthentication::class.java) {
credentials(HttpHeaderCredentials::class.java) {
name = "Job-Token"
value = System.getenv("CI_JOB_TOKEN")
}
}
}
}
}
}
}
rootProject.idea.project {
this as ExtensionAware
configure<ProjectSettings> {
this as ExtensionAware
configure<TaskTriggersConfig> {
afterSync(tasks["generateTemplates"], tasks["processResources"])
}
}
}
//rootProject.eclipse.synchronizationTasks("generateTemplates", "processResources")
//Fuck eclipse users amirite?

19
gradle.properties Normal file
View file

@ -0,0 +1,19 @@
#
# Bedge
# Copyright (C) 2023 moonleay
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,23 @@
#
# Bedge
# Copyright (C) 2023 moonleay
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

236
gradlew vendored Executable file
View file

@ -0,0 +1,236 @@
#!/bin/sh
#
# Bedge
# Copyright (C) 2023 moonleay
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
##############################################################################
#
# 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/master/subprojects/plugins/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
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
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.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# 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 ;; #(
MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# 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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

89
gradlew.bat vendored Normal file
View file

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@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 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.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@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 execute
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 execute
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
: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 %*
: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

30
settings.gradle.kts Normal file
View file

@ -0,0 +1,30 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "Bedge"

View file

@ -0,0 +1,110 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge
import com.kotlindiscord.kord.extensions.ExtensibleBot
import dev.kord.common.entity.PresenceStatus
import dev.kord.core.event.gateway.ReadyEvent
import dev.kord.core.on
import dev.kord.gateway.Intent
import dev.kord.gateway.PrivilegedIntent
import kotlinx.coroutines.Job
import net.moonleay.bedge.data.CredentialManager
import net.moonleay.bedge.data.database.DB
import net.moonleay.bedge.features.WakeupFeature
import net.moonleay.bedge.util.Logger
import net.moonleay.bedge.extensions.*
import kotlin.system.exitProcess
object Bot {
//The kord object gets set at app launch
lateinit var bot: ExtensibleBot
private val jobs = mutableListOf<Job>()
@OptIn(PrivilegedIntent::class)
suspend fun start() {
Logger.out("Starting Bot...")
// Load config
CredentialManager.load()
// Don't run the bot when there is no bot token in config
if (CredentialManager.token == "empty") {
Logger.out("The config does not contain a bot token.")
exitProcess(3)
}
// Check if the credentials for the Database are existent, don't run if they are missing
if (CredentialManager.dbDomain == "empty" || CredentialManager.dbName == "empty" || CredentialManager.dbUser == "empty" || CredentialManager.dbPassword == "empty") {
Logger.out("The config does not contain the whole Database credentials.")
exitProcess(3)
}
// Connect to the database
DB.connect(
CredentialManager.dbDomain,
CredentialManager.dbName,
CredentialManager.dbUser,
CredentialManager.dbPassword
)
// Make sure the database is up-to-date
DB.register()
// Create the bot object
bot = ExtensibleBot(CredentialManager.token) {
applicationCommands {
enabled = true
}
extensions {
add(::TimeExtension)
add(::AwakeExtension)
add(::ProfileExtension)
add(::TopExtension)
}
this.presence {
this.status = PresenceStatus.Online
this.listening("soothing rain sounds")
}
this.intents {
+Intent.GuildMembers
}
// Will add Sharding someday, I promise
/*
sharding { recommended ->
Shards(recommended)
} */
}
bot.kordRef.on<ReadyEvent> {
// run when init'd
WakeupFeature.createWakeupCronjobs()
Logger.out("Bot is ready!")
}
//Start the bot
bot.start()
}
}

View file

@ -0,0 +1,26 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge
import net.moonleay.bedge.build.BuildConstants
suspend fun main() {
println("v.${BuildConstants.version}")
Bot.start()
}

View file

@ -0,0 +1,98 @@
/*
* lilJudd
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.data
import java.io.*
import java.util.*
object CredentialManager {
private const val foldername = "data"
private const val filename = "credentials.nils"
lateinit var token: String
lateinit var dbDomain: String
lateinit var dbName: String
lateinit var dbUser: String
lateinit var dbPassword: String
///Load the needed credentials, generate a config if there is none
fun load() {
val folder = File(foldername)
if (!folder.exists()) {
save()
return
}
val configFile = File(folder, filename)
if (!configFile.exists()) {
save()
return
}
try {
val input: InputStream = FileInputStream(foldername + File.separator + filename)
val prop = Properties()
prop.load(input)
token = prop.getProperty("token")
dbDomain = prop.getProperty("dbDomain")
dbName = prop.getProperty("dbName")
dbUser = prop.getProperty("dbUser")
dbPassword = prop.getProperty("dbPassword")
input.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
///generate a new sample config
private fun save() {
val folder = File(foldername)
if (!folder.exists()) {
try {
folder.mkdirs()
} catch (e: IOException) {
e.printStackTrace()
}
}
val configFile = File(foldername + File.separator + filename)
if (!configFile.exists()) {
try {
configFile.createNewFile()
} catch (e: IOException) {
e.printStackTrace()
}
}
try {
val output: OutputStream = FileOutputStream(foldername + File.separator + filename)
val prop = Properties()
prop.setProperty("token", "empty")
prop.setProperty("dbDomain", "empty")
prop.setProperty("dbName", "empty")
prop.setProperty("dbUser", "empty")
prop.setProperty("dbPassword", "empty")
prop.store(output, null)
output.close()
token = "empty"
dbDomain = "empty"
dbName = "empty"
dbUser = "empty"
dbPassword = "empty"
} catch (e: IOException) {
e.printStackTrace()
}
}
}

View file

@ -0,0 +1,49 @@
/*
* lilJudd
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.data.database
import net.moonleay.bedge.data.database.tables.UserTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
object DB {
private var connected = false
//Connect to the provided DB; trows errors, if the DB is not available.
fun connect(dbDomain: String, dbName: String, dbUser: String, dbPasswd: String) {
Database.connect(
"jdbc:postgresql://$dbDomain/$dbName",
driver = "org.postgresql.Driver",
user = dbUser,
password = dbPasswd
)
connected = true
}
fun register() {
if (!connected)
return
// Register tables here
transaction {
SchemaUtils.create(UserTable)
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.data.database.entry
data class UserData(
val id: Int,
val userid: Long,
val accountCreationDate: Long,
var currentStreak: Int,
var longestStreak: Int,
var wantsToBeReminded: Boolean,
var coins: Int,
var coinsCollected: Int,
var xp: Int,
var level: Int,
var numberOfFails: Int,
var targetChannelId: Long,
var customReminderMessage: String,
var preferredSleepTime: Int,
var customWakeupMessage: String,
var nextWakeup: Long,
var nextWakeupCron: String,
var lastWakeup: Long,
var isAwake: Boolean,
var timezone: String
)

View file

@ -0,0 +1,146 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.data.database.repository
import net.moonleay.bedge.data.database.entry.UserData
import net.moonleay.bedge.data.database.tables.UserTable
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
object UserRepository {
fun getAllUsers(): List<UserData> {
val list: MutableList<UserData> = mutableListOf()
transaction {
UserTable.selectAll().forEach { user ->
list.add(UserData(
user[UserTable.id],
user[UserTable.userid],
user[UserTable.accountCreationDate],
user[UserTable.currentStreak],
user[UserTable.longestStreak],
user[UserTable.wantsToBeReminded],
user[UserTable.coins],
user[UserTable.coinsCollected],
user[UserTable.xp],
user[UserTable.level],
user[UserTable.numberOfFails],
user[UserTable.targetChannelId],
user[UserTable.customReminderMessage],
user[UserTable.preferredSleepTime],
user[UserTable.customWakeupMessage],
user[UserTable.nextWakeup],
user[UserTable.nextWakeupCron],
user[UserTable.lastWakeup],
user[UserTable.isAwake],
user[UserTable.timezone]
))
}
}
return list
}
fun getUserByID(id: ULong): UserData = getUserByID(id.toLong())
fun getUserByID(id: Long): UserData {
lateinit var user: UserData
transaction {
UserTable.select(UserTable.userid eq id).forEach {
user = UserData(
it[UserTable.id],
it[UserTable.userid],
it[UserTable.accountCreationDate],
it[UserTable.currentStreak],
it[UserTable.longestStreak],
it[UserTable.wantsToBeReminded],
it[UserTable.coins],
it[UserTable.coinsCollected],
it[UserTable.xp],
it[UserTable.level],
it[UserTable.numberOfFails],
it[UserTable.targetChannelId],
it[UserTable.customReminderMessage],
it[UserTable.preferredSleepTime],
it[UserTable.customWakeupMessage],
it[UserTable.nextWakeup],
it[UserTable.nextWakeupCron],
it[UserTable.lastWakeup],
it[UserTable.isAwake],
it[UserTable.timezone]
)
}
}
return user
}
fun doesUserExist(id: ULong) = transaction {
UserTable.select { UserTable.userid eq id.toLong() }.count() > 0
}
fun write(data: UserData) = transaction {
UserTable.insert {
it[UserTable.userid] = data.userid
it[UserTable.accountCreationDate] = data.accountCreationDate
it[UserTable.currentStreak] = data.currentStreak
it[UserTable.longestStreak] = data.longestStreak
it[UserTable.wantsToBeReminded] = data.wantsToBeReminded
it[UserTable.coins] = data.coins
it[UserTable.coinsCollected] = data.coinsCollected
it[UserTable.xp] = data.xp
it[UserTable.level] = data.level
it[UserTable.numberOfFails] = data.numberOfFails
it[UserTable.targetChannelId] = data.targetChannelId
it[UserTable.customReminderMessage] = data.customReminderMessage
it[UserTable.preferredSleepTime] = data.preferredSleepTime
it[UserTable.customWakeupMessage] = data.customWakeupMessage
it[UserTable.nextWakeup] = data.nextWakeup
it[UserTable.nextWakeupCron] = data.nextWakeupCron
it[UserTable.lastWakeup] = data.lastWakeup
it[UserTable.isAwake] = data.isAwake
it[UserTable.timezone] = data.timezone
} get UserTable.id
}
fun update(data: UserData) = transaction {
UserTable.update({ UserTable.userid eq data.userid}) {
it[UserTable.currentStreak] = data.currentStreak
it[UserTable.longestStreak] = data.longestStreak
it[UserTable.wantsToBeReminded] = data.wantsToBeReminded
it[UserTable.coins] = data.coins
it[UserTable.coinsCollected] = data.coinsCollected
it[UserTable.xp] = data.xp
it[UserTable.level] = data.level
it[UserTable.numberOfFails] = data.numberOfFails
it[UserTable.targetChannelId] = data.targetChannelId
it[UserTable.customReminderMessage] = data.customReminderMessage
it[UserTable.preferredSleepTime] = data.preferredSleepTime
it[UserTable.customWakeupMessage] = data.customWakeupMessage
it[UserTable.nextWakeup] = data.nextWakeup
it[UserTable.nextWakeupCron] = data.nextWakeupCron
it[UserTable.lastWakeup] = data.lastWakeup
it[UserTable.isAwake] = data.isAwake
it[UserTable.timezone] = data.timezone
}
}
}

View file

@ -0,0 +1,44 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.data.database.tables
import org.jetbrains.exposed.sql.Table
object UserTable : Table(name = "users") {
var id = integer("id").autoIncrement()
var userid = long("userid")
var accountCreationDate = long("account_creation_date")
var currentStreak = integer("current_streak")
var longestStreak = integer("longest_streak")
var wantsToBeReminded = bool("wants_to_be_reminded")
var coins = integer("coins")
var coinsCollected = integer("coins_collected")
var xp = integer("xp")
var level = integer("level")
var numberOfFails = integer("number_of_fails")
var targetChannelId = long("target_channel_id")
var customReminderMessage = text("custom_reminder_message")
var preferredSleepTime = integer("preferred_sleep_time")
var customWakeupMessage = text("custom_wakeup_message")
var nextWakeup = long("next_wakeup")
var nextWakeupCron = varchar("next_wakeup_cron", 50)
var lastWakeup = long("last_wakeup")
var isAwake = bool("is_awake")
var timezone = varchar("timezone", 50)
}

View file

@ -0,0 +1,116 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.extensions
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand
import com.kotlindiscord.kord.extensions.types.respond
import dev.kord.common.entity.MessageFlags
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.util.EmbedColor
import net.moonleay.bedge.util.Logger
import net.moonleay.bedge.util.MessageUtil
class AwakeExtension : Extension() {
override val name = "awake"
override suspend fun setup() {
publicSlashCommand {
name = "awake"
description = "Set yourself as awake"
this.action {
val u = this.user.asUser()
Logger.out("User ${u.username} wants to be awake")
if (UserRepository.doesUserExist(u.id.value)){
val ud = UserRepository.getUserByID(u.id.value)
if (ud.isAwake) {
// User is already awake
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.ERROR,
"You are already awake!",
"You can set a wakeup time for tomorrow with `/time`",
u.username,
)
)
}
return@action
}
// set awake
ud.isAwake = true
ud.lastWakeup = System.currentTimeMillis()
// update the streak
ud.currentStreak++
if (ud.currentStreak > ud.longestStreak) {
ud.longestStreak = ud.currentStreak
}
// hand out coins for streak & success
var streakCoins = ud.currentStreak / 7
if (streakCoins > 5)
streakCoins = 5
ud.coins += (1 + streakCoins)
ud.coinsCollected += (1 + streakCoins)
// grant xp and check for lvlup
val neededXpForNextLvl = (10 + ((100*0.1) * (ud.level - 1))).toInt()
val bonusXp = (1.5 * ud.currentStreak).toInt()
ud.xp += 10 + bonusXp
if (ud.xp >= neededXpForNextLvl) {
ud.xp -= neededXpForNextLvl
++ud.level
}
// update user
UserRepository.update(ud)
// respond to user
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.SUCCESS,
"Good morning, ${u.username}!",
ud.customWakeupMessage.replace("#user", u.mention) + "\n" +
"\n" +
"${if (streakCoins > 0) "[${ud.currentStreak} day streak]" else ""}\n" +
"${ud.coins} coin${if (ud.coins >= 1) "s" else ""} (+${streakCoins+1})\n" +
"lvl ${ud.level} (${ud.xp}/${neededXpForNextLvl} xp) [+${10 + bonusXp} xp]\n",
u.username,
)
)
}
} else {
// User is running for the first time
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.ERROR,
"You are not registered!",
"Please register with `/time`",
u.username,
)
)
}
}
}
}
}
}

View file

@ -0,0 +1,115 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.extensions
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.commands.converters.impl.optionalUser
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand
import com.kotlindiscord.kord.extensions.types.respond
import dev.kord.core.entity.User
import dev.kord.rest.builder.message.EmbedBuilder
import net.moonleay.bedge.data.database.entry.UserData
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.util.EmbedColor
import net.moonleay.bedge.util.MessageUtil
class ProfileExtension : Extension() {
override val name = "profile"
override val allowApplicationCommandInDMs: Boolean
get() = false
override suspend fun setup() {
publicSlashCommand(::ProfileArguments) {
name = "profile"
description = "Checkout (your / a) profile"
this.action {
val user = this.user.asUser()
if (this.arguments.target == null || this.arguments.target!!.id == this.user.id) {
// User wants to see own profile
val target = this.arguments.target!!
if(!UserRepository.doesUserExist(target.id.value)){
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.ERROR,
"User not found!",
"You did not use the bot yet, so there is no information about you.",
target.username,
)
)
}
return@action
}
val td = UserRepository.getUserByID(target.id.value)
this.respond {
this.embeds.add(
getProfileMsg(td, target, target)
)
}
return@action
}
// User wants to see other profile
val target = this.arguments.target!!
if(!UserRepository.doesUserExist(target.id.value)){
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.ERROR,
"User not found!",
"The user did not use the bot yet, so there is no information about them.",
target.username,
)
)
}
return@action
}
val td = UserRepository.getUserByID(target.id.value)
this.respond {
this.embeds.add(
getProfileMsg(td, target, user)
)
}
}
}
}
private fun getProfileMsg(target: UserData, targetUser: User, requester: User): EmbedBuilder = MessageUtil.getEmbedWithImage(
EmbedColor.INFO,
"Profile of ${target.userid}",
"Account created: ${target.accountCreationDate}\n" +
"Current streak: ${target.currentStreak} days\n" +
"Longest streak: ${target.longestStreak} days\n" +
"Number of fails: ${target.numberOfFails}x\n" +
"Coins: ${target.coins}\n" +
"Preferred sleep time: ${target.preferredSleepTime} hrs\n" +
"Timezone: ${target.timezone}\n",
requester.username,
targetUser.avatar?.cdnUrl!!.toUrl())
inner class ProfileArguments : Arguments() {
val target by optionalUser {
this.name = "target"
this.description = "The target user"
}
}
}

View file

@ -0,0 +1,112 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.extensions
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.commands.converters.impl.string
import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand
import com.kotlindiscord.kord.extensions.types.respond
import net.moonleay.bedge.data.database.entry.UserData
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.jobs.WakeupJob
import net.moonleay.bedge.jobs.component.JobManager
import net.moonleay.bedge.util.*
class TimeExtension : Extension() {
override val name = "time"
override val allowApplicationCommandInDMs: Boolean
get() = false
override suspend fun setup() {
publicSlashCommand(::TimeArguments) {
name = "time"
description = "Set the wakeup time for tomorrow"
this.action {
val u = this.user.asUser()
val targetTime = this.arguments.time
Logger.out("User ${u.username} wants to be awake at $targetTime")
val timeToWake = TimeUtil.getZdtFromTime(targetTime, "UTC")
val cronJobString = TimeUtil.getCronjobStringFromDate(timeToWake)
val targetChannelId = this.channel.asChannel().id.value.toLong()
lateinit var ud: UserData
if (UserRepository.doesUserExist(u.id.value)) {
// Update existing user
ud = UserRepository.getUserByID(u.id.value)
ud.nextWakeup = timeToWake.toEpochSecond() * 1000 // ms
ud.nextWakeupCron = cronJobString
ud.isAwake = false
UserRepository.update(ud)
} else {
// create new user
ud = UserData (
-1,
u.id.value.toLong(),
System.currentTimeMillis(), // account creation date
0,
0,
false,
0,
0,
0,
1,
0,
targetChannelId,
"Don't forget to go to bed, #user!",
8, // hrs
"#user is now awake!",
timeToWake.toEpochSecond() * 1000, // ms
cronJobString,
0,
false,
"UTC"
)
UserRepository.write(ud)
}
JobManager.killNamedJob("WakeupJob${u.id.value.toLong()}") // Make sure that there is no job, which is already running
JobManager.addJob(WakeupJob("WakeupJob${u.id.value.toLong()}", cronJobString, u.id.value.toLong()))
Logger.out("User ${u.username} is now set to be awake at $targetTime")
this.respond {
this.embeds.add(MessageUtil.getEmbed(
EmbedColor.SUCCESS,
"Wakeup time set",
"${u.mention} is now set to be awake at $targetTime.\n" +
"Have a restfull sleep!\n" +
"***You can change your wakeup time by running /time again!***",
u.username
))
}
}
}
}
inner class TimeArguments : Arguments() {
val time by string {
this.name = "time"
this.description = "The time you want to be awake at. Format: \"HH:mm\""
}
}
}

View file

@ -0,0 +1,110 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.extensions
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.commands.application.slash.converters.impl.enumChoice
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand
import com.kotlindiscord.kord.extensions.types.respond
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.Guild
import kotlinx.coroutines.flow.map
import net.moonleay.bedge.data.database.entry.UserData
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.extensions.component.ListTypes
import net.moonleay.bedge.util.EmbedColor
import net.moonleay.bedge.util.MessageUtil
class TopExtension : Extension() {
override val name = "top"
override val allowApplicationCommandInDMs: Boolean
get() = false
override suspend fun setup() {
publicSlashCommand(::TopArguments) {
name = "top"
description = "See the top lists"
this.action {
val u = this.user.asUser()
val g = this.guild!!.asGuild()
val targetList = this.arguments.listType
val all = UserRepository.getAllUsers()
val allInGuild = all.filter { g.getMemberOrNull(Snowflake(it.userid)) != null }
when(targetList) {
ListTypes.TOPSTREAK -> {
allInGuild.sortedByDescending { it.longestStreak }
}
ListTypes.STREAK -> {
allInGuild.sortedByDescending { it.currentStreak }
}
ListTypes.TOPCOINS -> {
allInGuild.sortedByDescending { it.coinsCollected }
}
ListTypes.COINS -> {
allInGuild.sortedByDescending { it.coins }
}
ListTypes.FAILS -> {
allInGuild.sortedByDescending { it.numberOfFails }
}
}
var msg = ""
for (i in 0..9) {
val user = allInGuild[i]
val row = getRow(user, g, targetList)
msg += "${i+1}. ${row[0]}: ${row[1]}\n"
}
this.respond {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.INFO,
"Top ${targetList.name}",
msg,
u.username,
)
)
}
}
}
}
private suspend fun getRow(user: UserData, g: Guild, type: ListTypes): Array<String> {
val typeResult: String = when(type) {
ListTypes.TOPSTREAK -> user.longestStreak.toString()
ListTypes.STREAK -> user.currentStreak.toString()
ListTypes.TOPCOINS -> user.coinsCollected.toString()
ListTypes.COINS -> user.coins.toString()
ListTypes.FAILS -> user.numberOfFails.toString()
}
return arrayOf(g.getMember(Snowflake(user.userid)).mention, typeResult)
}
inner class TopArguments : Arguments() {
val listType by enumChoice<ListTypes> {
this.name = "list"
this.typeName = "list"
this.description = "The list you want to view"
}
}
}

View file

@ -0,0 +1,29 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.extensions.component
import com.kotlindiscord.kord.extensions.commands.application.slash.converters.ChoiceEnum
enum class ListTypes(override val readableName: String) : ChoiceEnum{
TOPSTREAK("best streak all-time"),
STREAK("best streak"),
TOPCOINS("most earned coins"),
COINS("most coins"),
FAILS("most fails"),
}

View file

@ -0,0 +1,45 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.features
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.jobs.WakeupJob
import net.moonleay.bedge.jobs.component.JobManager
import net.moonleay.bedge.util.Logger
object WakeupFeature {
fun createWakeupCronjobs() {
val users = UserRepository.getAllUsers()
users.forEach { user ->
if (user.nextWakeup > System.currentTimeMillis() && !user.isAwake) {
JobManager.addJob(WakeupJob("WakeupJob${user.id}", user.nextWakeupCron, user.userid))
Logger.out("Created wakeup job for user ${user.id}")
} else if (user.nextWakeup < System.currentTimeMillis() && !user.isAwake) {
// Set the user awake since the wakeup time was during downtime
user.isAwake = true
// don't increase the streak, since it is not certain that the user was awake
// user.currentStreak++
user.lastWakeup = System.currentTimeMillis()
Logger.out("Updated user ${user.id} to be awake")
}
}
Logger.out("Finished updating wakeup jobs")
}
}

View file

@ -0,0 +1,78 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.jobs
import dev.inmo.krontab.KronScheduler
import dev.kord.common.entity.Snowflake
import dev.kord.core.behavior.channel.createEmbed
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.entity.channel.MessageChannel
import kotlinx.coroutines.Job
import net.moonleay.bedge.Bot
import net.moonleay.bedge.data.database.repository.UserRepository
import net.moonleay.bedge.jobs.component.CronjobType
import net.moonleay.bedge.jobs.component.ICronjob
import net.moonleay.bedge.jobs.component.JobManager
import net.moonleay.bedge.util.EmbedColor
import net.moonleay.bedge.util.Logger
import net.moonleay.bedge.util.MessageUtil
import net.moonleay.bedge.util.TimeUtil
class WakeupJob(override val jobName: String, override val jobIncoming: String, val userId: Long) : ICronjob {
override val jobType: CronjobType
get() = CronjobType.ONCE
override val continueJob: Boolean
get() = false
override lateinit var cronjobJob: Job
override lateinit var scheduler: KronScheduler
override suspend fun jobFunction() {
Logger.out("WakeupJob, running \"$jobName\"")
val user = UserRepository.getUserByID(userId)
if (!user.isAwake){
// Failed
val brokenStreak = user.currentStreak
val isBiggestStreakYet = user.currentStreak > user.longestStreak
++user.numberOfFails
user.currentStreak = 0
user.isAwake = true
user.lastWakeup = System.currentTimeMillis()
UserRepository.update(user)
if(Bot.bot.kordRef.getChannel(Snowflake(user.targetChannelId)) != null){
val ch = Bot.bot.kordRef.getChannelOf<MessageChannel>(Snowflake(user.targetChannelId))
ch!!.createMessage {
this.embeds.add(
MessageUtil.getEmbed(
EmbedColor.ERROR,
"You failed to wake up!",
"You failed to wake up at ${TimeUtil.getHourAndMinuteFromStamp(user.nextWakeup)}!\n" +
"You lost a streak of ${user.currentStreak}" +
if(isBiggestStreakYet) ", which was your biggest streak yet." else "." +
"\nYou can try again tomorrow with `/time`",
user.userid.toString(),
)
)
}
}
}
// else: Success
JobManager.killJob(this)
}
}

View file

@ -0,0 +1,25 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.jobs.component
enum class CronjobType {
INFINITE,
ONCE,
WHILE
}

View file

@ -0,0 +1,48 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.jobs.component
import dev.inmo.krontab.KronScheduler
import kotlinx.coroutines.Job
import net.moonleay.bedge.jobs.component.CronjobType
interface ICronjob {
val jobName: String
/* /--------------- Seconds
| /------------- Minutes
| | /----------- Hours
| | | /--------- Days of months
| | | | /------- Months
| | | | | /----- (optional) Year
| | | | | | /--- (optional) Timezone offset
| | | | | | | / (optional) Week days
* * * * * * 0o *w
*/
val jobIncoming: String
val jobType: CronjobType
val continueJob: Boolean
var cronjobJob: Job
var scheduler: KronScheduler
suspend fun jobFunction()
}

View file

@ -0,0 +1,106 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.jobs.component
import dev.inmo.krontab.buildSchedule
import dev.inmo.krontab.doInfinityTz
import dev.inmo.krontab.doOnceTz
import dev.inmo.krontab.doWhileTz
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.moonleay.bedge.util.Logger
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object JobManager {
private val jobs: MutableList<ICronjob> = mutableListOf()
// Add a cronjob and register it
fun addJob(job: ICronjob) {
if (jobs.contains(job)) {
killJob(job)
}
registerJob(job)
jobs.add(job)
Logger.out("Registered job \"${job.jobName}\" of type \"${job.javaClass.name}\".")
}
// Register a cronjob
private fun registerJob(job: ICronjob) {
Logger.out(
"INFO: Registering job \"${job.jobName}\"of type ${job.javaClass.name} at ${
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
}"
)
job.cronjobJob = CoroutineScope(Dispatchers.Default).launch {
job.scheduler = buildSchedule(job.jobIncoming)
Logger.out("Registered job \"${job.jobName}\"of type ${job.javaClass.name} to run at timer \"${job.jobIncoming}\".")
when (job.jobType) {
// Runs the job once at the specified time
CronjobType.ONCE -> {
job.scheduler.doOnceTz {
job.jobFunction()
}
}
// Runs the job whiles the variable is set to true
CronjobType.WHILE -> {
job.scheduler.doWhileTz {
job.jobFunction()
job.continueJob
}
}
// Run this job until the programm stops
CronjobType.INFINITE -> {
job.scheduler.doInfinityTz {
job.jobFunction()
}
}
}
}
}
// Kill all cronjobs
fun killAllJobs() {
for (j in jobs) {
killJob(j)
}
}
// Kill a cronjob
fun killJob(j: ICronjob) {
if (!jobs.contains(j)) {
Logger.out("This job does not exist.")
return
}
Logger.out("Killing job \"${j.jobName}\" of type ${j.javaClass.name}.")
j.cronjobJob.cancel()
jobs.remove(j)
}
fun killNamedJob(name: String) {
for (j in jobs) {
if (j.jobName == name) {
killJob(j)
return
}
}
Logger.out("This job does not exist.")
}
}

View file

@ -0,0 +1,28 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import dev.kord.common.Color
enum class EmbedColor(val color: Color) {
ERROR(Color(0xE0311A)),
WARNING(Color(0xFFA500)),
SUCCESS(Color(0x52E01A)),
INFO(Color(0x4C4645)),
}

View file

@ -0,0 +1,127 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import dev.kord.common.entity.ButtonStyle
import dev.kord.core.entity.Embed
import dev.kord.rest.builder.component.ActionRowBuilder
import dev.kord.rest.builder.message.EmbedBuilder
object EmbedUtil {
fun getTimePlannerButtons(): ActionRowBuilder {
val ar = ActionRowBuilder()
ar.interactionButton(ButtonStyle.Success, "public.edit.btn.timemanagement.available") {
this.label = "Available"
}
ar.interactionButton(ButtonStyle.Primary, "public.edit.btn.timemanagement.maybeavailable") {
this.label = "May be available"
}
ar.interactionButton(ButtonStyle.Danger, "public.edit.btn.timemanagement.notavailable") {
this.label = "Not available"
}
return ar
}
fun getMatchButtons(): ActionRowBuilder {
val ar = ActionRowBuilder()
ar.interactionButton(ButtonStyle.Success, "public.edit.btn.matchmanagement.accept") {
this.label = "I'm in!"
}
ar.interactionButton(ButtonStyle.Danger, "public.edit.btn.matchmanagement.decline") {
this.label = "I'm out!"
}
/*
ar.interactionButton(ButtonStyle.Secondary, "public.edit.btn.matchmanagement.cancel") {
this.label = "Cancel this match..."
} */
return ar
}
fun replaceXWithYinValuesAtTable(x: String, y: String, e: Embed, table: Int): EmbedBuilder {
return replaceXWithYinValuesAtTable(x, y, MessageUtil.getAClonedEmbed(e), table)
}
fun replaceXWithYinValuesAtTable(x: String, y: String, ebb: EmbedBuilder, table: Int): EmbedBuilder {
val ebbb = MessageUtil.getAClonedEmbed(ebb)
ebbb.fields = mutableListOf()
for ((i, f) in ebb.fields.withIndex()) {
val fb = EmbedBuilder.Field()
fb.name = f.name
if (i == table - 1) {
val v = f.value.split("\n").toMutableList()
for ((j, l) in v.withIndex())
if (l.contains(x))
v[j] = y
v.removeIf {
!it.contains("@")
}
fb.value = v.joinToString("\n")
} else
fb.value = f.value
fb.inline = true
ebbb.fields.add(fb)
}
return ebbb
}
fun getAllUsersInTheFirstXTables(amountOfTables: Int, e: Embed): List<String> {
val users = mutableListOf<String>()
for (i in 0 until amountOfTables - 1) {
val f = e.fields[i]
if (!f.value.contains("@"))
continue // check next one. this one does not have any entries
val v = f.value.split("\n").toMutableList()
for (l in v) {
Logger.out(l)
users.add(l.subSequence(2, l.indexOf(">")).toString())
}
}
return users
}
fun addXToValuesAtTable(x: String, e: Embed, table: Int): EmbedBuilder {
return addXToValuesAtTable(x, MessageUtil.getAClonedEmbed(e), table)
}
fun addXToValuesAtTable(x: String, ebb: EmbedBuilder, table: Int): EmbedBuilder {
val ebbb = MessageUtil.getAClonedEmbed(ebb)
ebbb.fields = mutableListOf()
ebb.fields.forEachIndexed { i, f ->
val fb = EmbedBuilder.Field()
fb.name = f.name
if (i == table - 1)
fb.value = f.value + "\n<@$x>"
else {
val v = f.value.split("\n").toMutableList()
for ((j, l) in v.withIndex())
if (l.contains(x))
v[j] = ""
v.removeIf {
!it.contains("@")
}
fb.value = v.joinToString("\n")
}
fb.inline = true
ebbb.fields.add(fb)
}
return ebbb
}
}

View file

@ -0,0 +1,41 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object Logger {
private val dtf: DateTimeFormatter = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss")
fun out(msg: String) {
val caller = Thread.currentThread().stackTrace[2]
val now: LocalDateTime = LocalDateTime.now()
try {
println(
("[" + Class.forName(caller.className).simpleName + "." +
caller.methodName + ":" + caller.lineNumber + "] [" + dtf.format(now)) + "] <" + msg + ">"
)
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
// Ich kann nicht mehr
// [Klasse.Funktion] [T/M HH:MM] <NACHRICHT>
}
}

View file

@ -0,0 +1,180 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.commands.application.slash.PublicSlashCommandContext
import com.kotlindiscord.kord.extensions.components.forms.ModalForm
import com.kotlindiscord.kord.extensions.types.respond
import dev.kord.core.entity.Embed
import dev.kord.rest.builder.message.EmbedBuilder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object MessageUtil {
private val dtf: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy @ HH:mm:ss")
///Send an embedded message as a reply
suspend fun sendEmbedForPublicSlashCommand(
ctx: PublicSlashCommandContext<Arguments, ModalForm>,
color: EmbedColor,
title: String,
description: String
) {
ctx.respond {
embeds.add(
getEmbed(
color,
title,
description,
ctx.user.asUser().username + "#" + ctx.user.asUser().discriminator
)
)
}
}
///Send an embedded message with an image as a reply
suspend fun sendEmbedForPublicSlashCommandWithImage(
ctx: PublicSlashCommandContext<Arguments, ModalForm>,
color: EmbedColor,
title: String,
description: String,
thumbnailUrl: String
) {
ctx.respond {
embeds.add(
getEmbedWithImage(
color,
title,
description,
ctx.user.asUser().username + "#" + ctx.user.asUser().discriminator,
thumbnailUrl
)
)
}
}
///Get a cloned embedded message
fun getAClonedEmbed(e: Embed): EmbedBuilder {
val ebb = EmbedBuilder()
ebb.color = e.color
ebb.title = e.title
e.fields.forEach {
val fb = EmbedBuilder.Field()
fb.name = it.name
fb.value = it.value
fb.inline = it.inline
ebb.fields.add(fb)
}
ebb.description = e.description
return ebb
}
fun getAClonedEmbed(e: EmbedBuilder): EmbedBuilder {
val ebb = EmbedBuilder()
ebb.color = e.color
ebb.title = e.title
e.fields.forEach {
val fb = EmbedBuilder.Field()
fb.name = it.name
fb.value = it.value
fb.inline = it.inline
ebb.fields.add(fb)
}
ebb.description = e.description
return ebb
}
fun getEmbedWithTableWithFooter(
color: EmbedColor,
title: String,
description: String,
values: Map<String, List<String>>?,
footer: String
): EmbedBuilder {
val ebb = getEmbedWithTable(color, title, description, values)
ebb.footer = EmbedBuilder.Footer()
ebb.footer!!.text = ">m.id/$footer"
return ebb
}
///Get an embedded msg with image, title and description
fun getEmbedWithTable(
color: EmbedColor,
title: String,
description: String,
values: Map<String, List<String>>?
): EmbedBuilder {
val ebb = getEmbedSmall(color, title, description)
if (values != null)
for (key in values.keys) {
val fb = EmbedBuilder.Field()
fb.name = key
var s = ""
for (value in values[key]!!)
s += "$value\n"
fb.value = s
fb.inline = true
ebb.fields.add(fb)
}
return ebb
}
///Get an embedded msg with title and description
fun getEmbedSmall(
color: EmbedColor,
title: String,
description: String
): EmbedBuilder {
val ebb = EmbedBuilder()
ebb.title = title
ebb.description = description
ebb.color = color.color
return ebb
}
///Get an embedded msg with title, description and a src
fun getEmbed(
color: EmbedColor,
title: String,
description: String,
source: String
): EmbedBuilder {
val ebb = getEmbedSmall(color, title, description)
val now: LocalDateTime = LocalDateTime.now()
ebb.footer = EmbedBuilder.Footer()
ebb.footer!!.text = ">" + dtf.format(now) + " - $source"
return ebb
}
///Get an embedded msg with image, title, description and a src
fun getEmbedWithImage(
color: EmbedColor,
title: String,
description: String,
source: String,
thumbnailUrl: String
): EmbedBuilder {
val ebb = getEmbed(color, title, description, source)
ebb.thumbnail = EmbedBuilder.Thumbnail()
ebb.thumbnail!!.url = thumbnailUrl
return ebb
}
}

View file

@ -0,0 +1,45 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import java.net.URL
import javax.net.ssl.HttpsURLConnection
object NetUtil {
fun GETJsonData(urlIN: String, userAgent: String): String {
val startTime = System.currentTimeMillis()
val url = URL(urlIN)
val connection = url.openConnection() as HttpsURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("User-Agent", userAgent)
connection.setRequestProperty("Accept", "application/json")
val responseCode = connection.responseCode
val timeDiff = System.currentTimeMillis() - startTime
Logger.out("GET took $timeDiff ms (from: $urlIN, as $userAgent)")
return if (responseCode == HttpsURLConnection.HTTP_OK) {
val inputStream = connection.inputStream
val inputStreamReader = inputStream.reader()
val inputAsString = inputStreamReader.readText()
inputStream.close()
inputAsString
} else {
"Error $responseCode"
}
}
}

View file

@ -0,0 +1,187 @@
/*
* Bedge
* Copyright (C) 2023 moonleay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.moonleay.bedge.util
import kotlinx.datetime.DayOfWeek
import java.time.*
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
object TimeUtil {
fun getTimeFormatedShortend(time2: Long, showS: Boolean): String {
var time = time2
val days: Long = TimeUnit.MILLISECONDS
.toDays(time)
time -= TimeUnit.DAYS.toMillis(days)
val hours: Long = TimeUnit.MILLISECONDS
.toHours(time)
time -= TimeUnit.HOURS.toMillis(hours)
val minutes: Long = TimeUnit.MILLISECONDS
.toMinutes(time)
time -= TimeUnit.MINUTES.toMillis(minutes)
val seconds: Long = TimeUnit.MILLISECONDS
.toSeconds(time)
var s = ""
if (days >= 1) {
s += days.toString() + "d "
}
if (hours >= 1) {
s += hours.toString() + "h "
}
if (minutes >= 1) {
s += minutes.toString() + "m "
}
if (seconds >= 1 && hours < 1 && showS) {
s += seconds.toString() + "s"
}
if (s.isEmpty() || s.isBlank()) {
s = "None"
}
return s
}
fun getTimeFormatedRaw(time2: Long): String {
var time = time2
val days: Long = TimeUnit.MILLISECONDS
.toDays(time)
time -= TimeUnit.DAYS.toMillis(days)
val hours: Long = TimeUnit.MILLISECONDS
.toHours(time)
time -= TimeUnit.HOURS.toMillis(hours)
val minutes: Long = TimeUnit.MILLISECONDS
.toMinutes(time)
time -= TimeUnit.MINUTES.toMillis(minutes)
val seconds: Long = TimeUnit.MILLISECONDS
.toSeconds(time)
var s = ""
if (days >= 1) {
s += days.toString() + "d "
}
if (hours >= 1) {
s += hours.toString() + "h "
}
if (minutes >= 1) {
s += minutes.toString() + "m "
}
if (seconds >= 1) {
s += seconds.toString() + "s"
}
if (s.isEmpty() || s.isBlank()) {
s = "None"
}
return s
}
//This 100000%ly can be improved, I wrote this at 2am
fun getTimeUnformated(timeStr: String): Long {
var days: Long = 0
var hours: Long = 0
var minutes: Long = 0
var seconds: Long = 0
val timeArr = timeStr.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (s in timeArr) {
if (s.endsWith("d")) {
days = s.split("d".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toLong()
} else if (s.endsWith("h")) {
hours = s.split("h".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toLong()
} else if (s.endsWith("m")) {
minutes = s.split("m".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toLong()
} else if (s.endsWith("s")) {
seconds = s.split("s".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toLong()
}
}
return Duration.ofSeconds(seconds).plus(Duration.ofMinutes(minutes)).plus(Duration.ofHours(hours))
.plus(Duration.ofDays(days)).toMillis()
}
private val DaysUntilMonday: Map<String, Int> = object : HashMap<String, Int>() {
init {
put("MONDAY", 0)
put("TUESDAY", 6)
put("WEDNESDAY", 5)
put("THURSDAY", 4)
put("FRIDAY", 3)
put("SATURDAY", 2)
put("SUNDAY", 1)
}
}
// Returns the day of the month of the monday of this week
fun getMondayDayOfMonth(): Int {
return ZonedDateTime.now().with(DayOfWeek.MONDAY).dayOfMonth
}
// Returns the day of the week as an int. Monday = 0; Sunday = 6
fun getDayOfMonthInt(dow: DayOfWeek): Int {
return dow.value
}
// Returns the day of the month of the monday of the current week
fun getWeekStamp(): ZonedDateTime {
return ZonedDateTime.now(ZoneId.of("Europe/Berlin")).withDayOfMonth(getMondayDayOfMonth()).withHour(4)
.withMinute(0).withSecond(0)
}
fun getDateFromString(input: String): ZonedDateTime {
val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")
val localDateTime = LocalDateTime.parse(input, formatter)
val zoneId = ZoneId.of("UTC+2") // TODO: Add the possibility to set your timezone
return ZonedDateTime.of(localDateTime, zoneId)
}
fun getCronjobStringFromDate(zdt: ZonedDateTime): String {
// I'll have to add the possibility to set your timezone in the future
// Only subtracting 1 hour, because I want to run the job 1 hour later
val zdt_ = zdt.minusHours(1)
return "0 ${zdt_.minute} ${zdt_.hour} ${zdt_.dayOfMonth - 1} ${zdt_.month.value - 1} ${zdt_.year}"// 0o *w"
}
fun deformatJSONTime(inp: String, zone: String): Long {
// 2023-10-05T08:00:00Z
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val localDateTime = LocalDateTime.parse(inp, formatter)
val zoneId = ZoneId.of(zone) // TODO: Add the possibility to set your timezone
return ZonedDateTime.of(localDateTime, zoneId).toEpochSecond() * 1000
}
fun getZdtFromTime(inp: String, zone: String): ZonedDateTime {
val formatter = DateTimeFormatter.ofPattern("HH:mm")
val localDateTime = LocalDateTime.parse(inp, formatter)
val zoneId = ZoneId.of(zone)
val now = ZonedDateTime.now(zoneId)
val zdtPre = ZonedDateTime.of(localDateTime, zoneId).withDayOfMonth(now.dayOfMonth).withMonth(now.monthValue).withYear(now.year)
if(zdtPre.isBefore(now))
return zdtPre.plusDays(1)
return zdtPre
}
fun getHourAndMinuteFromStamp(stamp: Long): String {
val zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(stamp), ZoneId.of("UTC"))
return "${zdt.hour}:${zdt.minute}"
}
fun getTimeDifferenceFormatted(start: Long, end: Long): String {
val diff = end - start
return getTimeFormatedShortend(diff, false)
}
}

View file

@ -0,0 +1,11 @@
package net.moonleay.bedge.build
internal object BuildConstants {
const val version = "${version}"
const val ownerID = "${ownerID}"
const val kordVersion = "${kordversion}"
const val coroutinesVersion = "${coroutinesversion}"
const val ktorVersion = "${ktorversion}"
const val exposedVersion = "${exposedversion}"
const val postgresVersion = "${postgresversion}"
const val krontabVersion = "${krontabversion}"
}