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

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)
}
}