├── .editorconfig ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ └── kotlin │ │ └── club │ │ └── minnced │ │ └── kjda │ │ ├── entities │ │ ├── KJDAVoice.kt │ │ ├── KJDAUser.kt │ │ ├── KJDAGuild.kt │ │ ├── KJDAHistory.kt │ │ └── KJDAMessages.kt │ │ ├── KJDAUtils.kt │ │ ├── KJDA.kt │ │ ├── events │ │ └── AsyncEventManager.kt │ │ ├── KJDABuilders.kt │ │ ├── RestPromise.kt │ │ ├── KJDAClientBuilder.kt │ │ └── builders │ │ └── KJDAEmbedBuilder.kt └── examples │ └── kotlin │ └── Runner.kt ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*.{java,kt}] 5 | indent_style = space 6 | indent_size = 4 7 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Kotlin-JDA' 2 | if (file('../JDA').exists()) 3 | includeBuild '../JDA' 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JDA-Applications/Kotlin-JDA/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Jul 15 15:16:33 CEST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.4.1-bin.zip 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 5 | 6 | # Credentials 7 | .token 8 | 9 | # Mongo Explorer plugin: 10 | .idea/**/mongoSettings.xml 11 | 12 | ## File-based project format: 13 | *.iws 14 | 15 | ## Plugin-specific files: 16 | 17 | # IntelliJ 18 | /out/ 19 | *.iml 20 | 21 | # mpeltonen/sbt-idea plugin 22 | .idea_modules/ 23 | 24 | # JIRA plugin 25 | atlassian-ide-plugin.xml 26 | 27 | # Crashlytics plugin (for Android Studio and IntelliJ) 28 | com_crashlytics_export_strings.xml 29 | crashlytics.properties 30 | crashlytics-build.properties 31 | fabric.properties 32 | 33 | .gradle/ 34 | .idea/ 35 | /gradle.properties 36 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/entities/KJDAVoice.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDAVoice") 17 | package club.minnced.kjda.entities 18 | 19 | import net.dv8tion.jda.core.entities.Guild 20 | import net.dv8tion.jda.core.entities.VoiceChannel 21 | 22 | /** Joins this VoiceChannel, shortcut for [AudioManager.openAudioConnection][net.dv8tion.jda.core.managers.AudioManager.openAudioConnection] */ 23 | fun VoiceChannel.join() = guild.audioManager.openAudioConnection(this) 24 | 25 | /** Leaves current VoiceChannel if connected. */ 26 | fun Guild.disconnect() = if (audioManager.isConnected) audioManager.closeAudioConnection() else { } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/KJDAUtils.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package club.minnced.kjda 18 | 19 | operator fun CharSequence.times(amount: Int): String { 20 | val out = StringBuilder(this) 21 | repeat(amount) { 22 | out += this 23 | } 24 | return out.toString() 25 | } 26 | 27 | val SPACES = Regex("\\s+") 28 | 29 | operator fun CharSequence.div(amount: Int): List { 30 | if (amount < 1) 31 | return this.split(SPACES) 32 | return this.split(SPACES, amount) 33 | } 34 | 35 | operator fun String.rem(col: Collection) = rem(col.toTypedArray()) 36 | operator fun String.rem(arr: Array) = String.format(this, *arr) 37 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/entities/KJDAUser.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDAUser") 17 | package club.minnced.kjda.entities 18 | 19 | import net.dv8tion.jda.core.OnlineStatus 20 | import net.dv8tion.jda.core.entities.* 21 | 22 | typealias Status = OnlineStatus 23 | 24 | val User.game: Game? 25 | get() = mutualGuilds.first().getMember(this).game 26 | 27 | val User.status: Status 28 | get() = mutualGuilds.first().getMember(this).onlineStatus 29 | 30 | val User.isSelf: Boolean 31 | get() = this is SelfUser 32 | 33 | val Member.connectedChannel: VoiceChannel? 34 | get() = voiceState.channel 35 | 36 | val Member.isConnected: Boolean 37 | get() = connectedChannel !== null 38 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/entities/KJDAGuild.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package club.minnced.kjda.entities 18 | 19 | import net.dv8tion.jda.core.Permission.MESSAGE_WRITE 20 | import net.dv8tion.jda.core.entities.Guild 21 | import net.dv8tion.jda.core.entities.Member 22 | import net.dv8tion.jda.core.entities.TextChannel 23 | import net.dv8tion.jda.core.requests.RestAction 24 | 25 | 26 | fun Guild.ban(id: Long, days: Int = 0) = controller.ban(id.toString(), days) 27 | fun Guild.ban(id: String, days: Int = 0) = controller.ban(id, days) 28 | infix fun Guild.kick(member: Member) = controller.kick(member) 29 | 30 | infix fun Member.mute(channel: TextChannel): RestAction<*> { 31 | val over = channel.getPermissionOverride(this) 32 | if (over !== null) return over.manager.deny(MESSAGE_WRITE) 33 | return channel.createPermissionOverride(this).setDeny(MESSAGE_WRITE) 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin-JDA 2 | 3 | JDA: [ ![jda](https://api.bintray.com/packages/dv8fromtheworld/maven/JDA/images/download.svg) ](https://github.com/DV8FromTheWorld/JDA)
4 | Kotlin-JDA: [ ![jitpack](https://jitpack.io/v/JDA-Applications/Kotlin-JDA.svg) ](https://jitpack.io/#JDA-Applications/Kotlin-JDA) 5 | 6 | A kotlin interface for JDA, providing extensions and convenience for kotlin based projects that want to interact with JDA 7 | 8 | ## Setup 9 | 10 | ### Gradle 11 | 12 | ```gradle 13 | repositories { 14 | jcenter() 15 | maven { url 'https://jitpack.io' } 16 | } 17 | 18 | dependencies { 19 | compile 'net.dv8tion:JDA:3.0.0_156' 20 | compile 'com.github.JDA-Applications:Kotlin-JDA:master-SNAPSHOT' 21 | } 22 | ``` 23 | 24 | > Replace the JDA version if needed
25 | > Kotlin setup is up to you! 26 | 27 | ### Maven 28 | 29 | ```xml 30 | 31 | 32 | jitpack.io 33 | https://jitpack.io 34 | 35 | 36 | jcenter 37 | jcenter-bintray 38 | http://jcenter.bintray.com 39 | 40 | 41 | 42 | 43 | com.github.JDA-Applications 44 | Kotlin-JDA 45 | master-SNAPSHOT 46 | 47 | 48 | net.dv8tion 49 | JDA 50 | 3.0.0_156 51 | 52 | 53 | ``` 54 | 55 | > Replace the JDA version if needed
56 | > Kotlin setup is up to you! 57 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/KJDA.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDA") 17 | package club.minnced.kjda 18 | 19 | import net.dv8tion.jda.core.JDA 20 | import net.dv8tion.jda.core.OnlineStatus 21 | import net.dv8tion.jda.core.entities.Game 22 | import net.dv8tion.jda.core.entities.impl.JDAImpl 23 | import net.dv8tion.jda.core.events.Event 24 | 25 | typealias Status = OnlineStatus 26 | 27 | /** Sets the game for the current session using [Presence.setGame][net.dv8tion.jda.core.managers.Presence.setGame] */ 28 | infix inline fun JDA.game(lazy: () -> Game): JDA { 29 | presence.game = lazy() 30 | return this 31 | } 32 | /** Sets the online status for the current session using [Presence.setStatus][net.dv8tion.jda.core.managers.Presence.setStatus] */ 33 | infix inline fun JDA.status(lazy: () -> Status): JDA { 34 | presence.status = lazy() 35 | return this 36 | } 37 | /** Sets the online status for the current session using [Presence.setIdle][net.dv8tion.jda.core.managers.Presence.setIdle] */ 38 | infix inline fun JDA.idle(lazy: () -> Boolean): JDA { 39 | presence.isIdle = lazy() 40 | return this 41 | } 42 | 43 | /** 44 | * Fires the specified Event on the receiving JDA instance 45 | */ 46 | infix fun JDA.emit(event: Event) { 47 | check(this is JDAImpl) 48 | (this as JDAImpl).eventManager.handle(event) 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/events/AsyncEventManager.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package club.minnced.kjda.events 18 | 19 | import net.dv8tion.jda.core.events.Event 20 | import net.dv8tion.jda.core.hooks.EventListener 21 | import net.dv8tion.jda.core.hooks.IEventManager 22 | import java.util.concurrent.CopyOnWriteArraySet 23 | import java.util.concurrent.ExecutorService 24 | import java.util.concurrent.Executors 25 | 26 | typealias static = JvmStatic 27 | 28 | class AsyncEventManager(private val executor: ExecutorService = AsyncEventManager.POOL) : IEventManager { 29 | 30 | companion object { 31 | @static val POOL: ExecutorService by lazy { 32 | Executors.newCachedThreadPool { 33 | val t = Thread(it, "EventThread") 34 | t.isDaemon = true 35 | t 36 | } 37 | } 38 | } 39 | 40 | private val listeners = CopyOnWriteArraySet() 41 | 42 | override fun handle(event: Event?) = executor.execute { listeners.forEach { 43 | try { 44 | it.onEvent(event) 45 | } 46 | catch (ex: Throwable) { 47 | ex.printStackTrace() 48 | }} 49 | } 50 | 51 | override fun register(listener: Any?) { 52 | require(listener is EventListener) { 53 | "Listener must implement EventListener!" 54 | } 55 | listeners += listener as EventListener 56 | } 57 | 58 | override fun getRegisteredListeners(): MutableList = mutableListOf(listeners) 59 | 60 | override fun unregister(listener: Any?) { 61 | if (listener is EventListener) 62 | listeners -= listener 63 | } 64 | } -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/entities/KJDAHistory.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package club.minnced.kjda.entities 18 | 19 | import club.minnced.kjda.after 20 | import club.minnced.kjda.get 21 | import kotlinx.coroutines.experimental.CommonPool 22 | import kotlinx.coroutines.experimental.CoroutineDispatcher 23 | import kotlinx.coroutines.experimental.channels.produce 24 | import kotlinx.coroutines.experimental.runBlocking 25 | import net.dv8tion.jda.core.entities.Message 26 | import net.dv8tion.jda.core.entities.MessageChannel 27 | import net.dv8tion.jda.core.entities.MessageHistory 28 | import java.util.LinkedList 29 | import java.util.Queue 30 | import java.util.concurrent.TimeUnit.SECONDS 31 | import kotlin.coroutines.experimental.buildSequence 32 | 33 | fun MessageHistory.paginated() = produce(CommonPool) { 34 | val messages: Queue = LinkedList(retrievePast(100).get()) 35 | do { 36 | while (messages.isNotEmpty()) 37 | send(messages.poll()) 38 | messages += retrievePast(100).after(1, SECONDS) ?: break 39 | } 40 | while (messages.isNotEmpty()) 41 | } 42 | 43 | fun MessageChannel.messages(context: CoroutineDispatcher = CommonPool) = produce(context) { 44 | val iterable = iterableHistory 45 | iterable.forEach { send(it) } 46 | close() 47 | } 48 | 49 | fun MessageChannel.asSequence(): Sequence { 50 | val messages = messages() 51 | return buildSequence { 52 | runBlocking { 53 | messages.receiveOrNull() 54 | } 55 | } 56 | } 57 | 58 | fun MessageChannel.map(mapper: (Message) -> R) = asSequence().map(mapper) 59 | 60 | fun MessageChannel.filter(filter: (Message) -> Boolean) = asSequence().filter(filter) 61 | 62 | fun MessageChannel.forEach(block: (Message) -> Unit) = asSequence().forEach(block) 63 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/KJDABuilders.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDABuilders") 17 | package club.minnced.kjda 18 | 19 | import club.minnced.kjda.builders.KEmbedBuilder 20 | import net.dv8tion.jda.core.MessageBuilder 21 | import net.dv8tion.jda.core.entities.IMentionable 22 | import net.dv8tion.jda.core.entities.Message 23 | import net.dv8tion.jda.core.entities.MessageEmbed 24 | 25 | /** 26 | * Constructs a [Message] from the specified [init] function 27 | * which has a [MessageBuilder] as its receiver. 28 | * 29 | * To set an embed use [embed]! 30 | * 31 | * @param[builder] 32 | * An optional [MessageBuilder] to use as receiver, 33 | * this creates a new instance by default. 34 | * @param[init] 35 | * A function which constructs a new [Message] by using 36 | * the receiving [MessageBuilder] 37 | * 38 | * @return[Message] - a sendable finished Message instance 39 | */ 40 | fun message(builder: MessageBuilder = MessageBuilder(), init: MessageBuilder.() -> Unit): Message { 41 | builder.init() 42 | return builder.build() 43 | } 44 | 45 | operator fun Appendable.plusAssign(other: CharSequence) { 46 | append(other) 47 | } 48 | 49 | operator fun Appendable.plusAssign(other: Char) { 50 | append(other) 51 | } 52 | 53 | operator fun Appendable.plusAssign(other: IMentionable) { 54 | append(other.asMention) 55 | } 56 | 57 | /** 58 | * Constructs a [MessageEmbed] for the receiving [MessageBuilder] 59 | * and sets that constructed Embed using [MessageBuilder.setEmbed]! 60 | * 61 | * @param[init] 62 | * A function which constructs a [MessageEmbed] from the receiving 63 | * [EmbedBuilder] 64 | * 65 | * @receiver[MessageBuilder] 66 | * 67 | * @return[MessageBuilder] - current MessageBuilder 68 | */ 69 | infix inline fun MessageBuilder.embed(crossinline init: KEmbedBuilder.() -> Unit): MessageBuilder 70 | = setEmbed(club.minnced.kjda.builders.embed { init() }) 71 | -------------------------------------------------------------------------------- /src/examples/kotlin/Runner.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import club.minnced.kjda.* 18 | import club.minnced.kjda.entities.sendAsync 19 | import net.dv8tion.jda.core.AccountType.BOT 20 | import net.dv8tion.jda.core.OnlineStatus.DO_NOT_DISTURB 21 | import net.dv8tion.jda.core.events.ReadyEvent 22 | import net.dv8tion.jda.core.events.message.MessageReceivedEvent 23 | import net.dv8tion.jda.core.hooks.EventListener 24 | import net.dv8tion.jda.core.hooks.ListenerAdapter 25 | import java.io.File 26 | import java.util.concurrent.TimeUnit.SECONDS 27 | 28 | fun main(args: Array) { 29 | client(BOT) { 30 | token { File(".token").readText() } 31 | game { 32 | "Powered by Kotlin-JDA" 33 | } 34 | 35 | status { DO_NOT_DISTURB } 36 | 37 | this += Runner() 38 | this += EventListener { 39 | if (it is ReadyEvent) 40 | println("Dab!!!") 41 | } 42 | 43 | httpSettings { 44 | connectTimeout(2, SECONDS) 45 | readTimeout(3, SECONDS) 46 | writeTimeout(2, SECONDS) 47 | } 48 | 49 | websocketSettings { 50 | connectionTimeout = SECONDS.toMillis(1).toInt() 51 | } 52 | } 53 | } 54 | 55 | class Runner : ListenerAdapter() { 56 | 57 | override fun onMessageReceived(event: MessageReceivedEvent) { 58 | if (event.author.isBot || event.author == event.jda.selfUser) 59 | return 60 | val start = System.currentTimeMillis() 61 | event.channel.sendTyping().onlyIf(event.message.rawContent == ".ping") { 62 | event.channel.sendAsync { 63 | this += "Ping" 64 | embed { 65 | field { 66 | name = "Time" 67 | value = (System.currentTimeMillis() - start).toString() 68 | } 69 | } 70 | } then { 71 | println("Sent Ping response! [${it?.embeds?.firstOrNull()?.fields?.first()?.value}]") 72 | } catch { it?.printStackTrace() } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/RestPromise.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:Suppress("UNUSED") 17 | package club.minnced.kjda 18 | 19 | import kotlinx.coroutines.experimental.* 20 | import net.dv8tion.jda.core.requests.RestAction 21 | import java.util.concurrent.TimeUnit 22 | import java.util.concurrent.TimeUnit.MILLISECONDS 23 | import kotlin.coroutines.experimental.CoroutineContext 24 | 25 | /** Constructs a new [RestPromise] for this [RestAction] instance */ 26 | fun RestAction.promise() = RestPromise(this) 27 | 28 | /** Shortcut for [RestPromise.then] */ 29 | infix fun RestAction.then(apply: V?.() -> Unit) = this.promise().then { 30 | it.apply() 31 | } 32 | 33 | /** Shortcut for [RestPromise.catch] */ 34 | infix fun RestAction.catch(apply: Throwable?.() -> Unit) = this.promise().catch { 35 | it.apply() 36 | } 37 | 38 | // Conditional 39 | fun RestAction.onlyIf(condition: Boolean, block: RestPromise.() -> Unit = { }) { 40 | if (condition) 41 | this.promise().block() 42 | } 43 | 44 | fun RestAction.unless(condition: Boolean, block: RestPromise.() -> Unit = { }) { 45 | if (!condition) 46 | this.promise().block() 47 | } 48 | 49 | // Coroutines 50 | fun RestAction.prepare(context: CoroutineContext = CommonPool) = async(context, start = false) { 51 | this@prepare.promise() 52 | } 53 | 54 | fun RestAction.start(context: CoroutineContext = CommonPool) = launch(context) { 55 | this@start.queue() 56 | } 57 | 58 | suspend fun RestAction.get(context: CoroutineContext = CommonPool) = run(context) { 59 | this@get.complete() 60 | } 61 | 62 | suspend fun RestAction.after(time: Long, unit: TimeUnit = MILLISECONDS, context: CoroutineContext = CommonPool) 63 | = run(context) { 64 | delay(time, unit) 65 | this@after.get() 66 | } 67 | 68 | /** 69 | * This class allows the end-user to specify callback behaviour after issuing 70 | * a request. 71 | * 72 | * ```kotlin 73 | * channel.sendMessage("Hello").promise() then { 74 | * println("Sent Message $it") 75 | * } catch { 76 | * println("Failed to send Message") 77 | * it.printStackTrace() 78 | * } 79 | * ``` 80 | * 81 | * @constructor Creates a new RestPromise for the specified [RestAction] and 82 | * calls the [RestAction.queue] 83 | */ 84 | class RestPromise(action: RestAction) { 85 | 86 | private val success = Callback() 87 | private val failure = Callback() 88 | 89 | /** 90 | * Overrides the internal Success-Callback. 91 | * 92 | * The provided function is called immediately if this already finished 93 | * Successfully. 94 | * 95 | * @param[lazyCallback] The function to replace the current Success-Callback 96 | * 97 | * @return The current RestPromise 98 | */ 99 | infix fun then(lazyCallback: (V?) -> Unit): RestPromise { 100 | success.backing = lazyCallback 101 | return this 102 | } 103 | 104 | /** 105 | * Overrides the internal Failure-Callback. 106 | * 107 | * The provided function is called immediately if this already failed. 108 | * 109 | * @param[lazyHandler] The function to replace the current Failure-Callback 110 | * 111 | * @return The current RestPromise 112 | */ 113 | infix fun catch(lazyHandler: (Throwable?) -> Unit): RestPromise { 114 | failure.backing = lazyHandler 115 | return this 116 | } 117 | 118 | init { 119 | action.queue({ success.call(it) }, { failure.call(it) }) 120 | } 121 | 122 | } 123 | 124 | @FunctionalInterface 125 | internal class Callback { 126 | 127 | var finishedValue: T? = null 128 | var finished: Boolean = false 129 | 130 | var backing: (T?) -> Unit = { } 131 | set(value) { 132 | if (finished) 133 | value(finishedValue) 134 | field = value 135 | } 136 | 137 | fun call(value: T?): Unit = synchronized( backing ) { 138 | finished = true 139 | finishedValue = value 140 | backing(value) 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/KJDAClientBuilder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDAClientBuilder") 17 | 18 | package club.minnced.kjda 19 | 20 | import com.neovisionaries.ws.client.WebSocketFactory 21 | import net.dv8tion.jda.core.AccountType 22 | import net.dv8tion.jda.core.JDA 23 | import net.dv8tion.jda.core.JDABuilder 24 | import net.dv8tion.jda.core.OnlineStatus 25 | import net.dv8tion.jda.core.audio.factory.IAudioSendFactory 26 | import net.dv8tion.jda.core.entities.Game 27 | import net.dv8tion.jda.core.hooks.IEventManager 28 | import okhttp3.OkHttpClient 29 | 30 | /** 31 | * Constructs a new [JDABuilder] and applies the specified 32 | * init function `() -> Unit` to that receiver. 33 | * This uses [JDABuilder.buildAsync] 34 | * 35 | * The token is not required here, however needs to be configured in the given function! 36 | * 37 | * @param[accountType] 38 | * The [AccountType] for the account being issued for creation 39 | * @param[init] 40 | * The function which uses the constructed JDABuilder as receiver to setup 41 | * the JDA information before building it 42 | * 43 | * @sample client 44 | * 45 | * @see JDABuilder 46 | */ 47 | fun client(accountType: AccountType, init: JDABuilder.() -> Unit): JDA { 48 | val builder = JDABuilder(accountType) 49 | builder.init() 50 | return builder.buildAsync() 51 | } 52 | 53 | /** Lazy infix overload for [JDABuilder.setToken] */ 54 | infix inline fun T.token(lazyToken: () -> String): T 55 | = this.setToken(lazyToken()) as T 56 | /** Lazy infix overload for [JDABuilder.setGame] */ 57 | infix inline fun T.game(lazy: () -> String): T 58 | = this.setGame(Game.of(lazy())) as T 59 | /** Lazy infix overload for [JDABuilder.setStatus] */ 60 | infix inline fun T.status(lazy: () -> OnlineStatus): T 61 | = this.setStatus(lazy()) as T 62 | /** Lazy infix overload for [JDABuilder.setEventManager] */ 63 | infix inline fun T.manager(lazy: () -> IEventManager): T 64 | = this.setEventManager(lazy()) as T 65 | /** Lazy infix overload for [JDABuilder.addEventListener] */ 66 | infix inline fun T.listener(lazy: () -> Any): T 67 | = this.addEventListener(lazy()) as T 68 | /** Lazy infix overload for [JDABuilder.setAudioSendFactory] */ 69 | infix inline fun T.audioSendFactory(lazy: () -> IAudioSendFactory): T 70 | = this.setAudioSendFactory(lazy()) as T 71 | 72 | /** Infix overload for [JDABuilder.setIdle] */ 73 | infix inline fun T.idle(lazy: Boolean): T 74 | = this.setIdle(lazy) as T 75 | /** Infix overload for [JDABuilder.setEnableShutdownHook] */ 76 | infix inline fun T.shutdownHook(lazy: Boolean): T 77 | = this.setEnableShutdownHook(lazy) as T 78 | /** Infix overload for [JDABuilder.setAudioEnabled] */ 79 | infix inline fun T.audio(lazy: Boolean): T 80 | = this.setAudioEnabled(lazy) as T 81 | /** Infix overload for [JDABuilder.setAutoReconnect] */ 82 | infix inline fun T.autoReconnect(lazy: Boolean): T 83 | = this.setAutoReconnect(lazy) as T 84 | 85 | /** 86 | * Provides new WebSocketFactory and calls the provided lazy 87 | * initializer to allow setting options like timeouts 88 | */ 89 | infix inline fun T.websocketSettings(init: WebSocketFactory.() -> Unit): T { 90 | val factory = WebSocketFactory() 91 | factory.init() 92 | setWebsocketFactory(factory) 93 | return this 94 | } 95 | 96 | /** 97 | * Provides new OkHttpClient.Builder and calls the provided lazy 98 | * initializer to allow setting options like timeouts 99 | */ 100 | infix inline fun T.httpSettings(init: OkHttpClient.Builder.() -> Unit): T { 101 | val builder = OkHttpClient.Builder() 102 | builder.init() 103 | setHttpClientBuilder(builder) 104 | return this 105 | } 106 | 107 | /** Overload for [JDABuilder.addEventListener] */ 108 | inline fun T.listener(vararg listener: Any): T 109 | = this.addEventListener(*listener) as T 110 | /** Overload for [JDABuilder.removeEventListener] */ 111 | inline fun T.removeListener(vararg listener: Any): T 112 | = this.removeEventListener(*listener) as T 113 | 114 | /** Operator overload for [JDABuilder.addEventListener] */ 115 | inline operator fun T.plusAssign(other: Any) { listener(other) } 116 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/builders/KJDAEmbedBuilder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | @file:JvmName("KJDAEmbedBuilder") 18 | package club.minnced.kjda.builders 19 | 20 | import net.dv8tion.jda.core.EmbedBuilder 21 | import net.dv8tion.jda.core.entities.IMentionable 22 | import net.dv8tion.jda.core.entities.MessageEmbed 23 | import net.dv8tion.jda.core.entities.MessageEmbed.Field 24 | import java.awt.Color 25 | import java.time.temporal.TemporalAccessor 26 | 27 | class KEmbedBuilder internal constructor() : Appendable { 28 | 29 | val fields: MutableList = mutableListOf() 30 | var description: StringBuilder = StringBuilder() 31 | 32 | var title: String? = null 33 | var url : String? = null 34 | var color: Int? = null 35 | set(value) { field = value?.and(0xFFFFFF) } 36 | 37 | var thumbnail: String? = null 38 | var image : String? = null 39 | 40 | var time : TemporalAccessor? = null 41 | 42 | var author: KEmbedEntity? = null 43 | var footer: KEmbedEntity? = null 44 | 45 | 46 | internal fun build() = with (EmbedBuilder()) { 47 | val (description, fields, title, url, time, color, author, thumbnail, footer, image) = this@KEmbedBuilder 48 | fields.forEach { addField(it) } 49 | 50 | if (!description.isNullOrBlank()) 51 | setDescription(description) 52 | if (!title.isNullOrBlank()) 53 | setTitle(title, url) 54 | 55 | if (image !== null) 56 | setImage(image) 57 | if (time !== null) 58 | setTimestamp(time) 59 | if (thumbnail !== null) 60 | setThumbnail(thumbnail) 61 | 62 | if (color !== null && 0 <= color) 63 | setColor(Color(color)) 64 | 65 | if (footer !== null) 66 | setFooter(footer.value, footer.icon) 67 | if (author !== null) 68 | setAuthor(author.value, author.url, author.icon) 69 | 70 | build() 71 | } 72 | 73 | /////////////////////////////// 74 | /// Components 75 | /////////////////////////////// 76 | 77 | operator fun component1() = description 78 | operator fun component2() = fields 79 | operator fun component3() = title 80 | operator fun component4() = url 81 | operator fun component5() = time 82 | operator fun component6() = color 83 | operator fun component7() = author 84 | operator fun component8() = thumbnail 85 | operator fun component9() = footer 86 | operator fun component10() = image 87 | 88 | /////////////////////////////// 89 | /// Appendable implementation 90 | /////////////////////////////// 91 | 92 | override fun append(csq: CharSequence?): KEmbedBuilder { 93 | description.append(csq) 94 | return this 95 | } 96 | override fun append(csq: CharSequence?, start: Int, end: Int): KEmbedBuilder { 97 | description.append(csq, start, end) 98 | return this 99 | } 100 | override fun append(c: Char): KEmbedBuilder { 101 | description.append(c) 102 | return this 103 | } 104 | 105 | infix fun append(any: Any?) = append(any.normalize()) 106 | infix fun appendln(any: Any?) = append(any).appendln() 107 | fun appendln() = append(System.lineSeparator()) 108 | 109 | operator fun plusAssign(any: Any?) { append(any) } 110 | 111 | /////////////////////////////// 112 | /// Lazy Setters 113 | /////////////////////////////// 114 | 115 | infix inline fun description(lazy: () -> String): KEmbedBuilder { 116 | description = StringBuilder(lazy()) 117 | return this 118 | } 119 | infix inline fun image(lazy: () -> String): KEmbedBuilder { 120 | image = lazy() 121 | return this 122 | } 123 | infix inline fun url(lazy: () -> String): KEmbedBuilder { 124 | url = lazy() 125 | return this 126 | } 127 | infix inline fun title(lazy: () -> String): KEmbedBuilder { 128 | title = lazy() 129 | return this 130 | } 131 | infix inline fun thumbnail(lazy: () -> String): KEmbedBuilder { 132 | thumbnail = lazy() 133 | return this 134 | } 135 | infix inline fun time(lazy: () -> TemporalAccessor): KEmbedBuilder { 136 | time = lazy() 137 | return this 138 | } 139 | infix inline fun color(lazy: () -> Int): KEmbedBuilder { 140 | color = lazy() 141 | return this 142 | } 143 | 144 | infix inline fun author(lazy: KEmbedEntity.() -> Unit): KEmbedBuilder { 145 | val data = KEmbedEntity() 146 | data.lazy() 147 | author = data 148 | return this 149 | } 150 | infix inline fun footer(lazy: KEmbedEntity.() -> Unit): KEmbedBuilder { 151 | val data = KEmbedEntity() 152 | data.lazy() 153 | footer = data 154 | return this 155 | } 156 | 157 | infix fun field(lazy: FieldBuilder.() -> Unit): KEmbedBuilder { 158 | val builder = FieldBuilder() 159 | builder.lazy() 160 | fields.add(builder.build()) 161 | return this 162 | } 163 | 164 | } 165 | 166 | data class KEmbedEntity( 167 | var value: String = EmbedBuilder.ZERO_WIDTH_SPACE, 168 | var url: String? = null, 169 | var icon: String? = null) 170 | 171 | class FieldBuilder : Appendable { 172 | 173 | var name: String = EmbedBuilder.ZERO_WIDTH_SPACE 174 | var value: String = EmbedBuilder.ZERO_WIDTH_SPACE 175 | var inline: Boolean = true 176 | 177 | 178 | operator fun plusAssign(any: Any?) { append(any) } 179 | 180 | 181 | override fun append(csq: CharSequence?): FieldBuilder { 182 | value += csq 183 | return this 184 | } 185 | 186 | override fun append(csq: CharSequence?, start: Int, end: Int) 187 | = append(csq?.subSequence(start..end)) 188 | override fun append(c: Char) 189 | = append(c.toString()) 190 | 191 | 192 | infix fun appendln(any: Any?) = append(any).appendln() 193 | fun appendln() = append(System.lineSeparator()) 194 | fun append(any: Any?) = append(any.normalize()) 195 | 196 | internal fun build() = Field(name, value, inline) 197 | 198 | } 199 | 200 | var KEmbedBuilder.colorAwt: Color? 201 | get() = Color(color ?: 0) 202 | set(value) { color = value?.rgb } 203 | 204 | internal fun Any?.normalize() = if (this is IMentionable) asMention else toString() 205 | 206 | fun embed(init: KEmbedBuilder.() -> Unit): MessageEmbed = with (KEmbedBuilder()) { 207 | init() 208 | build() 209 | } 210 | -------------------------------------------------------------------------------- /src/main/kotlin/club/minnced/kjda/entities/KJDAMessages.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 - 2017 Florian Spieß 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @file:JvmName("KJDAMessages") 17 | package club.minnced.kjda.entities 18 | 19 | import club.minnced.kjda.* 20 | import club.minnced.kjda.builders.KEmbedBuilder 21 | import net.dv8tion.jda.core.MessageBuilder 22 | import net.dv8tion.jda.core.entities.Message 23 | import net.dv8tion.jda.core.entities.MessageChannel 24 | import net.dv8tion.jda.core.entities.MessageEmbed 25 | 26 | /** 27 | * Sends a new [Message] to the receiving [MessageChannel] 28 | * and returns the resulting [Message] object. 29 | * 30 | * It is recommended to use [sendAsync] if the returned 31 | * [Message] is not used. 32 | * 33 | * @param[init] 34 | * A function which holds a [MessageBuilder] as its receiver 35 | * 36 | * @receiver[MessageChannel] 37 | * 38 | * @return [Message] of successful send task. 39 | */ 40 | infix fun MessageChannel.send(init: MessageBuilder.() -> Unit): Message { 41 | val msg = message(init = init) 42 | return sendMessage(msg).complete() 43 | } 44 | 45 | /** 46 | * Sends a new [Message] constructed from the contents 47 | * of the provided [KMessage]. 48 | * 49 | * It is recommended to [sendAsync] when the resulting [Message] 50 | * is not used. 51 | * 52 | * @param[message] 53 | * A sendable [KMessage] instance 54 | * 55 | * @throws[IllegalArgumentException] 56 | * If the provided message is empty 57 | * 58 | * @return[Message] - The message that has been processed 59 | */ 60 | infix fun MessageChannel.send(message: KMessage): Message { 61 | require(message.sendable) { 62 | "Cannot send empty message!" 63 | } 64 | 65 | val (content, tts, embed) = message 66 | return send { 67 | if (content !== null) 68 | this += content 69 | if (embed !== null) 70 | this.setEmbed(embed) 71 | this.setTTS(tts) 72 | } 73 | } 74 | 75 | /** 76 | * Sends a new [Message] to the receiving [MessageChannel] 77 | * and returns the resulting [Message] object. 78 | * 79 | * It is recommended to use [sendTextAsync] if the returned 80 | * [Message] is not used. 81 | * 82 | * @param[lazyContent] 83 | * A function which provides anything and will be converted to a [String] 84 | * to be provided as `Message Content`. 85 | * 86 | * @receiver[MessageChannel] 87 | * 88 | * @return [Message] of successful send task. 89 | */ 90 | infix fun MessageChannel.sendText(lazyContent: () -> Any): Message { 91 | return sendMessage(lazyContent().toString()).complete() 92 | } 93 | 94 | /** 95 | * Sends a new [MessageEmbed][net.dv8tion.jda.core.entities.MessageEmbed] to the receiving [MessageChannel] 96 | * and returns the resulting [Message] object. 97 | * 98 | * It is recommended to use [sendEmbedAsync] if the returned 99 | * [Message] is not used. 100 | * 101 | * @param[init] 102 | * A function which holds an [EmbedBuilder] as its receiver 103 | * 104 | * @receiver[MessageChannel] 105 | * 106 | * @return [Message] of successful send task. 107 | */ 108 | infix fun MessageChannel.sendEmbed(init: KEmbedBuilder.() -> Unit): Message { 109 | val msg = message { embed(init) } 110 | return sendMessage(msg).complete() 111 | } 112 | 113 | /** 114 | * Sends a [Message] to the receiving [MessageChannel] 115 | * and returns a [RestPromise] to represent the async task. 116 | * 117 | * You can use [RestPromise.then] and [RestPromise.catch] to 118 | * handle success and failure. 119 | * 120 | * @param[init] 121 | * A function which constructs a [Message] instance using 122 | * a [MessageBuilder] as its receiver. 123 | * 124 | * @receiver[MessageChannel] 125 | * 126 | * @return A [RestPromise] representing the send task 127 | */ 128 | infix fun MessageChannel.sendAsync(init: MessageBuilder.() -> Unit): RestPromise { 129 | val msg = message(init = init) 130 | return sendMessage(msg).promise() 131 | } 132 | 133 | /** 134 | * Sends a new [Message] constructed from the contents 135 | * of the provided [KMessage]. 136 | * 137 | * @param[message] 138 | * A sendable [KMessage] instance 139 | * 140 | * @throws[IllegalArgumentException] 141 | * If the provided message is empty 142 | * 143 | * @return[RestPromise] - RestPromise representing the send task 144 | */ 145 | infix fun MessageChannel.sendAsync(message: KMessage): RestPromise { 146 | require(message.sendable) { 147 | "Cannot send empty message!" 148 | } 149 | 150 | val (content, tts, embed) = message 151 | return sendAsync { 152 | if (content !== null) 153 | this += content 154 | if (embed !== null) 155 | this.setEmbed(embed) 156 | this.setTTS(tts) 157 | } 158 | } 159 | 160 | /** 161 | * Sends a [Message] to the receiving [MessageChannel] 162 | * and returns a [RestPromise] to represent the async task. 163 | * 164 | * You can use [RestPromise.then] and [RestPromise.catch] to 165 | * handle success and failure. 166 | * 167 | * @param[lazyContent] 168 | * A function which constructs a [Message] instance using 169 | * the provided function lazy load its content using a [Any.toString] call 170 | * 171 | * @receiver[MessageChannel] 172 | * 173 | * @return A [RestPromise] representing the send task 174 | */ 175 | infix fun MessageChannel.sendTextAsync(lazyContent: () -> Any): RestPromise { 176 | return sendMessage(lazyContent().toString()).promise() 177 | } 178 | 179 | /** 180 | * Sends a [MessageEmbed][net.dv8tion.jda.core.entities.MessageEmbed] to the receiving [MessageChannel] 181 | * and returns a [RestPromise] to represent the async task. 182 | * 183 | * You can use [RestPromise.then] and [RestPromise.catch] to 184 | * handle success and failure. 185 | * 186 | * @param[init] 187 | * A function which constructs a [Message] instance using 188 | * a [EmbedBuilder] as its receiver. 189 | * 190 | * @receiver[MessageChannel] 191 | * 192 | * @return A [RestPromise] representing the send task 193 | */ 194 | infix fun MessageChannel.sendEmbedAsync(init: KEmbedBuilder.() -> Unit): RestPromise { 195 | val msg = message { 196 | embed(init) 197 | } 198 | return sendMessage(msg).promise() 199 | } 200 | 201 | 202 | infix fun Message.edit(init: MessageBuilder.() -> Unit): Message { 203 | val msg = message(init = init) 204 | return editMessage(msg).complete() 205 | } 206 | 207 | infix fun Message.edit(message: KMessage): Message { 208 | require(message.sendable) { 209 | "Cannot send empty message!" 210 | } 211 | 212 | val (content, tts, embed) = message 213 | return edit { 214 | if (content !== null) 215 | this += content 216 | if (embed !== null) 217 | this.setEmbed(embed) 218 | this.setTTS(tts) 219 | } 220 | } 221 | 222 | infix fun Message.editText(lazyContent: () -> Any): Message { 223 | return editMessage(lazyContent().toString()).complete() 224 | } 225 | 226 | infix fun Message.editEmbed(init: KEmbedBuilder.() -> Unit): Message { 227 | val msg = message { embed(init) } 228 | return editMessage(msg).complete() 229 | } 230 | 231 | 232 | infix fun Message.editAsync(init: MessageBuilder.() -> Unit): RestPromise { 233 | val msg = message(init = init) 234 | return editMessage(msg).promise() 235 | } 236 | 237 | infix fun Message.editAsync(message: KMessage): RestPromise { 238 | require(message.sendable) { 239 | "Cannot send empty message!" 240 | } 241 | 242 | val (content, tts, embed) = message 243 | return editAsync { 244 | if (content !== null) 245 | this += content 246 | if (embed !== null) 247 | this.setEmbed(embed) 248 | this.setTTS(tts) 249 | } 250 | } 251 | 252 | infix fun Message.editTextAsync(lazyContent: () -> Any): RestPromise { 253 | return editMessage(lazyContent().toString()).promise() 254 | } 255 | 256 | infix fun Message.editEmbedAsync(init: KEmbedBuilder.() -> Unit): RestPromise { 257 | val msg = message { embed(init) } 258 | return editMessage(msg).promise() 259 | } 260 | 261 | data class KMessage( 262 | val content: String? = null, 263 | val tts: Boolean = false, 264 | val embed: MessageEmbed? = null 265 | ) { 266 | internal val sendable: Boolean 267 | get() = content?.isNotEmpty() ?: false || embed !== null 268 | } 269 | 270 | /** 271 | * Splits the rawContent of this message into 272 | * the provided slice amount, use `<= 0` amount to slice all. 273 | * 274 | * Using `\s+` as slice regex 275 | */ 276 | operator fun Message.div(upTo: Int): List { 277 | if (upTo < 1) 278 | return rawContent / upTo 279 | 280 | return rawContent / upTo 281 | } 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Florian Spieß 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------