Skip to content

Commit

Permalink
Upgrade to JDA 5.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
cascer1 committed Jul 25, 2024
1 parent e6d672b commit 1be2982
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ class BgGraph(

fun getBitmapBytes(bitmapFormat: BitmapEncoder.BitmapFormat): ByteArray {
val theme = settings.theme.instance
val bufferedImage = BufferedImage(theme.getImageWidth(this), theme.getImageHeight(this), BufferedImage.TYPE_INT_ARGB)
val bufferedImage =
BufferedImage(theme.getImageWidth(this), theme.getImageHeight(this), BufferedImage.TYPE_INT_ARGB)
val g = bufferedImage.createGraphics()

if (theme.overridePaint) {
Expand Down
2 changes: 1 addition & 1 deletion bot/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
dependencies {
// JDA
implementation "com.github.MinnDevelopment:jda-ktx:${jdaKtxVersion}"
implementation "club.minnced:jda-ktx:${jdaKtxVersion}"
implementation "pw.chew:jda-chewtils:${jdaChewtilsVersion}"
implementation("net.dv8tion:JDA:${jdaVersion}") {
exclude module: 'opus-java'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ class AboutCommand(
if (info.isBotPublic) {
info.setRequiredScopes("applications.commands")
info.getInviteUrl(*perms)
} else ""
} else {
""
}
} catch (e: Exception) {
logger.warn("Encountered exception while generating bot invite link", e)
""
Expand All @@ -55,7 +57,9 @@ class AboutCommand(
"Join my server [`here`](${event.client.serverInvite})"
} else if (invite) {
"Please [`invite`]($oauthLink) me to your server"
} else ""
} else {
""
}

val author = if (event.jda.getUserById(event.client.ownerId) == null) {
"<@" + event.client.ownerId + ">"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class NightscoutGraphApplicationCommand : ApplicationCommand {

val chart = getDataSet(event.user.id, hours).awaitSingle()
val imageBytes = chart.getBitmapBytes(BitmapFormat.PNG)
event.hook.editOriginalAttachments(FileUpload.fromData(imageBytes, "graph.png")).submit().await()
event.hook.editOriginalAttachments(FileUpload.fromData(imageBytes, "graph.png")).await()
applyCooldown(event.user.id)
} catch (e: Exception) {
logger.error("Error generating NS graph for ${event.user}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ class QuoteImportCommand(category: Category, parent: QuoteCommand) : DiscordComm

importQuotes.subscribe({
// on each
logger.debug("Finished adding $it")
logger.debug("Finished adding {}", it)
}, {
// on error
var errorMessage = "Import failed: ${it::class.simpleName} - ${it.message}"
Expand Down Expand Up @@ -304,7 +304,9 @@ class QuoteImportCommand(category: Category, parent: QuoteCommand) : DiscordComm
// the channel key can be missing, which is why we need a null check
val channelId = if (channel != null) {
guild?.channels?.firstOrNull { it.name == channel }?.id ?: ""
} else ""
} else {
""
}

return QuoteDTO(
quoteId = id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ class QuoteMineCommand(category: Category, parent: QuoteCommand) : DiscordComman
{
event.reply(createEmbed(event.author.name, it))
}, {
logger.info("Error finding all quotes for " + event.author.name)
})
logger.info("Error finding all quotes for " + event.author.name)
})
}

private fun createEmbed(author: String, quoteDTOs: List<QuoteDTO>): MessageEmbed {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.dongtronic.diabot.util.logger
import com.jagrosh.jdautilities.command.Command
import com.jagrosh.jdautilities.command.CommandEvent
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.channel.ChannelType
import net.dv8tion.jda.api.exceptions.ErrorResponseException
Expand All @@ -25,7 +24,7 @@ class HelpListener : Consumer<CommandEvent> {
*/
private fun sendingError(exc: Throwable, event: CommandEvent) {
if (exc is ErrorResponseException &&
exc.errorResponse != ErrorResponse.CANNOT_SEND_TO_USER
exc.errorResponse != ErrorResponse.CANNOT_SEND_TO_USER
) {
// Print a warning in console if the error code was not related to DMs being blocked
logger.warn("Unexpected error response when sending DM: ${exc.errorCode} - ${exc.meaning}")
Expand Down Expand Up @@ -53,13 +52,13 @@ class HelpListener : Consumer<CommandEvent> {
try {
// Open the DM channel and send the message
event.author.openPrivateChannel().submit()
.thenCompose { it.sendMessageEmbeds(embedBuilder.build()).submit() }
.whenComplete { _: Message?, exc: Throwable? ->
if (exc != null) {
// If there's a throwable then assume it failed
sendingError(exc, event)
.thenCompose { it.sendMessageEmbeds(embedBuilder.build()).submit() }
.whenComplete { _: Message?, exc: Throwable? ->
if (exc != null) {
// If there's a throwable then assume it failed
sendingError(exc, event)
}
}
}
} catch (ex: InsufficientPermissionException) {
event.replyError("Couldn't build help message due to missing permission: `${ex.permission}`")
}
Expand All @@ -78,15 +77,15 @@ class HelpListener : Consumer<CommandEvent> {

// Store the CompletableFuture in the queue, so we can cancel it later
val message = channel.thenCompose { it.sendMessageEmbeds(categoryBuilder.build()).submit() }
.whenComplete { _: Message?, exc: Throwable? ->
if (exc != null) {
sendingError(exc, event)
// Cancel the other messages in the queue
messageQueue.forEach { it.cancel(true) }
}
.whenComplete { _: Message?, exc: Throwable? ->
if (exc != null) {
sendingError(exc, event)
// Cancel the other messages in the queue
messageQueue.forEach { it.cancel(true) }
}

messageQueue.clear()
}
messageQueue.clear()
}
messageQueue.add(message)
}
}
Expand Down Expand Up @@ -226,41 +225,20 @@ class HelpListener : Consumer<CommandEvent> {
* @param event original CommandEvent. Used for checking permissions
* @return list of commands the user is authorized to use
*/
private fun filterAllowedCommands(commands: List<Command>, event: CommandEvent): ArrayList<Command> {
val allowedCommands = ArrayList<Command>()
private fun filterAllowedCommands(commands: List<Command>, event: CommandEvent): List<Command> {
val guildMember = event.member != null
val userPermissions = event.member?.permissions

// TODO: Refactor method to recude jump statements
for (command in commands) {
if (command.isHidden) {
continue
}

val requiredPermissions = command.userPermissions

if (requiredPermissions.isEmpty()) {
allowedCommands.add(command)
continue
}

var userPermissions: EnumSet<Permission> = Permission.getPermissions(Permission.ALL_PERMISSIONS)
if (event.member != null) {
userPermissions = event.member.permissions
}

var userIsAllowedToUseCommand = true

for (requiredPermission in requiredPermissions) {
if (!userPermissions.contains(requiredPermission)) {
userIsAllowedToUseCommand = false
}
}

if (userIsAllowedToUseCommand) {
allowedCommands.add(command)
}
if (!guildMember) {
// Message in DM, no need to check for server permissions
return commands.filter { !it.isHidden }
}

return allowedCommands
// Return all not-hidden commands that the user has permission for in the guild
return commands.filter { !it.isHidden }
.filter { command ->
userPermissions!!.containsAll(command.userPermissions.filterNotNull())
}
}

/**
Expand Down
39 changes: 23 additions & 16 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,17 @@ allprojects {
systemProperty "junit.jupiter.testinstance.lifecycle.default", "per_class"
}

group = 'com.dongtronic.diabot'
java {
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_17
}

kotlin {
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_17
}

sourceCompatibility = 17
targetCompatibility = 17
group = "com.dongtronic.diabot"

detekt {
buildUponDefaultConfig = true // preconfigure defaults
Expand Down Expand Up @@ -90,33 +97,33 @@ allprojects {
}


task stage(dependsOn: ['clean', 'shadowJar'])
task stage(dependsOn: ["clean", "shadowJar"])

shadowJar {
exclude 'logback-test.xml'
archiveBaseName.set('diabot')
archiveClassifier.set('')
archiveVersion.set('')
exclude "logback-test.xml"
archiveBaseName.set("diabot")
archiveClassifier.set("")
archiveVersion.set("")
manifest {
attributes(
'Implementation-Title': 'Diabot - a diabetes Discord bot',
'Implementation-Version': this.version,
'Main-Class': 'com.dongtronic.diabot.Main',
"Implementation-Title": "Diabot - a diabetes Discord bot",
"Implementation-Version": this.version,
"Main-Class": "com.dongtronic.diabot.Main",
// fixes retrofit v2.8 reflection warnings
'Add-Opens': 'java.base/java.lang.invoke'
"Add-Opens": "java.base/java.lang.invoke"
)
}
}

release {
tagTemplate = 'v$version'
tagTemplate = "v$version"
git {
requireBranch.set('main')
requireBranch.set("main")
signTag.set(true)
ignoredSnapshotDependencies = [ "pw.chew:jda-chewtils" ]
ignoredSnapshotDependencies = ["pw.chew:jda-chewtils"]
}
}

dependencies {
implementation project(path: ':bot')
implementation project(path: ":bot")
}
10 changes: 5 additions & 5 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ version = 1.19.6

# Plugins
shadowVersion = 7.1.2
detektVersion = 1.21.0
kotlinVersion = 1.9.24
kotlinCoroutinesVersion = 1.8.1
detektVersion = 1.23.6
kotlinVersion = 2.0.0
kotlinCoroutinesVersion = 1.9.0-RC
junitVersion = 5.8.2
releasePluginVersion = 3.0.2

Expand All @@ -18,9 +18,9 @@ reactorCoreVersion = 3.3.8.RELEASE
reactorKotlinVersion = 1.0.2.RELEASE

# JDA
jdaVersion = 5.0.0-beta.24
jdaVersion = 5.0.1
jdaChewtilsVersion = 2.0-SNAPSHOT
jdaKtxVersion = 0.11.0-beta.19
jdaKtxVersion = 0.12.0

# Parsing
romeVersion = 1.11.1
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
2 changes: 1 addition & 1 deletion system.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
java.runtime.version=11
java.runtime.version=17

0 comments on commit 1be2982

Please sign in to comment.