├── .gitignore ├── test.json ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── release.sh ├── release_beta.sh ├── .idea ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml └── copyright │ └── botCommons.xml ├── .editorconfig ├── settings.gradle ├── src ├── test │ └── java │ │ └── me │ │ └── duncte123 │ │ └── botcommons │ │ ├── obj │ │ └── TestConfig.java │ │ ├── ConfigTest.java │ │ ├── EmbedUtilsTest.java │ │ ├── StringUtilsTest.java │ │ └── WebTest.java └── main │ └── java │ └── me │ └── duncte123 │ └── botcommons │ ├── web │ ├── RequestBuilderFunction.java │ ├── PendingRequestFunction.java │ ├── requests │ │ ├── EmptyFromRequestBody.java │ │ ├── IRequestBody.java │ │ ├── PlainTextRequestBody.java │ │ ├── FormRequestBody.java │ │ └── JSONRequestBody.java │ ├── ContentType.java │ ├── WebParserUtils.java │ └── WebUtils.java │ ├── messaging │ ├── MessageConfigDefaults.java │ ├── EmbedUtils.java │ ├── MessageUtils.java │ └── MessageConfig.java │ ├── config │ └── ConfigUtils.java │ ├── JSONHelper.java │ ├── commands │ ├── DefaultCommandContext.java │ └── ICommandContext.java │ ├── text │ └── TextColor.java │ ├── BotCommons.java │ └── StringUtils.java ├── .github └── workflows │ ├── build-and-release.yml │ └── release-beta.yml ├── README.md ├── USAGE.md ├── gradlew.bat ├── gradlew └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .gradle/ 3 | out/ 4 | build/ 5 | -------------------------------------------------------------------------------- /test.json: -------------------------------------------------------------------------------- 1 | { 2 | "val1": "hello", 3 | "val2": "world" 4 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duncte123/botCommons/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | git checkout master 3 | git pull 4 | git merge develop 5 | git push 6 | git checkout develop 7 | -------------------------------------------------------------------------------- /release_beta.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | git checkout beta 3 | git pull 4 | git merge develop 5 | git push 6 | git checkout develop 7 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 4 10 | 11 | [gradlew] 12 | end_of_line = lf -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 | rootProject.name = 'botCommons' 18 | 19 | -------------------------------------------------------------------------------- /.idea/copyright/botCommons.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/test/java/me/duncte123/botcommons/obj/TestConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.obj; 18 | 19 | public class TestConfig { 20 | 21 | public String val1; 22 | public String val2; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/RequestBuilderFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web; 18 | 19 | import okhttp3.Request; 20 | import org.jetbrains.annotations.NotNull; 21 | 22 | @FunctionalInterface 23 | public interface RequestBuilderFunction { 24 | @NotNull Request.Builder apply(@NotNull Request.Builder builder); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/PendingRequestFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web; 18 | 19 | import com.github.natanbc.reliqua.util.PendingRequestBuilder; 20 | import org.jetbrains.annotations.NotNull; 21 | 22 | @FunctionalInterface 23 | public interface PendingRequestFunction { 24 | @NotNull PendingRequestBuilder apply(@NotNull PendingRequestBuilder builder); 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/build-and-release.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: release-botcommons 5 | 6 | on: 7 | push: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | 14 | concurrency: 15 | group: ${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Set up java 23 | uses: actions/setup-java@v3 24 | with: 25 | distribution: 'zulu' 26 | java-version: 17 27 | - name: Grant execute permission for gradlew 28 | run: chmod +x gradlew 29 | - name: dependencies 30 | run: ./gradlew --no-daemon dependencies 31 | - name: Build and Release with Gradle 32 | env: 33 | USERNAME: ${{ secrets.M2_USER }} 34 | PASSWORD: ${{ secrets.M2_PASS }} 35 | run: ./gradlew --no-daemon publish -x test 36 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/messaging/MessageConfigDefaults.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.messaging; 18 | 19 | import java.util.concurrent.TimeUnit; 20 | import java.util.function.Function; 21 | 22 | public class MessageConfigDefaults { 23 | public static final Function DELETE_MESSAGE_AFTER_SECONDS = (secs) -> new MessageConfig.Builder().setSuccessAction( 24 | (message) -> message.delete() 25 | .reason("automatic remove") 26 | .queueAfter(secs, TimeUnit.SECONDS) 27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/requests/EmptyFromRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web.requests; 18 | 19 | import me.duncte123.botcommons.web.ContentType; 20 | import okhttp3.RequestBody; 21 | import org.jetbrains.annotations.NotNull; 22 | 23 | public class EmptyFromRequestBody implements IRequestBody { 24 | @Override 25 | public @NotNull ContentType getContentType() { 26 | return ContentType.URLENCODED; 27 | } 28 | 29 | @Override 30 | public @NotNull RequestBody toRequestBody() { 31 | return RequestBody.create(new byte[0]); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/config/ConfigUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.config; 18 | 19 | import me.duncte123.botcommons.JSONHelper; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | 24 | public class ConfigUtils { 25 | 26 | public static T loadFromFile(String fileName, Class classOfT) throws IOException { 27 | return loadFromFile(new File(fileName), classOfT); 28 | } 29 | 30 | public static T loadFromFile(File file, Class classOfT) throws IOException { 31 | return JSONHelper.createObjectMapper().readValue(file, classOfT); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/release-beta.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: release-botcommons-beta 5 | 6 | on: 7 | push: 8 | branches: 9 | - beta 10 | 11 | jobs: 12 | build: 13 | 14 | concurrency: 15 | group: ${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Set up java 23 | uses: actions/setup-java@v3 24 | with: 25 | distribution: 'zulu' 26 | java-version: 17 27 | - name: Grant execute permission for gradlew 28 | run: chmod +x gradlew 29 | - name: dependencies 30 | run: ./gradlew --no-daemon dependencies 31 | - name: Build and Release with Gradle 32 | env: 33 | USERNAME: ${{ secrets.M2_USER }} 34 | PASSWORD: ${{ secrets.M2_PASS }} 35 | VERSION_PREFIX: beta_ 36 | DEPLOY_PATH: snapshots 37 | run: ./gradlew --no-daemon publish -x test 38 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/requests/IRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web.requests; 18 | 19 | import me.duncte123.botcommons.web.ContentType; 20 | import okhttp3.MediaType; 21 | import okhttp3.RequestBody; 22 | import org.jetbrains.annotations.NotNull; 23 | import org.jetbrains.annotations.Nullable; 24 | 25 | public interface IRequestBody { 26 | 27 | @NotNull 28 | ContentType getContentType(); 29 | 30 | @NotNull 31 | RequestBody toRequestBody(); 32 | 33 | @Nullable 34 | default MediaType getMediaType() { 35 | return MediaType.parse(getContentType().getType()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/JSONHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import com.fasterxml.jackson.core.JsonParser; 20 | import com.fasterxml.jackson.databind.DeserializationFeature; 21 | import com.fasterxml.jackson.databind.ObjectMapper; 22 | 23 | public class JSONHelper { 24 | public static ObjectMapper createObjectMapper() { 25 | final ObjectMapper mapper = new ObjectMapper(); 26 | 27 | mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 28 | mapper.enable(JsonParser.Feature.ALLOW_COMMENTS); 29 | mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES); 30 | 31 | return mapper; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/ContentType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web; 18 | 19 | import okhttp3.MediaType; 20 | 21 | public enum ContentType { 22 | JSON("application/json"), 23 | XML("application/xml"), 24 | URLENCODED("application/x-www-form-urlencoded"), 25 | TEXT_PLAIN("text/plain"), 26 | TEXT_HTML("text/html"), 27 | OCTET_STREAM("application/octet-stream"), 28 | ANY("*/*"); 29 | 30 | private final String type; 31 | 32 | ContentType(String type) { 33 | this.type = type; 34 | } 35 | 36 | public String getType() { 37 | return type; 38 | } 39 | 40 | public MediaType toMediaType() { 41 | return MediaType.parse(type); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/me/duncte123/botcommons/ConfigTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import me.duncte123.botcommons.config.ConfigUtils; 20 | import me.duncte123.botcommons.obj.TestConfig; 21 | import org.junit.Test; 22 | 23 | import java.io.IOException; 24 | 25 | import static junit.framework.TestCase.assertEquals; 26 | 27 | public class ConfigTest { 28 | 29 | @Test 30 | public void testConfigV2() { 31 | try { 32 | TestConfig config = ConfigUtils.loadFromFile("test.json", TestConfig.class); 33 | assertEquals(config.val1, "hello"); 34 | assertEquals(config.val2, "world"); 35 | } catch (IOException e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/commands/DefaultCommandContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.commands; 18 | 19 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 20 | import net.dv8tion.jda.internal.utils.Checks; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * Provides a basic command context that should be sufficient for most bots 26 | */ 27 | public class DefaultCommandContext implements ICommandContext { 28 | private final MessageReceivedEvent event; 29 | private final List args; 30 | 31 | public DefaultCommandContext(List args, MessageReceivedEvent event) { 32 | Checks.notNull(event, "event"); 33 | Checks.notNull(args, "args"); 34 | 35 | this.args = args; 36 | this.event = event; 37 | } 38 | 39 | public List getArgs() { 40 | return this.args; 41 | } 42 | 43 | @Override 44 | public MessageReceivedEvent getEvent() { 45 | return this.event; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/requests/PlainTextRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web.requests; 18 | 19 | import me.duncte123.botcommons.web.ContentType; 20 | import okhttp3.RequestBody; 21 | import org.jetbrains.annotations.NotNull; 22 | 23 | public class PlainTextRequestBody implements IRequestBody { 24 | private final StringBuilder body = new StringBuilder(); 25 | 26 | @Override 27 | public @NotNull ContentType getContentType() { 28 | return ContentType.TEXT_PLAIN; 29 | } 30 | 31 | public PlainTextRequestBody setContent(@NotNull String content) { 32 | this.body.setLength(0); 33 | this.body.append(content); 34 | 35 | return this; 36 | } 37 | 38 | public PlainTextRequestBody appendContent(@NotNull String content) { 39 | this.body.append(content); 40 | 41 | return this; 42 | } 43 | 44 | public StringBuilder getBuilder() { 45 | return body; 46 | } 47 | 48 | @Override 49 | public @NotNull RequestBody toRequestBody() { 50 | return RequestBody.create(this.body.toString().getBytes()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/requests/FormRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web.requests; 18 | 19 | import me.duncte123.botcommons.web.ContentType; 20 | import okhttp3.FormBody; 21 | import okhttp3.RequestBody; 22 | import org.jetbrains.annotations.NotNull; 23 | 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | public class FormRequestBody implements IRequestBody { 28 | private final Map params = new HashMap<>(); 29 | 30 | public FormRequestBody append(@NotNull String key, @NotNull String value) { 31 | this.params.put(key, value); 32 | return this; 33 | } 34 | 35 | @Override 36 | public @NotNull ContentType getContentType() { 37 | return ContentType.URLENCODED; 38 | } 39 | 40 | @Override 41 | public @NotNull RequestBody toRequestBody() { 42 | // this builder has a weird impl so we can't reuse it (and we probably shouldn't) 43 | final FormBody.Builder builder = new FormBody.Builder(); 44 | 45 | // Add all the params to the builder 46 | this.params.forEach(builder::add); 47 | 48 | return builder.build(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BotCommons [![BuildStatus][circleImage]][circleLink] 2 | A set of tools for the [JDA] library 3 | 4 | 5 | ## Adding to your project 6 | The current latest version is: [ ![version][] ][download] 7 | 8 | ## Usage 9 | 10 | Usage instructions can be found [here][usage] with some examples in the [tests folder](src/test/java/me/duncte123/botcommons) 11 | 12 | ## Bot not shutting down? 13 | A shutdown method was created in the `BotCommons` class.
14 | This method also accepts your JDA or ShardManager instance for killing the threads that OkHttp created, because of these running threads your bot will not shut down. 15 | 16 | 17 | #### With gradle 18 | [ ![version][] ][download] 19 | 20 | ```GRADLE 21 | repositories { 22 | maven { 23 | name 'm2-duncte123' 24 | url 'https://m2.duncte123.dev/releases' 25 | } 26 | } 27 | 28 | dependencies { 29 | implementation group: 'me.duncte123', name: 'botCommons', version: '[VERSION]' 30 | } 31 | ``` 32 | 33 | #### With maven 34 | 35 | ```XML 36 | 37 | m2-duncte123 38 | m2-duncte123 39 | https://m2.duncte123.dev/releases 40 | 41 | 42 | 43 | me.duncte123 44 | botCommons 45 | [VERSION] 46 | 47 | ``` 48 | 49 | Make sure to replace `[VERSION]` with the version listed above. 50 | 51 | [JDA]: https://github.com/DV8FromTheWorld/JDA 52 | [version]: https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Fm2.duncte123.dev%2Freleases%2Fme%2Fduncte123%2FbotCommons%2Fmaven-metadata.xml 53 | [download]: https://m2.duncte123.dev/#/releases/me/duncte123/botCommons 54 | [usage]: USAGE.md 55 | [circleLink]: https://github.com/duncte123/botCommons 56 | [circleImage]: https://github.com/duncte123/botCommons/workflows/release-botcommons/badge.svg 57 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/text/TextColor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.text; 18 | 19 | /** 20 | * Class that holds color values that can be printed in terminals 21 | */ 22 | @SuppressWarnings("unused") 23 | public class TextColor { 24 | 25 | public static final String RESET = "\u001B[0m"; 26 | public static final String BLACK = "\u001B[30m"; 27 | public static final String RED = "\u001B[31m"; 28 | public static final String GREEN = "\u001B[32m"; 29 | public static final String YELLOW = "\u001B[33m"; 30 | public static final String BLUE = "\u001B[34m"; 31 | public static final String PURPLE = "\u001B[35m"; 32 | public static final String CYAN = "\u001B[36m"; 33 | public static final String WHITE = "\u001B[37m"; 34 | public static final String ORANGE = "\u001B[38;2;255;140;0m"; 35 | 36 | public static final String BLACK_BACKGROUND = "\u001B[40m"; 37 | public static final String RED_BACKGROUND = "\u001B[41m"; 38 | public static final String GREEN_BACKGROUND = "\u001B[42m"; 39 | public static final String YELLOW_BACKGROUND = "\u001B[43m"; 40 | public static final String BLUE_BACKGROUND = "\u001B[44m"; 41 | public static final String PURPLE_BACKGROUND = "\u001B[45m"; 42 | public static final String CYAN_BACKGROUND = "\u001B[46m"; 43 | public static final String WHITE_BACKGROUND = "\u001B[47m"; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /src/test/java/me/duncte123/botcommons/EmbedUtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import me.duncte123.botcommons.messaging.EmbedUtils; 20 | import net.dv8tion.jda.api.EmbedBuilder; 21 | import net.dv8tion.jda.api.entities.MessageEmbed; 22 | import net.dv8tion.jda.api.entities.Role; 23 | import org.junit.Test; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | public class EmbedUtilsTest { 28 | 29 | @Test 30 | public void testCanSetEmbedSupplier() { 31 | 32 | EmbedUtils.setEmbedBuilder( 33 | () -> new EmbedBuilder().setAuthor("test") 34 | ); 35 | 36 | MessageEmbed embedWithCustomAuthor = EmbedUtils.getDefaultEmbed() 37 | .setAuthor("Kaas").setDescription("Hello world2").build(); 38 | 39 | MessageEmbed normalEmbed = EmbedUtils.embedMessage("Hello World").build(); 40 | 41 | assertEquals("Kaas", embedWithCustomAuthor.getAuthor().getName()); 42 | assertEquals("test", normalEmbed.getAuthor().getName()); 43 | } 44 | 45 | 46 | @Test 47 | public void testCanSetCustomColors() { 48 | int color = 0xFF00FF; 49 | 50 | EmbedUtils.setEmbedColorSupplier((guildId) -> color); 51 | 52 | MessageEmbed embed = EmbedUtils.getDefaultEmbed(3L).build(); 53 | 54 | assertEquals(color, embed.getColorRaw()); 55 | } 56 | 57 | @Test 58 | public void testEmbedColorDefaultsWhenNotSet() { 59 | MessageEmbed embed = EmbedUtils.getDefaultEmbed(3L).build(); 60 | 61 | assertEquals(Role.DEFAULT_COLOR_RAW, embed.getColorRaw()); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/BotCommons.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import me.duncte123.botcommons.web.WebUtils; 20 | import net.dv8tion.jda.api.JDA; 21 | import net.dv8tion.jda.api.sharding.ShardManager; 22 | 23 | public class BotCommons { 24 | 25 | public static final String VERSION = "@version@"; 26 | 27 | /** 28 | * Kills all the threads that BotCommons uses internally, allowing your bot to shut own without using System.exit 29 | * 30 | * @param manager Your {@link ShardManager ShardManager} instance for killing the threads that JDA does not shut down and keep your bot up 31 | */ 32 | public static void shutdown(ShardManager manager) { 33 | manager.shutdown(); 34 | manager.getShardCache().forEach((jda) -> { 35 | jda.getHttpClient().connectionPool().evictAll(); 36 | jda.getHttpClient().dispatcher().executorService().shutdown(); 37 | }); 38 | shutdown(); 39 | } 40 | 41 | /** 42 | * Kills all the threads that BotCommons uses internally, allowing your bot to shut own without using System.exit 43 | * 44 | * @param jda Your {@link JDA JDA} instance for killing the threads that JDA does not shut down and keep your bot up 45 | */ 46 | public static void shutdown(JDA jda) { 47 | jda.shutdown(); 48 | jda.getHttpClient().connectionPool().evictAll(); 49 | jda.getHttpClient().dispatcher().executorService().shutdown(); 50 | shutdown(); 51 | } 52 | 53 | /** 54 | * Kills all the threads that BotCommons uses internally, allowing your bot to shut own without using System.exit 55 | */ 56 | public static void shutdown() { 57 | try { 58 | WebUtils.ins.shutdown(); 59 | } catch (Exception e) { 60 | e.printStackTrace(); // should never happen but just in case 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/me/duncte123/botcommons/StringUtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import org.junit.Test; 20 | 21 | import static org.junit.Assert.*; 22 | 23 | public class StringUtilsTest { 24 | 25 | @Test 26 | public void testReplaceLastReplacesCorrectly() { 27 | String input = "this , that"; 28 | String expected = "this and that"; 29 | 30 | String result = StringUtils.replaceLast(input, ",", "and"); 31 | 32 | assertEquals(expected, result); 33 | } 34 | 35 | @Test 36 | public void testReplaceLastDoesNothingWhenSearchIsNotPresent() { 37 | String input = "this | that"; 38 | String expected = "this and that"; 39 | 40 | String result = StringUtils.replaceLast(input, ",", "and"); 41 | 42 | assertEquals(input, result); 43 | assertNotEquals(expected, result); 44 | } 45 | 46 | @Test(expected = IllegalArgumentException.class) 47 | public void testReplaceLastThrowsWhenArgumentsAreEmpty() { 48 | StringUtils.replaceLast("", ",", "and"); 49 | } 50 | 51 | @Test(expected = IllegalArgumentException.class) 52 | public void testReplaceLastThrowsWhenArgumentsAreNull() { 53 | StringUtils.replaceLast("hello world", null, "and"); 54 | } 55 | 56 | @Test 57 | public void testNormalStringAbbreviations() { 58 | String res1 = StringUtils.abbreviate("Hello world, this is a very long string", 10); 59 | String res2 = StringUtils.abbreviate("Hello", 10); 60 | 61 | assertEquals("Hello w...", res1); 62 | assertEquals("Hello", res2); 63 | } 64 | 65 | @Test(expected = IllegalArgumentException.class) 66 | public void testFailingStringAbbreviations() { 67 | StringUtils.abbreviate("", 10); 68 | StringUtils.abbreviate(null, 10); 69 | StringUtils.abbreviate("bla bla bla", 0); 70 | StringUtils.abbreviate("bla bla bla", -1); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /USAGE.md: -------------------------------------------------------------------------------- 1 | ## Usage instructions 2 | 3 | ### EmbedUtils 4 | 5 | Setting the default embed builder: 6 | ```java 7 | import me.duncte123.botcommons.messaging.EmbedUtils; 8 | import net.dv8tion.jda.api.EmbedBuilder; 9 | 10 | class SettingBuilderExample { 11 | public void setBuilderExample() { 12 | EmbedUtils.setEmbedBuilder( 13 | () -> new EmbedBuilder() 14 | .setFooter("Default footer that is present on all embeds") 15 | ); 16 | } 17 | } 18 | ``` 19 | 20 | Creating an embed: 21 | ```java 22 | import me.duncte123.botcommons.messaging.EmbedUtils; 23 | import net.dv8tion.jda.core.entities.MessageEmbed; 24 | import net.dv8tion.jda.core.entities.TextChannel; 25 | 26 | class SendingMessageExample { 27 | public void sendMessageExample(TextChannel channel) { 28 | MessageEmbed embed = EmbedUtils.embedMessage("My message here").build(); 29 | 30 | channel.sendMessage(embed).queue(); 31 | } 32 | } 33 | ``` 34 | 35 | Creating an embed with image: 36 | ```java 37 | import me.duncte123.botcommons.messaging.EmbedUtils; 38 | import net.dv8tion.jda.core.entities.MessageEmbed; 39 | import net.dv8tion.jda.core.entities.TextChannel; 40 | 41 | class SendingMessageExample { 42 | public void sendMessageExample(TextChannel channel) { 43 | String url = "https://cdn.duncte123.me/AN-wr625PaolD"; 44 | MessageEmbed embed = EmbedUtils.embedImage(url).build(); 45 | 46 | channel.sendMessage(embed).queue(); 47 | } 48 | } 49 | ``` 50 | 51 | ### WebUtils 52 | 53 | ```java 54 | import me.duncte123.botcommons.web.WebUtils; 55 | 56 | class WebUtilsJsonExample { 57 | public void jsonExample() { 58 | WebUtils.setUserAgent("MyApp/1.0"); 59 | 60 | WebUtils.ins.getJSONObject("https://apis.duncte123.me/user-agent").async( 61 | (json) -> System.out.println(json.get("data").get("user-agent").asText()) // Expected output: MyApp/1.0 62 | ); 63 | } 64 | } 65 | ``` 66 | 67 | ```java 68 | import me.duncte123.botcommons.web.WebUtils; 69 | import me.duncte123.botcommons.web.requests.JSONRequestBody; 70 | import net.dv8tion.jda.api.utils.data.DataObject; 71 | import net.dv8tion.jda.api.entities.MessageEmbed; 72 | import net.dv8tion.jda.api.EmbedBuilder; 73 | 74 | class WebUtilsJsonExample { 75 | public void jsonExample() { 76 | WebUtils.setUserAgent("MyApp/1.0"); 77 | 78 | MessageEmbed embed = new EmbedBuilder().build(); 79 | DataObject data = embed.toData(); 80 | // Available bodies are EmptyFromRequestBody, FromRequestBody, JSONRequestBody, PlainTextRequestBody 81 | // Or use the IRequestBody interface to write your own 82 | JSONRequestBody body = JSONRequestBody.fromDataObject(data); 83 | 84 | WebUtils.ins.postRequest("https://httpbin.org/post", body).async( 85 | (json) -> System.out.println(json) // Do something with the result 86 | ); 87 | } 88 | } 89 | ``` 90 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/requests/JSONRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web.requests; 18 | 19 | import com.fasterxml.jackson.core.JsonProcessingException; 20 | import com.fasterxml.jackson.databind.JsonNode; 21 | import com.fasterxml.jackson.databind.ObjectMapper; 22 | import me.duncte123.botcommons.JSONHelper; 23 | import me.duncte123.botcommons.web.ContentType; 24 | import net.dv8tion.jda.api.utils.data.DataArray; 25 | import net.dv8tion.jda.api.utils.data.DataObject; 26 | import okhttp3.RequestBody; 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | import java.io.IOException; 30 | 31 | public class JSONRequestBody implements IRequestBody { 32 | 33 | private final byte[] json; 34 | 35 | private JSONRequestBody(byte[] json) { 36 | this.json = json; 37 | } 38 | 39 | public static JSONRequestBody fromDataObject(@NotNull DataObject data) { 40 | return new JSONRequestBody(data.toString().getBytes()); 41 | } 42 | 43 | public static JSONRequestBody fromDataArray(@NotNull DataArray data) { 44 | return new JSONRequestBody(data.toString().getBytes()); 45 | } 46 | 47 | public static JSONRequestBody fromJSONObject(@NotNull org.json.JSONObject jsonObject) { 48 | return new JSONRequestBody(jsonObject.toString().getBytes()); 49 | } 50 | 51 | public static JSONRequestBody fromJSONArray(@NotNull org.json.JSONArray jsonObject) { 52 | return new JSONRequestBody(jsonObject.toString().getBytes()); 53 | } 54 | 55 | public static JSONRequestBody fromJackson(@NotNull JsonNode jsonNode) throws JsonProcessingException { 56 | return new JSONRequestBody(JSONHelper.createObjectMapper().writeValueAsBytes(jsonNode)); 57 | } 58 | 59 | public static JSONRequestBody fromString(@NotNull String json) throws IOException { 60 | final ObjectMapper mapper = JSONHelper.createObjectMapper(); 61 | 62 | return new JSONRequestBody(mapper.writeValueAsBytes(mapper.readTree(json))); 63 | } 64 | 65 | @Override 66 | public @NotNull ContentType getContentType() { 67 | return ContentType.JSON; 68 | } 69 | 70 | @Override 71 | public @NotNull RequestBody toRequestBody() { 72 | return RequestBody.create(json); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/StringUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import net.dv8tion.jda.internal.utils.Checks; 20 | 21 | public class StringUtils { 22 | 23 | /** 24 | * Replaces the last thing in a string 25 | * 26 | * @param text 27 | * the text to replace 28 | * @param search 29 | * The string to search for 30 | * @param replacement 31 | * what to replace it with 32 | * 33 | * @return the replaced string 34 | * 35 | * @throws IllegalArgumentException 36 | * when text or search are blank or when any of the arguments are null 37 | */ 38 | public static String replaceLast(String text, String search, String replacement) { 39 | Checks.notBlank(text, "text"); 40 | Checks.notBlank(search, "search"); 41 | Checks.notNull(replacement, "replacement"); 42 | 43 | final int index = text.lastIndexOf(search); 44 | 45 | // Search not found 46 | if (index == -1) { 47 | return text; 48 | } 49 | 50 | final String firstPart = text.substring(0, index); 51 | final String lastPart = text.substring(index + search.length()); 52 | 53 | return firstPart + replacement + lastPart; 54 | } 55 | 56 | /** 57 | * Abbreviates the string to your desired length 58 | * 59 | * @param string 60 | * The string to abbreviate 61 | * @param maxLength 62 | * the maximum length of the returned string 63 | * 64 | * @return The abbreviated string 65 | * 66 | * @throws IllegalArgumentException 67 | * when the string is blank or null or when maxLength is less than 0 68 | */ 69 | public static String abbreviate(String string, int maxLength) { 70 | Checks.notNull(string, "string"); 71 | 72 | if (string.isEmpty()) { 73 | return ""; 74 | } 75 | 76 | Checks.positive(maxLength, "maxLength"); 77 | 78 | final String marker = "..."; 79 | final int markerLength = marker.length(); 80 | 81 | if (string.length() < maxLength - markerLength) { 82 | return string; 83 | } 84 | 85 | return string.substring(0, maxLength - markerLength) + marker; 86 | } 87 | 88 | /** 89 | * Capitalizes a string (this is NOT the same as String#toUpperCase) 90 | * 91 | * @param str 92 | * the string to capitalize 93 | * 94 | * @return the capitalized string 95 | */ 96 | public static String capitalizeFully(String str) { 97 | Checks.notBlank(str, "str"); 98 | 99 | final String[] words = str.toLowerCase().split("\\s+"); 100 | final StringBuilder builder = new StringBuilder(); 101 | 102 | for (String word : words) { 103 | builder.append(Character.toUpperCase(word.charAt(0))) 104 | .append(word.substring(1)); 105 | } 106 | 107 | return builder.toString(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/WebParserUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web; 18 | 19 | import com.fasterxml.jackson.databind.JsonNode; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.node.ObjectNode; 22 | import com.github.natanbc.reliqua.request.RequestContext; 23 | import com.github.natanbc.reliqua.request.RequestException; 24 | import me.duncte123.botcommons.JSONHelper; 25 | import okhttp3.Response; 26 | import okhttp3.ResponseBody; 27 | 28 | import javax.annotation.Nullable; 29 | import java.io.IOException; 30 | import java.io.InputStream; 31 | import java.util.zip.GZIPInputStream; 32 | import java.util.zip.InflaterInputStream; 33 | 34 | public class WebParserUtils { 35 | // Only null when invalid json is found 36 | @Nullable 37 | public static ObjectNode toJSONObject(Response response) throws IOException { 38 | return toJSONObject(response, JSONHelper.createObjectMapper()); 39 | } 40 | 41 | // Only null when invalid json is found 42 | @Nullable 43 | public static ObjectNode toJSONObject(Response response, ObjectMapper mapper) throws IOException { 44 | return (ObjectNode) mapper.readTree(getInputStream(response)); 45 | } 46 | 47 | public static InputStream getInputStream(Response response) { 48 | final ResponseBody body = response.body(); 49 | 50 | if (body == null) { 51 | throw new IllegalStateException("Body should never be null"); 52 | } 53 | 54 | final String encoding = response.header("Content-Encoding"); 55 | 56 | if (encoding != null) { 57 | switch (encoding.toLowerCase()) { 58 | case "gzip": 59 | try { 60 | return new GZIPInputStream(body.byteStream()); 61 | } catch (IOException e) { 62 | throw new IllegalStateException("Received Content-Encoding header of gzip, but data is not valid gzip", e); 63 | } 64 | case "deflate": 65 | return new InflaterInputStream(body.byteStream()); 66 | } 67 | } 68 | 69 | return body.byteStream(); 70 | } 71 | 72 | public static void handleError(RequestContext context) { 73 | final Response response = context.getResponse(); 74 | final ResponseBody body = response.body(); 75 | 76 | if (body == null) { 77 | context.getErrorConsumer().accept(new RequestException("Unexpected status code " + response.code() + " (No body)", context.getCallStack())); 78 | return; 79 | } 80 | 81 | JsonNode json = null; 82 | 83 | try { 84 | json = toJSONObject(response); 85 | } catch (Exception ignored) { 86 | } 87 | 88 | if (json != null) { 89 | context.getErrorConsumer().accept(new RequestException("Unexpected status code " + response.code() + ": " + json, context.getCallStack())); 90 | } else { 91 | context.getErrorConsumer().accept(new RequestException("Unexpected status code " + response.code(), context.getCallStack())); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/commands/ICommandContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.commands; 18 | 19 | import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; 20 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 21 | import net.dv8tion.jda.api.sharding.ShardManager; 22 | import net.dv8tion.jda.api.JDA; 23 | import net.dv8tion.jda.api.entities.*; 24 | 25 | /** 26 | * Dummy class that holds the basics for a command context 27 | */ 28 | public interface ICommandContext { 29 | 30 | /** 31 | * Returns the {@link net.dv8tion.jda.api.entities.Guild} for the current command/event 32 | * 33 | * @return the {@link net.dv8tion.jda.api.entities.Guild} for this command/event 34 | */ 35 | default Guild getGuild() { 36 | return this.getEvent().getGuild(); 37 | } 38 | 39 | /** 40 | * Returns true if this message event came from a guild 41 | * 42 | * @return true if this message event came from a guild 43 | */ 44 | default boolean isFromGuild() { 45 | return this.getEvent().isFromGuild(); 46 | } 47 | 48 | /** 49 | * Returns the {@link net.dv8tion.jda.api.events.message.MessageReceivedEvent message event} that was received for this instance 50 | * 51 | * @return the {@link net.dv8tion.jda.api.events.message.MessageReceivedEvent message event} that was received for this instance 52 | */ 53 | MessageReceivedEvent getEvent(); 54 | 55 | /** 56 | * Returns the {@link net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion channel} that the message for this event was sent in 57 | * 58 | * @return the {@link net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion channel} that the message for this event was sent in 59 | */ 60 | default MessageChannelUnion getChannel() { 61 | return this.getEvent().getChannel(); 62 | } 63 | 64 | /** 65 | * Returns the {@link net.dv8tion.jda.api.entities.Message message} that triggered this event 66 | * 67 | * @return the {@link net.dv8tion.jda.api.entities.Message message} that triggered this event 68 | */ 69 | default Message getMessage() { 70 | return this.getEvent().getMessage(); 71 | } 72 | 73 | /** 74 | * Returns the {@link net.dv8tion.jda.api.entities.User author} of the message as user 75 | * 76 | * @return the {@link net.dv8tion.jda.api.entities.User author} of the message as user 77 | */ 78 | default User getAuthor() { 79 | return this.getEvent().getAuthor(); 80 | } 81 | /** 82 | * Returns the {@link net.dv8tion.jda.api.entities.Member author} of the message as member 83 | * 84 | * @return the {@link net.dv8tion.jda.api.entities.Member author} of the message as member 85 | */ 86 | default Member getMember() { 87 | return this.getEvent().getMember(); 88 | } 89 | 90 | /** 91 | * Returns the current {@link net.dv8tion.jda.api.JDA jda} instance 92 | * 93 | * @return the current {@link net.dv8tion.jda.api.JDA jda} instance 94 | */ 95 | default JDA getJDA() { 96 | return this.getEvent().getJDA(); 97 | } 98 | 99 | /** 100 | * Returns the current {@link net.dv8tion.jda.api.sharding.ShardManager} instance 101 | * 102 | * @return the current {@link net.dv8tion.jda.api.sharding.ShardManager} instance 103 | */ 104 | default ShardManager getShardManager() { 105 | return this.getJDA().getShardManager(); 106 | } 107 | 108 | /** 109 | * Returns the {@link net.dv8tion.jda.api.entities.User user} for the currently logged in account 110 | * 111 | * @return the {@link net.dv8tion.jda.api.entities.User user} for the currently logged in account 112 | */ 113 | default User getSelfUser() { 114 | return this.getJDA().getSelfUser(); 115 | } 116 | 117 | /** 118 | * Returns the {@link net.dv8tion.jda.api.entities.Member member} in the guild for the currently logged in account 119 | * 120 | * @return the {@link net.dv8tion.jda.api.entities.Member member} in the guild for the currently logged in account 121 | */ 122 | default Member getSelfMember() { 123 | return this.getGuild().getSelfMember(); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/test/java/me/duncte123/botcommons/WebTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons; 18 | 19 | import com.fasterxml.jackson.core.JsonProcessingException; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.node.ObjectNode; 22 | import com.github.natanbc.reliqua.request.PendingRequest; 23 | import com.github.natanbc.reliqua.util.StatusCodeValidator; 24 | import me.duncte123.botcommons.web.WebUtils; 25 | import okhttp3.HttpUrl; 26 | import okhttp3.mockwebserver.MockResponse; 27 | import okhttp3.mockwebserver.MockWebServer; 28 | import org.junit.Test; 29 | 30 | import static org.junit.Assert.assertEquals; 31 | import static org.junit.Assert.assertNotNull; 32 | 33 | public class WebTest { 34 | 35 | @Test 36 | public void testWebUtilsCanSetUserAgentAndWillSendCorrectUserAgent() throws JsonProcessingException { 37 | String userAgent = "Mozilla/5.0 botCommons test"; 38 | ObjectMapper mapper = new ObjectMapper(); 39 | ObjectNode body = mapper.createObjectNode(); 40 | body.set( 41 | "data", 42 | mapper.createObjectNode().put("user-agent", userAgent) 43 | ); 44 | String parsed = mapper.writeValueAsString(body); 45 | 46 | MockWebServer server = new MockWebServer(); 47 | server.enqueue(new MockResponse() 48 | .addHeader("Content-Type", "application/json; charset=utf-8") 49 | .setBody(parsed) 50 | ); 51 | 52 | WebUtils.setUserAgent(userAgent); 53 | 54 | assertEquals(userAgent, WebUtils.getUserAgent()); 55 | 56 | HttpUrl baseUrl = server.url("/user-agent"); 57 | ObjectNode json = WebUtils.ins.getJSONObject(baseUrl.toString()).execute(); 58 | 59 | assertEquals(userAgent, json.get("data").get("user-agent").asText()); 60 | } 61 | 62 | @Test 63 | public void testAsyncWebRequest() throws JsonProcessingException { 64 | ObjectMapper mapper = new ObjectMapper(); 65 | ObjectNode body = mapper.createObjectNode(); 66 | body.set( 67 | "data", 68 | mapper.createObjectNode().put("file", "Hi there") 69 | ); 70 | String parsed = mapper.writeValueAsString(body); 71 | 72 | MockWebServer server = new MockWebServer(); 73 | server.enqueue(new MockResponse() 74 | .addHeader("Content-Type", "application/json; charset=utf-8") 75 | .setBody(parsed) 76 | ); 77 | 78 | HttpUrl baseUrl = server.url("/llama"); 79 | 80 | System.out.println("Before"); 81 | WebUtils.ins.getJSONObject(baseUrl.toString()) 82 | .async(json -> { 83 | assertNotNull(json.get("data").get("file").asText()); 84 | System.out.println("During"); 85 | }); 86 | System.out.println("After"); 87 | } 88 | 89 | @Test 90 | public void testPendingRequestFunction() { // Not that I expect it to go wrong 91 | final PendingRequest pendingRequest = WebUtils.ins.getJSONObject("https://example.com/", 92 | (b) -> b.setStatusCodeValidator(StatusCodeValidator.ACCEPT_2XX) 93 | ); 94 | 95 | assertEquals(StatusCodeValidator.ACCEPT_2XX, pendingRequest.getStatusCodeValidator()); 96 | } 97 | 98 | @Test 99 | public void testRateLimiting() { 100 | MockWebServer server = new MockWebServer(); 101 | server.enqueue(new MockResponse() 102 | .addHeader("Content-Type", "application/json; charset=utf-8") 103 | .addHeader("X-RateLimit-Remaining", 1) 104 | .addHeader("X-RateLimit-Limit", 1) 105 | .addHeader("X-RateLimit-Reset-After", 5) 106 | .setBody("My cool body") 107 | ); 108 | 109 | HttpUrl urlOne = server.url("/bla-request-one"); 110 | final String s1 = WebUtils.ins.getText(urlOne.toString()).execute(); 111 | 112 | System.out.println(s1); 113 | assertEquals("My cool body", s1); 114 | 115 | server.enqueue(new MockResponse() 116 | .addHeader("Content-Type", "application/json; charset=utf-8") 117 | .addHeader("X-RateLimit-Remaining", 1) 118 | .addHeader("X-RateLimit-Limit", 1) 119 | .addHeader("X-RateLimit-Reset-After", 5) 120 | .setBody("My cool body 2") 121 | ); 122 | 123 | final double curr = Math.floor(System.currentTimeMillis() / 1000D); 124 | 125 | final String s2 = WebUtils.ins.getText(urlOne.toString()).execute(); 126 | 127 | System.out.println(s2); 128 | assertEquals("My cool body 2", s2); 129 | 130 | final double now = Math.floor(System.currentTimeMillis() / 1000D); 131 | 132 | // should have waited for 5 seconds 133 | assertEquals(5D, now - curr, 0.5D); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/messaging/EmbedUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.messaging; 18 | 19 | import net.dv8tion.jda.api.EmbedBuilder; 20 | import net.dv8tion.jda.api.entities.MessageEmbed; 21 | import net.dv8tion.jda.api.entities.Role; 22 | import net.dv8tion.jda.internal.utils.Checks; 23 | 24 | import javax.annotation.Nonnull; 25 | import java.util.function.Function; 26 | import java.util.function.Supplier; 27 | 28 | /** 29 | * Util class to help send embeds 30 | */ 31 | public class EmbedUtils { 32 | private static Supplier embedBuilderSupplier = EmbedBuilder::new; 33 | private static int defaultColor = Role.DEFAULT_COLOR_RAW; 34 | static Function embedColorSupplier = (__) -> defaultColor; 35 | 36 | /** 37 | * Sets the embed builder for the util method 38 | * 39 | * @param embedBuilderSupplier 40 | * the default embed layout 41 | */ 42 | public static void setEmbedBuilder(@Nonnull Supplier embedBuilderSupplier) { 43 | Checks.notNull(embedBuilderSupplier, "embedBuilderSupplier"); 44 | 45 | EmbedUtils.embedBuilderSupplier = embedBuilderSupplier; 46 | } 47 | 48 | /** 49 | * Sets the supplier that gets embed colors 50 | * 51 | * @param supplier 52 | * the supplier for getting embed colors, the parameter is the guild id 53 | */ 54 | public static void setEmbedColorSupplier(@Nonnull Function supplier) { 55 | Checks.notNull(supplier, "supplier"); 56 | 57 | EmbedUtils.embedColorSupplier = supplier; 58 | } 59 | 60 | /** 61 | * Gets a color for an id 62 | * 63 | * @param key 64 | * the id to find the color for 65 | * 66 | * @return The color for this key or "0" 67 | */ 68 | public static int getColor(long key) { 69 | return embedColorSupplier.apply(key); 70 | } 71 | 72 | /** 73 | * Gets a color for an id 74 | * 75 | * @param key 76 | * the id to find the color for 77 | * 78 | * @return The color for this key or the default value 79 | * 80 | * @see #setDefaultColor(int) 81 | * @see #getDefaultColor() 82 | */ 83 | public static int getColorOrDefault(long key) { 84 | final int color = getColor(key); 85 | 86 | if (color <= 0) { 87 | return defaultColor; 88 | } 89 | 90 | return color; 91 | } 92 | 93 | /** 94 | * Returns the default color of all embeds 95 | * 96 | * @return the default color of all embeds 97 | */ 98 | public static int getDefaultColor() { 99 | return defaultColor; 100 | } 101 | 102 | /** 103 | * Sets the default color of all embeds 104 | * 105 | * @param defaultColor 106 | * The default color of all embeds 107 | */ 108 | public static void setDefaultColor(int defaultColor) { 109 | EmbedUtils.defaultColor = defaultColor; 110 | } 111 | 112 | /** 113 | * The default way to send a embedded message to the channel with a field in it 114 | * 115 | * @param title 116 | * The title of the field 117 | * @param message 118 | * The message to display 119 | * 120 | * @return The {@link EmbedBuilder} for this action 121 | */ 122 | public static EmbedBuilder embedField(String title, String message) { 123 | return getDefaultEmbed().addField(title, message, false); 124 | } 125 | 126 | /** 127 | * The default way to display a nice embedded message 128 | * 129 | * @param message 130 | * The message to display 131 | * 132 | * @return The {@link EmbedBuilder} for this action 133 | */ 134 | public static EmbedBuilder embedMessage(String message) { 135 | return getDefaultEmbed().setDescription(message); 136 | } 137 | 138 | /** 139 | * The default way to display a nice embedded message 140 | * 141 | * @param message 142 | * The message to display 143 | * @param title 144 | * The title for the embed 145 | * 146 | * @return The {@link EmbedBuilder} for this action 147 | */ 148 | public static EmbedBuilder embedMessageWithTitle(String title, String message) { 149 | return getDefaultEmbed().setTitle(title).setDescription(message); 150 | } 151 | 152 | /** 153 | * The default way to send a embedded image to the channel 154 | * 155 | * @param imageURL 156 | * The url from the image 157 | * 158 | * @return The {@link EmbedBuilder} for this action 159 | */ 160 | public static EmbedBuilder embedImage(String imageURL) { 161 | return getDefaultEmbed().setImage(imageURL); 162 | } 163 | 164 | /** 165 | * Creates an embed that has bot a title and an image 166 | * 167 | * @param title 168 | * The title of the embed 169 | * @param url 170 | * The url that the title links to 171 | * @param image 172 | * The image that the embed shows 173 | * 174 | * @return The {@link EmbedBuilder} for this action 175 | */ 176 | public static EmbedBuilder embedImageWithTitle(String title, String url, String image) { 177 | return getDefaultEmbed().setTitle(title, url).setImage(image); 178 | } 179 | 180 | /** 181 | * Returns the default {@link EmbedBuilder embed} set in {@link #setEmbedBuilder(Supplier)} 182 | * 183 | * @return The default {@link EmbedBuilder embed} set in {@link #setEmbedBuilder(Supplier)} 184 | */ 185 | public static EmbedBuilder getDefaultEmbed() { 186 | return embedBuilderSupplier.get(); 187 | } 188 | 189 | /** 190 | * Returns the default {@link EmbedBuilder embed} set in {@link #setEmbedBuilder(Supplier)} 191 | * 192 | * @param guildId 193 | * The guild id that has a color stored (or the defalt color) 194 | * 195 | * @return The default {@link EmbedBuilder embed} set in {@link #setEmbedBuilder(Supplier)} with the color value set 196 | * in {@link #setEmbedColorSupplier(Function)} 197 | */ 198 | public static EmbedBuilder getDefaultEmbed(long guildId) { 199 | return embedBuilderSupplier.get() 200 | .setColor(getColorOrDefault(guildId)); 201 | } 202 | 203 | /** 204 | * This will convert our embeds for if the bot is not able to send embeds 205 | * 206 | * @param embed 207 | * the {@link MessageEmbed} that we are trying to send 208 | * 209 | * @return the converted embed 210 | */ 211 | static String embedToMessage(MessageEmbed embed) { 212 | final StringBuilder msg = new StringBuilder(); 213 | 214 | if (embed.getAuthor() != null) { 215 | msg.append("***").append(embed.getAuthor().getName()).append("***\n\n"); 216 | } 217 | 218 | if (embed.getDescription() != null) { 219 | msg.append("_").append(embed.getDescription() 220 | // Reformat 221 | .replaceAll("\\[(.+)]\\((.+)\\)", "$1 (Link: $2)") 222 | ).append("_\n\n"); 223 | } 224 | 225 | for (MessageEmbed.Field f : embed.getFields()) { 226 | msg.append("__").append(f.getName()).append("__\n").append( 227 | f.getValue() 228 | // Reformat 229 | .replaceAll("\\[(.+)]\\((.+)\\)", "$1 (Link: $2)") 230 | ).append("\n\n"); 231 | } 232 | 233 | if (embed.getImage() != null) { 234 | msg.append(embed.getImage().getUrl()).append("\n"); 235 | } 236 | 237 | if (embed.getFooter() != null) { 238 | msg.append(embed.getFooter().getText()); 239 | } 240 | 241 | if (embed.getTimestamp() != null) { 242 | msg.append(" | ").append(embed.getTimestamp()); 243 | } 244 | 245 | return msg.toString(); 246 | } 247 | 248 | /*public static Queue embedToCodeBlock(MessageEmbed embed) { 249 | return new MessageBuilder().appendCodeBlock(embedToMessage(embed), "java").buildAll(SplitPolicy.NEWLINE); 250 | }*/ 251 | } 252 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 13 | 14 | 275 | 276 | 278 | 279 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/messaging/MessageUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.messaging; 18 | 19 | import me.duncte123.botcommons.commands.ICommandContext; 20 | import net.dv8tion.jda.api.EmbedBuilder; 21 | import net.dv8tion.jda.api.JDA; 22 | import net.dv8tion.jda.api.Permission; 23 | import net.dv8tion.jda.api.entities.*; 24 | import net.dv8tion.jda.api.entities.channel.ChannelType; 25 | import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; 26 | import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel; 27 | import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; 28 | import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; 29 | import net.dv8tion.jda.api.entities.emoji.Emoji; 30 | import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; 31 | import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; 32 | import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; 33 | import net.dv8tion.jda.api.utils.messages.MessageEditData; 34 | import org.slf4j.Logger; 35 | import org.slf4j.LoggerFactory; 36 | 37 | import javax.annotation.Nonnull; 38 | import javax.annotation.Nullable; 39 | import java.util.List; 40 | import java.util.function.Consumer; 41 | import java.util.stream.Collectors; 42 | 43 | import static me.duncte123.botcommons.messaging.EmbedUtils.embedToMessage; 44 | 45 | @SuppressWarnings({"unused", "WeakerAccess"}) 46 | public class MessageUtils { 47 | private static final Logger LOGGER = LoggerFactory.getLogger(MessageUtils.class); 48 | private static String errorReaction = "❌"; 49 | private static String successReaction = "✅"; 50 | 51 | /** 52 | * Returns the current error reaction 53 | * 54 | * @return The current error reaction 55 | * 56 | * @see #sendError(Message) 57 | */ 58 | public static String getErrorReaction() { 59 | return errorReaction; 60 | } 61 | 62 | /** 63 | * Sets the new error reaction
64 | * Hint: To use a custom emote as reaction use {@link Emoji#getAsReactionCode()} 65 | * 66 | * @param errorReaction 67 | * The new emoji/emote to use for error reactions. 68 | * 69 | * @see #sendError(Message) 70 | */ 71 | public static void setErrorReaction(String errorReaction) { 72 | MessageUtils.errorReaction = errorReaction; 73 | } 74 | 75 | /** 76 | * Returns the current success reaction 77 | * 78 | * @return The current success reaction 79 | * 80 | * @see #sendSuccess(Message) 81 | */ 82 | public static String getSuccessReaction() { 83 | return successReaction; 84 | } 85 | 86 | /** 87 | * Sets the new success reaction.
88 | * Hint: To use a custom emote as reaction use {@link Emoji#getAsReactionCode()} 89 | * 90 | * @param successReaction 91 | * The new emoji/emote to use as success reaction 92 | * 93 | * @see #sendSuccess(Message) 94 | */ 95 | public static void setSuccessReaction(String successReaction) { 96 | MessageUtils.successReaction = successReaction; 97 | } 98 | 99 | /** 100 | * This will react with a ❌ if the user doesn't have permission to run the command 101 | * 102 | * @param message 103 | * the message to add the reaction to 104 | */ 105 | public static void sendError(Message message) { 106 | if (message.getChannelType() == ChannelType.TEXT) { 107 | TextChannel channel = message.getChannel().asTextChannel(); 108 | 109 | if (!channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_HISTORY)) { 110 | return; 111 | } 112 | } 113 | 114 | message.addReaction(Emoji.fromUnicode(errorReaction)).queue(null, (ignored) -> {}); 115 | } 116 | 117 | /** 118 | * This method uses the {@link #sendError(Message)} and {@link #sendMsg(MessageConfig)} methods 119 | * 120 | * @param message 121 | * the {@link Message} for the sendError method 122 | * @param text 123 | * the {@link String} for the sendMsg method 124 | */ 125 | public static void sendErrorWithMessage(Message message, String text) { 126 | sendError(message); 127 | 128 | sendMsg( 129 | new MessageConfig.Builder() 130 | .setChannel(message.getChannel()) 131 | .setMessage(text) 132 | ); 133 | } 134 | 135 | /** 136 | * This will react with a ✅ if the user doesn't have permission to run the command 137 | * 138 | * @param message 139 | * the message to add the reaction to 140 | */ 141 | public static void sendSuccess(Message message) { 142 | if (message.getChannelType() == ChannelType.TEXT) { 143 | final TextChannel channel = message.getChannel().asTextChannel(); 144 | 145 | if (channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_HISTORY)) { 146 | message.addReaction(Emoji.fromUnicode(successReaction)).queue(null, (ignored) -> {}); 147 | } 148 | } 149 | } 150 | 151 | /** 152 | * This method uses the {@link #sendSuccess(Message)} and {@link #sendMsg(MessageConfig)} methods 153 | * 154 | * @param message 155 | * the {@link Message} for the sendSuccess method 156 | * @param text 157 | * the {@link String} for the sendMsg method 158 | */ 159 | public static void sendSuccessWithMessage(Message message, String text) { 160 | sendSuccess(message); 161 | 162 | sendMsg( 163 | new MessageConfig.Builder() 164 | .setChannel(message.getChannel()) 165 | .setMessage(text) 166 | ); 167 | } 168 | 169 | /** 170 | * Shortcut for editing a message that does permission checks for embeds 171 | * 172 | * @param message 173 | * The message to edit 174 | * @param newContent 175 | * The new content of the message 176 | */ 177 | public static void editMsg(Message message, Message newContent) { 178 | if (message == null || newContent == null) return; 179 | if (newContent.getEmbeds().size() > 0) { 180 | if (!message.getGuild().getSelfMember().hasPermission(message.getGuildChannel(), Permission.MESSAGE_EMBED_LINKS)) { 181 | final StringBuilder mb = new StringBuilder() 182 | .append(newContent.getContentRaw()) 183 | .append('\n'); 184 | 185 | 186 | 187 | newContent.getEmbeds().forEach( 188 | messageEmbed -> mb.append(embedToMessage(messageEmbed)) 189 | ); 190 | 191 | message.editMessage(mb.toString()).queue(); 192 | 193 | return; 194 | } 195 | } 196 | 197 | message.editMessage(MessageEditData.fromMessage(newContent)).queue(); 198 | } 199 | 200 | /** 201 | * Shortcut for sending an embed from a command context 202 | * 203 | * @param ctx 204 | * The command context that holds the target channel 205 | * @param embed 206 | * The embed to send to the channel 207 | * 208 | * @see #sendEmbed(ICommandContext, EmbedBuilder, boolean) 209 | */ 210 | public static void sendEmbed(ICommandContext ctx, EmbedBuilder embed) { 211 | sendEmbed(ctx, embed, false); 212 | } 213 | 214 | /** 215 | * Shortcut for sending an embed from a command context 216 | * 217 | * @param ctx 218 | * The command context that has the target channel 219 | * @param embed 220 | * The embed to send to the channel 221 | * @param raw 222 | * {@code true} to skip parsing of the guild-colors and other future items, default value is {@code false} 223 | * 224 | * @see #sendEmbed(ICommandContext, EmbedBuilder) 225 | */ 226 | public static void sendEmbed(ICommandContext ctx, EmbedBuilder embed, boolean raw) { 227 | sendMsg( 228 | MessageConfig.Builder.fromCtx(ctx) 229 | .setEmbeds(raw, embed) 230 | .build() 231 | ); 232 | } 233 | 234 | /** 235 | * Shortcut for sending message from a command context 236 | * 237 | * @param ctx 238 | * The command context that has the target channel 239 | * @param message 240 | * The message to send 241 | */ 242 | public static void sendMsg(ICommandContext ctx, String message) { 243 | sendMsg( 244 | MessageConfig.Builder.fromCtx(ctx) 245 | .setMessage(message) 246 | .build() 247 | ); 248 | } 249 | 250 | /** 251 | * Shortcut for the lazy that don't want to build their config before sending a message, calls {@link 252 | * MessageConfig.Builder#build()} underwater 253 | * 254 | * @param builder 255 | * The config builder to base the message off 256 | */ 257 | public static void sendMsg(MessageConfig.Builder builder) { 258 | sendMsg(builder.build()); 259 | } 260 | 261 | /** 262 | * Sends a message based off the message config 263 | * 264 | * @param config 265 | * The configuration on how to send the message 266 | */ 267 | public static void sendMsg(@Nonnull MessageConfig config) { 268 | final MessageChannel channel = config.getChannel(); 269 | final JDA jda = channel.getJDA(); 270 | // refresh the entity 271 | final MessageChannel channelById = jda.getChannelById(MessageChannel.class, channel.getIdLong()); 272 | 273 | if (channelById == null) { 274 | throw new IllegalArgumentException("Channel does not seem to exist on JDA#getTextChannelById???"); 275 | } 276 | 277 | // we cannot talk here 278 | if (!channelById.canTalk()) { 279 | return; 280 | } 281 | 282 | boolean canReply = true; 283 | final MessageCreateBuilder messageBuilder = config.getMessageBuilder(); 284 | final List embeds = config.getEmbeds(); 285 | 286 | if (channelById instanceof GuildMessageChannel) { 287 | final GuildMessageChannel chan = (GuildMessageChannel) channelById; 288 | final Guild guild = jda.getGuildById(chan.getGuild().getIdLong()); 289 | 290 | if (guild == null) { 291 | throw new IllegalArgumentException("Guild does not seem to exist on JDA#getGuildById???"); 292 | } 293 | 294 | final Member selfMember = guild.getSelfMember(); 295 | 296 | if (!embeds.isEmpty() && selfMember.hasPermission(chan, Permission.MESSAGE_EMBED_LINKS)) { 297 | messageBuilder.setEmbeds( 298 | embeds.stream().map(EmbedBuilder::build).collect(Collectors.toList()) 299 | ); 300 | 301 | // TODO: keep the text transformer? 302 | /*if (guild.getSelfMember().hasPermission(channelById, Permission.MESSAGE_EMBED_LINKS)) { 303 | messageBuilder.setEmbeds( 304 | embeds.stream().map(EmbedBuilder::build).collect(Collectors.toList()) 305 | ); 306 | } else { 307 | messageBuilder.append( 308 | embedToMessage(embeds.get(0).build()) 309 | ); 310 | }*/ 311 | } 312 | 313 | canReply = selfMember.hasPermission(chan, Permission.MESSAGE_HISTORY); 314 | } else { 315 | messageBuilder.setEmbeds( 316 | embeds.stream().map(EmbedBuilder::build).collect(Collectors.toList()) 317 | ); 318 | } 319 | 320 | if (messageBuilder.isEmpty()) { 321 | return; 322 | } 323 | 324 | final Consumer failureAction = config.getFailureAction(); 325 | final Consumer successAction = config.getSuccessAction(); 326 | final Consumer actionConfig = config.getActionConfig(); 327 | final boolean finalCanReply = canReply; // fuck java 8 :( 328 | 329 | // if the message is small enough we can just send it 330 | if (messageBuilder.getContent().length() <= Message.MAX_CONTENT_LENGTH) { 331 | final MessageCreateAction messageAction = channel.sendMessage(messageBuilder.build()); 332 | 333 | if (config.getReplyToId() > 0 && finalCanReply) { 334 | //noinspection ResultOfMethodCallIgnored 335 | messageAction.setMessageReference(config.getReplyToId()) 336 | .mentionRepliedUser(config.isMentionRepliedUser()); 337 | } 338 | 339 | actionConfig.accept(messageAction); 340 | messageAction.queue(successAction, failureAction); 341 | return; 342 | } 343 | 344 | // TODO: 345 | /*List messages = SplitUtil.split( 346 | someLargeString, // input string of arbitrary length 347 | 2000, // the split limit, can be arbitrary (>0) 348 | true, // whether to trim the strings (empty will be discarded) 349 | Strategy.NEWLINE, // split on '\n' characters if possible 350 | Strategy.ANYWHERE // otherwise split on the limit 351 | );*/ 352 | 353 | /*messageBuilder.buildAll(SplitPolicy.SPACE, SplitPolicy.NEWLINE).forEach( 354 | (message) -> { 355 | final MessageCreateAction messageAction = channel.sendMessage(message); 356 | 357 | if (config.getReplyToId() > 0 && finalCanReply) { 358 | //noinspection ResultOfMethodCallIgnored 359 | messageAction.setMessageReference(config.getReplyToId()) 360 | .mentionRepliedUser(config.isMentionRepliedUser()); 361 | } 362 | 363 | actionConfig.accept(messageAction); 364 | messageAction.queue(successAction, failureAction); 365 | } 366 | );*/ 367 | } 368 | } 369 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/web/WebUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.web; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.node.ArrayNode; 21 | import com.fasterxml.jackson.databind.node.ObjectNode; 22 | import com.github.natanbc.reliqua.Reliqua; 23 | import com.github.natanbc.reliqua.request.PendingRequest; 24 | import com.github.natanbc.reliqua.util.PendingRequestBuilder; 25 | import com.github.natanbc.reliqua.util.ResponseMapper; 26 | import me.duncte123.botcommons.BotCommons; 27 | import me.duncte123.botcommons.JSONHelper; 28 | import me.duncte123.botcommons.web.requests.IRequestBody; 29 | import net.dv8tion.jda.internal.utils.IOUtil; 30 | import okhttp3.OkHttpClient; 31 | import okhttp3.Request; 32 | import org.jsoup.Jsoup; 33 | import org.jsoup.nodes.Document; 34 | 35 | import javax.annotation.Nullable; 36 | import java.io.InputStream; 37 | import java.io.UnsupportedEncodingException; 38 | import java.net.URLEncoder; 39 | import java.util.concurrent.TimeUnit; 40 | 41 | @SuppressWarnings({"unused", "WeakerAccess", "ConstantConditions"}) 42 | public final class WebUtils extends Reliqua { 43 | 44 | public static final WebUtils ins = new WebUtils(); 45 | private static String USER_AGENT = "Mozilla/5.0 (compatible; BotCommons/" + BotCommons.VERSION + "; +https://github.com/duncte123/BotCommons;)"; 46 | private final ObjectMapper mapper = JSONHelper.createObjectMapper(); 47 | 48 | private WebUtils() { 49 | super( 50 | new OkHttpClient.Builder() 51 | .connectTimeout(30L, TimeUnit.SECONDS) 52 | .readTimeout(30L, TimeUnit.SECONDS) 53 | .writeTimeout(30L, TimeUnit.SECONDS) 54 | .build(), 55 | null, 56 | true 57 | ); 58 | } 59 | 60 | /** 61 | * Retrieves text from a webpage 62 | * 63 | * @param url 64 | * The url to retrieve the text from 65 | * 66 | * @return A {@link PendingRequest PendingRequest} that is pending execution via {@link PendingRequest#async() 67 | * PendingRequest#async()}, {@link PendingRequest#submit() PendingRequest#submit()} or {@link 68 | * PendingRequest#execute() PendingRequest#execute()} 69 | * 70 | * @see #getText(String, PendingRequestFunction) 71 | * @see #getText(String, PendingRequestFunction, RequestBuilderFunction) 72 | * @see PendingRequest 73 | */ 74 | public PendingRequest getText(String url) { 75 | return getText(url, null); 76 | } 77 | 78 | /** 79 | * Retrieves text from a webpage 80 | * 81 | * @param url 82 | * The url to retrieve the text from 83 | * @param pendingBuilder 84 | * Used {@link PendingRequestBuilder PendingRequestBuilder} to add extra configuration to the {@link 85 | * PendingRequest PendingRequest} returned 86 | * 87 | * @return A {@link PendingRequest PendingRequest} that is pending execution via {@link PendingRequest#async() 88 | * PendingRequest#async()}, {@link PendingRequest#submit() PendingRequest#submit()} or {@link 89 | * PendingRequest#execute() PendingRequest#execute()} 90 | * 91 | * @see #getText(String) 92 | * @see #getText(String, PendingRequestFunction, RequestBuilderFunction) 93 | * @see PendingRequest 94 | */ 95 | public PendingRequest getText(String url, @Nullable PendingRequestFunction pendingBuilder) { 96 | return getText(url, pendingBuilder, null); 97 | } 98 | 99 | 100 | /** 101 | * Retrieves text from a webpage 102 | * 103 | * @param url 104 | * The url to retrieve the text from 105 | * @param pendingBuilder 106 | * Used {@link PendingRequestBuilder PendingRequestBuilder} to add extra configuration to the {@link 107 | * PendingRequest PendingRequest} returned 108 | * @param requestBuilder 109 | * Used to configure the {@link Request Request} before it is send off to the server 110 | * 111 | * @return A {@link PendingRequest PendingRequest} that is pending execution via {@link PendingRequest#async() 112 | * PendingRequest#async()}, {@link PendingRequest#submit() PendingRequest#submit()} or {@link 113 | * PendingRequest#execute() PendingRequest#execute()} 114 | * 115 | * @see #getText(String) 116 | * @see #getText(String, PendingRequestFunction) 117 | * @see PendingRequest 118 | */ 119 | public PendingRequest getText(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 120 | final Request.Builder builder = prepareGet(url); 121 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 122 | 123 | return pendingRequestBuilder.build( 124 | (response) -> response.body().string(), 125 | WebParserUtils::handleError 126 | ); 127 | } 128 | 129 | /** 130 | * 131 | * @param url 132 | * @return 133 | * 134 | * @see #scrapeWebPage(String) 135 | * @see #scrapeWebPage(String, PendingRequestFunction) 136 | * @see #scrapeWebPage(String, PendingRequestFunction, RequestBuilderFunction) 137 | */ 138 | public PendingRequest scrapeWebPage(String url) { 139 | return scrapeWebPage(url, null); 140 | } 141 | 142 | /** 143 | * 144 | * @param url 145 | * @param pendingBuilder 146 | * @return 147 | * 148 | * @see #scrapeWebPage(String) 149 | * @see #scrapeWebPage(String, PendingRequestFunction) 150 | * @see #scrapeWebPage(String, PendingRequestFunction, RequestBuilderFunction) 151 | */ 152 | public PendingRequest scrapeWebPage(String url, @Nullable PendingRequestFunction pendingBuilder) { 153 | return scrapeWebPage(url, pendingBuilder, null); 154 | } 155 | 156 | /** 157 | * 158 | * @param url 159 | * @param pendingBuilder 160 | * @param requestBuilder 161 | * @return 162 | * 163 | * @see #scrapeWebPage(String) 164 | * @see #scrapeWebPage(String, PendingRequestFunction) 165 | * @see #scrapeWebPage(String, PendingRequestFunction, RequestBuilderFunction) 166 | */ 167 | public PendingRequest scrapeWebPage(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 168 | final Request.Builder builder = prepareGet(url, ContentType.TEXT_HTML); 169 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 170 | 171 | return pendingRequestBuilder.build( 172 | (response) -> Jsoup.parse(response.body().string()), 173 | WebParserUtils::handleError 174 | ); 175 | } 176 | 177 | /** 178 | * 179 | * @param url 180 | * @return 181 | * 182 | * @see #getJSONObject(String) 183 | * @see #getJSONObject(String, PendingRequestFunction) 184 | * @see #getJSONObject(String, PendingRequestFunction, RequestBuilderFunction) 185 | */ 186 | public PendingRequest getJSONObject(String url) { 187 | return getJSONObject(url, null); 188 | } 189 | 190 | /** 191 | * 192 | * @param url 193 | * @param pendingBuilder 194 | * @return 195 | * 196 | * @see #getJSONObject(String) 197 | * @see #getJSONObject(String, PendingRequestFunction) 198 | * @see #getJSONObject(String, PendingRequestFunction, RequestBuilderFunction) 199 | */ 200 | public PendingRequest getJSONObject(String url, @Nullable PendingRequestFunction pendingBuilder) { 201 | return getJSONObject(url, pendingBuilder, null); 202 | } 203 | 204 | /** 205 | * 206 | * @param url 207 | * @param pendingBuilder 208 | * @param requestBuilder 209 | * @return 210 | * 211 | * @see #getJSONObject(String) 212 | * @see #getJSONObject(String, PendingRequestFunction) 213 | * @see #getJSONObject(String, PendingRequestFunction, RequestBuilderFunction) 214 | */ 215 | public PendingRequest getJSONObject(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 216 | final Request.Builder builder = prepareGet(url, ContentType.JSON); 217 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 218 | 219 | return pendingRequestBuilder.build( 220 | (res) -> WebParserUtils.toJSONObject(res, mapper), 221 | WebParserUtils::handleError 222 | ); 223 | } 224 | 225 | /** 226 | * 227 | * @param url 228 | * @return 229 | * 230 | * @see #getJSONArray(String) 231 | * @see #getJSONArray(String, PendingRequestFunction) 232 | * @see #getJSONArray(String, PendingRequestFunction, RequestBuilderFunction) 233 | */ 234 | public PendingRequest getJSONArray(String url) { 235 | return getJSONArray(url, null); 236 | } 237 | 238 | /** 239 | * 240 | * @param url 241 | * @param pendingBuilder 242 | * @return 243 | * 244 | * @see #getJSONArray(String) 245 | * @see #getJSONArray(String, PendingRequestFunction) 246 | * @see #getJSONArray(String, PendingRequestFunction, RequestBuilderFunction) 247 | */ 248 | public PendingRequest getJSONArray(String url, @Nullable PendingRequestFunction pendingBuilder) { 249 | return getJSONArray(url, pendingBuilder, null); 250 | } 251 | 252 | /** 253 | * 254 | * @param url 255 | * @param pendingBuilder 256 | * @param requestBuilder 257 | * @return 258 | * 259 | * @see #getJSONArray(String) 260 | * @see #getJSONArray(String, PendingRequestFunction) 261 | * @see #getJSONArray(String, PendingRequestFunction, RequestBuilderFunction) 262 | */ 263 | public PendingRequest getJSONArray(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 264 | final Request.Builder builder = prepareGet(url, ContentType.JSON); 265 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 266 | 267 | return pendingRequestBuilder.build( 268 | (res) -> (ArrayNode) mapper.readTree(WebParserUtils.getInputStream(res)), 269 | WebParserUtils::handleError 270 | ); 271 | } 272 | 273 | /** 274 | * 275 | * @param url 276 | * @return 277 | * 278 | * @see #getInputStream(String) 279 | * @see #getInputStream(String, PendingRequestFunction) 280 | * @see #getInputStream(String, PendingRequestFunction, RequestBuilderFunction) 281 | */ 282 | public PendingRequest getInputStream(String url) { 283 | return getInputStream(url, null); 284 | } 285 | 286 | /** 287 | * 288 | * @param url 289 | * @param pendingBuilder 290 | * @return 291 | * 292 | * @see #getInputStream(String) 293 | * @see #getInputStream(String, PendingRequestFunction) 294 | * @see #getInputStream(String, PendingRequestFunction, RequestBuilderFunction) 295 | */ 296 | public PendingRequest getInputStream(String url, @Nullable PendingRequestFunction pendingBuilder) { 297 | return getInputStream(url, pendingBuilder, null); 298 | } 299 | 300 | /** 301 | * 302 | * @param url 303 | * @param pendingBuilder 304 | * @param requestBuilder 305 | * @return 306 | * 307 | * @see #getInputStream(String) 308 | * @see #getInputStream(String, PendingRequestFunction) 309 | * @see #getInputStream(String, PendingRequestFunction, RequestBuilderFunction) 310 | */ 311 | public PendingRequest getInputStream(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 312 | final Request.Builder builder = prepareGet(url); 313 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 314 | 315 | return pendingRequestBuilder.build( 316 | WebParserUtils::getInputStream, 317 | WebParserUtils::handleError 318 | ); 319 | } 320 | 321 | /** 322 | * 323 | * @param url 324 | * @return 325 | * 326 | * @see #getByteStream(String) 327 | * @see #getByteStream(String, PendingRequestFunction) 328 | * @see #getByteStream(String, PendingRequestFunction, RequestBuilderFunction) 329 | */ 330 | public PendingRequest getByteStream(String url) { 331 | return getByteStream(url, null); 332 | } 333 | 334 | /** 335 | * 336 | * @param url 337 | * @param pendingBuilder 338 | * @return 339 | * 340 | * @see #getByteStream(String) 341 | * @see #getByteStream(String, PendingRequestFunction) 342 | * @see #getByteStream(String, PendingRequestFunction, RequestBuilderFunction) 343 | */ 344 | public PendingRequest getByteStream(String url, @Nullable PendingRequestFunction pendingBuilder) { 345 | return getByteStream(url, pendingBuilder, null); 346 | } 347 | 348 | /** 349 | * 350 | * @param url 351 | * @param pendingBuilder 352 | * @param requestBuilder 353 | * @return 354 | * 355 | * @see #getByteStream(String) 356 | * @see #getByteStream(String, PendingRequestFunction) 357 | * @see #getByteStream(String, PendingRequestFunction, RequestBuilderFunction) 358 | */ 359 | public PendingRequest getByteStream(String url, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 360 | final Request.Builder builder = prepareGet(url); 361 | final PendingRequestBuilder pendingRequestBuilder = applyFunctions(builder, pendingBuilder, requestBuilder); 362 | 363 | return pendingRequestBuilder.build( 364 | (res) -> IOUtil.readFully(WebParserUtils.getInputStream(res)), 365 | WebParserUtils::handleError 366 | ); 367 | } 368 | 369 | /** 370 | * 371 | * @param url 372 | * @return 373 | */ 374 | public Request.Builder prepareGet(String url) { 375 | return prepareGet(url, ContentType.ANY); 376 | } 377 | 378 | /** 379 | * 380 | * @param url 381 | * @param accept 382 | * @return 383 | */ 384 | public Request.Builder prepareGet(String url, ContentType accept) { 385 | return 386 | defaultRequest() 387 | .url(url) 388 | .addHeader("Accept", accept.getType()); 389 | } 390 | 391 | /** 392 | * 393 | * @param url 394 | * @param body 395 | * @return 396 | */ 397 | public PendingRequestBuilder postRequest(String url, IRequestBody body) { 398 | return postRequest(url, body, null); 399 | } 400 | 401 | /** 402 | * 403 | * @param url 404 | * @param body 405 | * @param requestBuilder 406 | * @return 407 | */ 408 | public PendingRequestBuilder postRequest(String url, IRequestBody body, @Nullable RequestBuilderFunction requestBuilder) { 409 | final Request.Builder builder = defaultRequest() 410 | .url(url) 411 | .header("content-Type", body.getContentType().getType()) 412 | .post(body.toRequestBody()); 413 | 414 | // We return the builder so there is no need to have it as param 415 | return applyFunctions(builder, null, requestBuilder); 416 | } 417 | 418 | /** 419 | * 420 | * @param sourceLang 421 | * @param targetLang 422 | * @param input 423 | * @return 424 | */ 425 | public ArrayNode translate(String sourceLang, String targetLang, String input) { 426 | return (ArrayNode) getJSONArray( 427 | "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + input 428 | ) 429 | .execute() 430 | .get(0) 431 | .get(0); 432 | } 433 | 434 | public PendingRequestBuilder prepareBuilder(Request.Builder builder, @Nullable PendingRequestFunction fn1, @Nullable RequestBuilderFunction fn2) { 435 | if (fn2 != null) { 436 | builder = fn2.apply(builder); 437 | } 438 | 439 | PendingRequestBuilder pendingRequestBuilder = createRequest(builder); 440 | 441 | if (fn1 != null) { 442 | pendingRequestBuilder = fn1.apply(pendingRequestBuilder); 443 | } 444 | 445 | return pendingRequestBuilder; 446 | } 447 | 448 | /** 449 | * 450 | * @param request 451 | * @param mapper 452 | * @param 453 | * @return 454 | */ 455 | public PendingRequest prepareRaw(Request request, ResponseMapper mapper) { 456 | return createRequest(request).build(mapper, WebParserUtils::handleError); 457 | } 458 | 459 | private PendingRequestBuilder applyFunctions(Request.Builder builder, @Nullable PendingRequestFunction pendingBuilder, @Nullable RequestBuilderFunction requestBuilder) { 460 | if (requestBuilder != null) { 461 | builder = requestBuilder.apply(builder); 462 | } 463 | 464 | PendingRequestBuilder pendingRequestBuilder = createRequest(builder); 465 | 466 | if (pendingBuilder != null) { 467 | pendingRequestBuilder = pendingBuilder.apply(pendingRequestBuilder); 468 | } 469 | 470 | return pendingRequestBuilder; 471 | } 472 | 473 | /** 474 | * 475 | * @return 476 | */ 477 | public static String getUserAgent() { 478 | return USER_AGENT; 479 | } 480 | 481 | /** 482 | * 483 | * @param userAgent 484 | */ 485 | public static void setUserAgent(String userAgent) { 486 | USER_AGENT = userAgent; 487 | } 488 | 489 | /** 490 | * 491 | * @return 492 | */ 493 | public static Request.Builder defaultRequest() { 494 | return new Request.Builder() 495 | .get() 496 | .addHeader("User-Agent", USER_AGENT) 497 | .addHeader("cache-control", "no-cache"); 498 | } 499 | 500 | /** 501 | * Url encodes a string 502 | * 503 | * @param input the string the url encode 504 | * @return the url encoded string 505 | */ 506 | public static String urlEncodeString(String input) { 507 | try { 508 | return URLEncoder.encode(input, "UTF-8"); 509 | } catch (UnsupportedEncodingException ignored) { 510 | return ""; // Should never happen as we are using UTF-8 511 | } 512 | } 513 | } 514 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/botcommons/messaging/MessageConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Duncan "duncte123" Sterken 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 me.duncte123.botcommons.messaging; 18 | 19 | import me.duncte123.botcommons.StringUtils; 20 | import me.duncte123.botcommons.commands.ICommandContext; 21 | import net.dv8tion.jda.api.EmbedBuilder; 22 | import net.dv8tion.jda.api.entities.Message; 23 | import net.dv8tion.jda.api.entities.MessageEmbed; 24 | import net.dv8tion.jda.api.entities.MessageType; 25 | import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel; 26 | import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; 27 | import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; 28 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 29 | import net.dv8tion.jda.api.requests.RestAction; 30 | import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; 31 | import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; 32 | import net.dv8tion.jda.api.utils.messages.MessageRequest; 33 | import net.dv8tion.jda.internal.utils.Checks; 34 | 35 | import javax.annotation.Nonnull; 36 | import javax.annotation.Nullable; 37 | import java.util.ArrayList; 38 | import java.util.Arrays; 39 | import java.util.Collection; 40 | import java.util.List; 41 | import java.util.function.Consumer; 42 | import java.util.stream.Collectors; 43 | 44 | public class MessageConfig { 45 | private final MessageChannel channel; 46 | private final MessageCreateBuilder messageBuilder; 47 | private final List embeds; 48 | private final long replyToId; 49 | private final boolean mentionRepliedUser; 50 | 51 | private final Consumer failureAction; 52 | private final Consumer successAction; 53 | private final Consumer actionConfig; 54 | 55 | /** 56 | * Constructs a new instacne of the message config, it is better to use the {@link Builder builder} 57 | * 58 | * @param channel 59 | * The text channel that the message will be sent to 60 | * @param messageBuilder 61 | * The message builder that holds the content for the message 62 | * @param embeds 63 | * The embeds to send along with the message 64 | * @param replyToId 65 | * A message id to reply to, set to {@code 0} to disable 66 | * @param mentionRepliedUser 67 | * {@code false} to not ping the user in the reply (Default: {@code true}) 68 | * @param failureAction 69 | * The action that will be invoked when the message sending fails 70 | * @param successAction 71 | * The action that will be called when the message sending succeeds 72 | * @param actionConfig 73 | * Gets called before the message is sent, allows for more configuration on the message action 74 | * 75 | * @see Builder 76 | */ 77 | public MessageConfig(MessageChannel channel, MessageCreateBuilder messageBuilder, Collection embeds, long replyToId, 78 | boolean mentionRepliedUser, Consumer failureAction, 79 | Consumer successAction, Consumer actionConfig) { 80 | 81 | Checks.notNull(channel, "channel"); 82 | Checks.notNull(messageBuilder, "messageBuilder"); 83 | Checks.notNull(actionConfig, "actionConfig"); 84 | Checks.notNull(embeds, "embeds"); 85 | 86 | this.channel = channel; 87 | this.messageBuilder = messageBuilder; 88 | this.embeds = new ArrayList<>(embeds); 89 | this.replyToId = replyToId; 90 | this.mentionRepliedUser = mentionRepliedUser; 91 | this.failureAction = failureAction; 92 | this.successAction = successAction; 93 | this.actionConfig = actionConfig; 94 | } 95 | 96 | /** 97 | * Returns the text channel that the message will be sent in 98 | * 99 | * @return The text channel that the message will be sent in 100 | */ 101 | public MessageChannel getChannel() { 102 | return this.channel; 103 | } 104 | 105 | /** 106 | * Returns the message builder that holds the contents for the message
107 | * The reason that we are using a message builder is so that we can easily attach the embed and set the nonce 108 | * 109 | * @return The message builder that holds the contents for the message 110 | */ 111 | public MessageCreateBuilder getMessageBuilder() { 112 | return this.messageBuilder; 113 | } 114 | 115 | /** 116 | * Returns the list of embeds that should go under the message 117 | * 118 | * @return A possibly empty list of embeds that should go under the message 119 | */ 120 | @Nonnull 121 | public List getEmbeds() { 122 | return this.embeds; 123 | } 124 | 125 | /** 126 | * Returns the id of the message to reply to 127 | * 128 | * @return the message id that we want to reply to 129 | */ 130 | public long getReplyToId() { 131 | return replyToId; 132 | } 133 | 134 | /** 135 | * Returns true if we should mention the user we reply to, false otherwise 136 | * 137 | * @return true if we should mention the user we reply to, false otherwise 138 | */ 139 | public boolean isMentionRepliedUser() { 140 | return mentionRepliedUser; 141 | } 142 | 143 | /** 144 | * Returns the action that is called when the {@link RestAction} fails 145 | * 146 | * @return The action that is called when the {@link RestAction} fails 147 | */ 148 | public Consumer getFailureAction() { 149 | return this.failureAction; 150 | } 151 | 152 | /** 153 | * Returns the action that is called when the {@link RestAction} succeeds 154 | * 155 | * @return The action that is called when the {@link RestAction} succeeds 156 | */ 157 | public Consumer getSuccessAction() { 158 | return this.successAction; 159 | } 160 | 161 | /** 162 | * Returns the {@link MessageCreateAction} for you to configure (eg append some content or override the nonce) 163 | * 164 | * @return The {@link MessageCreateAction} for you to configure (eg append some content or override the nonce) 165 | */ 166 | public Consumer getActionConfig() { 167 | return this.actionConfig; 168 | } 169 | 170 | /** 171 | * Builder class for the message config 172 | */ 173 | // TODO: addEmbed and addEmbeds 174 | public static class Builder { 175 | private final List embeds = new ArrayList<>(); 176 | private MessageCreateBuilder messageBuilder = new MessageCreateBuilder(); 177 | private long replyToId; 178 | private boolean mentionRepliedUser = MessageRequest.isDefaultMentionRepliedUser(); 179 | private MessageChannel channel; 180 | private Consumer failureAction = RestAction.getDefaultFailure(); 181 | private Consumer successAction = RestAction.getDefaultSuccess(); 182 | private Consumer actionConfig = (a) -> { 183 | }; 184 | 185 | /** 186 | * Sets the channel that the message will be sent to 187 | * 188 | * @param channel 189 | * the channel that the message will be sent to 190 | * 191 | * @return The builder instance, useful for chaining 192 | * 193 | * @see #setChannel(MessageChannel) 194 | */ 195 | public Builder setChannel(@Nonnull MessageChannelUnion channel) { 196 | Checks.notNull(channel, "channel"); 197 | 198 | this.channel = channel; 199 | return this; 200 | } 201 | 202 | /** 203 | * Sets the channel that the message will be sent to 204 | * 205 | * @param channel 206 | * the channel that the message will be sent to 207 | * 208 | * @return The builder instance, useful for chaining 209 | * 210 | * @see #setChannel(MessageChannelUnion) 211 | */ 212 | public Builder setChannel(@Nonnull MessageChannel channel) { 213 | Checks.notNull(channel, "channel"); 214 | 215 | this.channel = channel; 216 | return this; 217 | } 218 | 219 | /** 220 | * Sets the message content for the message that will be sent.
221 | * THIS WILL REPLACE THE CURRENT MESSAGE BUILDER 222 | *

This method will also attempt to extract the channel and any possible embeds if this information is 223 | * present.

224 | * 225 | * @param message 226 | * The message to extract the content from 227 | * 228 | * @return The builder instance, useful for chaining 229 | * 230 | * @see #setMessage(String) 231 | * @see #setMessageFormat(String, Object...) 232 | */ 233 | public Builder setMessage(Message message) { 234 | this.messageBuilder = MessageCreateBuilder.fromMessage(message); 235 | // clear the embeds 236 | this.messageBuilder.setEmbeds(); 237 | 238 | // set the channel if we have one 239 | if (message.getType() == MessageType.DEFAULT && message.isFromGuild()) { 240 | this.setChannel(message.getChannel()); 241 | } 242 | 243 | // set the embeds on our own config, this will always use the raw preset 244 | if (!message.getEmbeds().isEmpty()) { 245 | this.setEmbeds(message.getEmbeds()); 246 | } 247 | 248 | return this; 249 | } 250 | 251 | /** 252 | * Sets the content of the message that will be sent 253 | * 254 | * @param message 255 | * The content for the message 256 | * 257 | * @return The builder instance, useful for chaining 258 | * 259 | * @see #setMessage(Message) 260 | * @see #setMessageFormat(String, Object...) 261 | */ 262 | public Builder setMessage(String message) { 263 | this.messageBuilder.setContent(StringUtils.abbreviate(message, Message.MAX_CONTENT_LENGTH)); 264 | return this; 265 | } 266 | 267 | /** 268 | * Sets the content for the message and applies a format, this is a shortcut for using {@link String#format} 269 | * with {@link #setMessage(String)} 270 | * 271 | * @param message 272 | * The content for the message 273 | * @param args 274 | * the arguments to format the message with 275 | * 276 | * @return The builder instance, useful for chaining 277 | * 278 | * @see #setMessage(Message) 279 | * @see #setMessage(String) 280 | */ 281 | public Builder setMessageFormat(String message, Object... args) { 282 | this.messageBuilder.setContent(String.format(message, args)); 283 | return this; 284 | } 285 | 286 | /** 287 | * Sets the embed for the message 288 | * 289 | * @param embeds 290 | * The embeds to set on the message 291 | * 292 | * @return The builder instance, useful for chaining 293 | * 294 | * @see #addEmbed(EmbedBuilder) 295 | * @see #addEmbed(boolean, EmbedBuilder) 296 | * @see #setEmbeds(boolean, EmbedBuilder...) 297 | * @see #setEmbeds(Collection) 298 | * @see #setEmbeds(boolean, Collection) 299 | */ 300 | public Builder setEmbeds(@Nonnull EmbedBuilder... embeds) { 301 | return this.setEmbeds(false, embeds); 302 | } 303 | 304 | /** 305 | * Sets the embed for the message.
306 | * NOTE: Parsing of colors will never happen if the text channel is null at the time of calling this 307 | * method 308 | * 309 | * @param raw 310 | * {@code true} to skip parsing of the guild-colors and other future items, default value is {@code false} 311 | * @param embeds 312 | * The embeds on the message 313 | * 314 | * @return The builder instance, useful for chaining 315 | * 316 | * @see #addEmbed(EmbedBuilder) 317 | * @see #addEmbed(boolean, EmbedBuilder) 318 | * @see #setEmbeds(EmbedBuilder...) 319 | * @see #setEmbeds(Collection) 320 | * @see #setEmbeds(boolean, Collection) 321 | */ 322 | public Builder setEmbeds(boolean raw, @Nonnull EmbedBuilder... embeds) { 323 | Checks.noneNull(embeds, "MessageEmbeds"); 324 | 325 | return this.setEmbeds(raw, Arrays.asList(embeds)); 326 | } 327 | 328 | /** 329 | * Sets the embeds that the message should have 330 | * 331 | * @param embeds 332 | * The embeds to attach to the message 333 | * 334 | * @return The builder instance, useful for chaining 335 | * 336 | * @see #addEmbed(EmbedBuilder) 337 | * @see #addEmbed(boolean, EmbedBuilder) 338 | * @see #setEmbeds(EmbedBuilder...) 339 | * @see #setEmbeds(boolean, EmbedBuilder...) 340 | * @see #setEmbeds(boolean, Collection) 341 | */ 342 | public Builder setEmbeds(@Nonnull Collection embeds) { 343 | return this.setEmbeds(false, embeds); 344 | } 345 | 346 | /** 347 | * Please don't use this method 348 | * 349 | * @param embeds 350 | * The embeds to set 351 | * 352 | * @return The builder instance, useful for chaining 353 | * 354 | * @see #addEmbed(EmbedBuilder) 355 | * @see #addEmbed(boolean, EmbedBuilder) 356 | * @see #setEmbeds(EmbedBuilder...) 357 | * @see #setEmbeds(boolean, EmbedBuilder...) 358 | * @see #setEmbeds(Collection) 359 | * @see #setEmbeds(boolean, Collection) 360 | */ 361 | public Builder setEmbeds(@Nonnull List embeds) { 362 | return this.setEmbeds( 363 | true, 364 | embeds.stream().map(EmbedBuilder::new).collect(Collectors.toList()) 365 | ); 366 | } 367 | 368 | /** 369 | * Sets the embeds for the message 370 | * 371 | * @param raw 372 | * {@code true} to skip parsing of the guild-colors and other future items, default value is {@code false} 373 | * @param embeds 374 | * The embeds to set on the message 375 | * 376 | * @return The builder instance, useful for chaining 377 | * 378 | * @see #addEmbed(EmbedBuilder) 379 | * @see #addEmbed(boolean, EmbedBuilder) 380 | * @see #setEmbeds(EmbedBuilder...) 381 | * @see #setEmbeds(boolean, EmbedBuilder...) 382 | * @see #setEmbeds(Collection) 383 | */ 384 | public Builder setEmbeds(boolean raw, @Nonnull Collection embeds) { 385 | Checks.noneNull(embeds, "MessageEmbeds"); 386 | 387 | Checks.check(embeds.size() <= 10, "Cannot have more than 10 embeds in a message!"); 388 | 389 | // Use raw to skip this parsing 390 | if (!raw && this.channel != null && this.channel instanceof GuildMessageChannel) { 391 | final long guild = ((GuildMessageChannel) this.channel).getGuild().getIdLong(); 392 | 393 | for (final EmbedBuilder embedBuilder : embeds) { 394 | embedBuilder.setColor(EmbedUtils.getColorOrDefault(guild)); 395 | } 396 | } 397 | 398 | this.embeds.clear(); 399 | this.embeds.addAll(embeds); 400 | 401 | return this; 402 | } 403 | 404 | /** 405 | * Adds a single embed to the current embed list 406 | * 407 | * @param embed 408 | * The embed to add 409 | * 410 | * @return The builder instance, useful for chaining 411 | * 412 | * @see #addEmbed(boolean, EmbedBuilder) 413 | * @see #setEmbeds(EmbedBuilder...) 414 | * @see #setEmbeds(boolean, EmbedBuilder...) 415 | * @see #setEmbeds(Collection) 416 | * @see #setEmbeds(boolean, Collection) 417 | */ 418 | public Builder addEmbed(@Nonnull EmbedBuilder embed) { 419 | return this.addEmbed(false, embed); 420 | } 421 | 422 | /** 423 | * Adds a single embed to the current embed list 424 | * 425 | * @param raw 426 | * {@code true} to skip parsing of the guild-colors and other future items, default value is {@code false} 427 | * @param embed 428 | * The embed to add 429 | * 430 | * @return The builder instance, useful for chaining 431 | * 432 | * @see #addEmbed(EmbedBuilder) 433 | * @see #setEmbeds(EmbedBuilder...) 434 | * @see #setEmbeds(boolean, EmbedBuilder...) 435 | * @see #setEmbeds(Collection) 436 | * @see #setEmbeds(boolean, Collection) 437 | */ 438 | public Builder addEmbed(boolean raw, @Nonnull EmbedBuilder embed) { 439 | Checks.notNull(embed, "embed"); 440 | Checks.check(this.embeds.size() <= 10, "Cannot have more than 10 embeds in a message!"); 441 | 442 | // Use raw to skip this parsing 443 | if (!raw && this.channel != null && this.channel instanceof GuildMessageChannel) { 444 | final long guild = ((GuildMessageChannel) this.channel).getGuild().getIdLong(); 445 | 446 | embed.setColor(EmbedUtils.getColorOrDefault(guild)); 447 | } 448 | 449 | this.embeds.add(embed); 450 | 451 | return this; 452 | } 453 | 454 | /** 455 | * Returns the current message builder instance for you to modify 456 | * 457 | * @return The message builder instance that you can modify 458 | * 459 | * @see #configureMessageBuilder(Consumer) 460 | */ 461 | public MessageCreateBuilder getMessageBuilder() { 462 | return this.messageBuilder; 463 | } 464 | 465 | /** 466 | * Allows you to override the message builder 467 | * 468 | * @param messageBuilder 469 | * the new message builder to use 470 | * 471 | * @return The builder instance, useful for chaining 472 | */ 473 | public Builder setMessageBuilder(MessageCreateBuilder messageBuilder) { 474 | this.messageBuilder = messageBuilder; 475 | 476 | return this; 477 | } 478 | 479 | /** 480 | * Applies a configuration to the message builder 481 | * 482 | * @param consumer 483 | * the builder that you can modify 484 | * 485 | * @return The builder instance, useful for chaining 486 | * 487 | * @see #getMessageBuilder() 488 | */ 489 | public Builder configureMessageBuilder(@Nonnull Consumer consumer) { 490 | Checks.notNull(consumer, "consumer"); 491 | 492 | consumer.accept(this.messageBuilder); 493 | return this; 494 | } 495 | 496 | /** 497 | * Sets the action that is called when the {@link RestAction} fails 498 | * 499 | * @param failureAction 500 | * the action that is called when the {@link RestAction} fails, Defaults to {@link 501 | * RestAction#getDefaultFailure()} 502 | * 503 | * @return The builder instance, useful for chaining 504 | */ 505 | public Builder setFailureAction(Consumer failureAction) { 506 | this.failureAction = failureAction; 507 | return this; 508 | } 509 | 510 | /** 511 | * Sets the action that is called when the {@link RestAction} succeeds 512 | * 513 | * @param successAction 514 | * the action that is called when the {@link RestAction} succeeds, Defaults to {@link 515 | * RestAction#getDefaultSuccess()} 516 | * 517 | * @return The builder instance, useful for chaining 518 | */ 519 | public Builder setSuccessAction(Consumer successAction) { 520 | this.successAction = successAction; 521 | return this; 522 | } 523 | 524 | /** 525 | * Sets the {@link MessageCreateAction} for you to configure (eg append some content or override the nonce) 526 | * 527 | * @param actionConfig 528 | * the {@link MessageCreateAction} for you to configure (eg append some content or override the nonce) 529 | * 530 | * @return The builder instance, useful for chaining 531 | * 532 | * @see MessageCreateAction 533 | */ 534 | public Builder setActionConfig(@Nonnull Consumer actionConfig) { 535 | Checks.notNull(actionConfig, "actionConfig"); 536 | 537 | this.actionConfig = actionConfig; 538 | return this; 539 | } 540 | 541 | /** 542 | * Replies to the given {@link Message}
543 | * THIS WILL ONLY WORK IF THE BOT HAS READ HISTORY PERMISSION IN THE CHANNEL 544 | * 545 | * @param message 546 | * The {@link Message} on discord that you want to reply to, or {@code null} to disable 547 | * 548 | * @return The builder instance, useful for chaining 549 | * 550 | * @see #replyTo(long) 551 | * @see #replyTo(long, boolean) 552 | * @see #replyTo(Message, boolean) 553 | */ 554 | public Builder replyTo(@Nullable Message message) { 555 | if (message == null) { 556 | this.replyToId = 0; 557 | } else { 558 | this.replyToId = message.getIdLong(); 559 | } 560 | 561 | return this; 562 | } 563 | 564 | /** 565 | * Replies to the given {@link Message}
566 | * THIS WILL ONLY WORK IF THE BOT HAS READ HISTORY PERMISSION IN THE CHANNEL 567 | * 568 | * @param message 569 | * The {@link Message} on discord that you want to reply to, or {@code null} to disable 570 | * @param mentionRepliedUser 571 | * Set to {@code false} to not ping the user in the reply (Default: {@link 572 | * MessageRequest#isDefaultMentionRepliedUser()}) 573 | * 574 | * @return The builder instance, useful for chaining 575 | * 576 | * @see #replyTo(long) 577 | * @see #replyTo(long, boolean) 578 | * @see #replyTo(Message) 579 | */ 580 | public Builder replyTo(@Nullable Message message, boolean mentionRepliedUser) { 581 | if (message == null) { 582 | this.replyToId = 0; 583 | } else { 584 | this.replyToId = message.getIdLong(); 585 | } 586 | 587 | this.mentionRepliedUser = mentionRepliedUser; 588 | return this; 589 | } 590 | 591 | /** 592 | * Replies to the given message with the specified id
593 | * THIS WILL ONLY WORK IF THE BOT HAS READ HISTORY PERMISSION IN THE CHANNEL 594 | * 595 | * @param messageId 596 | * The message id from a message on discord, set to {@code 0} to disable 597 | * 598 | * @return The builder instance, useful for chaining 599 | * 600 | * @see #replyTo(long, boolean) 601 | * @see #replyTo(Message) 602 | * @see #replyTo(Message, boolean) 603 | */ 604 | public Builder replyTo(long messageId) { 605 | this.replyToId = messageId; 606 | return this; 607 | } 608 | 609 | /** 610 | * Replies to the given message with the specified id
611 | * THIS WILL ONLY WORK IF THE BOT HAS READ HISTORY PERMISSION IN THE CHANNEL 612 | * 613 | * @param messageId 614 | * The message id from a message on discord, set to {@code 0} to disable 615 | * @param mentionRepliedUser 616 | * Set to {@code false} to not ping the user in the reply (Default: {@link 617 | * MessageRequest#isDefaultMentionRepliedUser()}) 618 | * 619 | * @return The builder instance, useful for chaining 620 | * 621 | * @see #replyTo(long) 622 | * @see #replyTo(Message) 623 | * @see #replyTo(Message, boolean) 624 | */ 625 | public Builder replyTo(long messageId, boolean mentionRepliedUser) { 626 | this.replyToId = messageId; 627 | this.mentionRepliedUser = mentionRepliedUser; 628 | return this; 629 | } 630 | 631 | /** 632 | * Builds the message config and returns it. 633 | *

NOTE: This method will return null when the text channel is null

634 | * 635 | * @return a message config instance 636 | */ 637 | @Nonnull 638 | public MessageConfig build() { 639 | if (this.channel == null) { 640 | throw new IllegalArgumentException("No text channel has been set, set this with setChannel"); 641 | } 642 | 643 | // we can send messages with just an embed 644 | if (this.messageBuilder.isEmpty() && this.embeds.isEmpty()) { 645 | throw new IllegalArgumentException("This message has no content, please add some content with setMessage or setEmbeds"); 646 | } 647 | 648 | Checks.check(this.embeds.size() <= 10, "Cannot have more than 10 embeds in a message!"); 649 | 650 | return new MessageConfig( 651 | this.channel, 652 | this.messageBuilder, 653 | this.embeds, 654 | this.replyToId, 655 | this.mentionRepliedUser, 656 | this.failureAction, 657 | this.successAction, 658 | this.actionConfig 659 | ); 660 | } 661 | 662 | /** 663 | * Creates a config builder instance from a command context 664 | * 665 | * @param ctx 666 | * a command context instance to get the text channel from 667 | * 668 | * @return A builder instance that was created from a command context 669 | * 670 | * @see me.duncte123.botcommons.commands.DefaultCommandContext 671 | */ 672 | public static Builder fromCtx(ICommandContext ctx) { 673 | return new Builder().setChannel(ctx.getChannel()).replyTo(ctx.getMessage()); 674 | } 675 | 676 | /** 677 | * Creates a config builder instance from a JDA guild message received event 678 | * 679 | * @param event 680 | * A {@link MessageReceivedEvent} from JDA to get the text channel from 681 | * 682 | * @return A builder instance that was created from a {@link MessageReceivedEvent} 683 | */ 684 | public static Builder fromEvent(MessageReceivedEvent event) { 685 | return new Builder().setChannel(event.getChannel()).replyTo(event.getMessage()); 686 | } 687 | } 688 | } 689 | --------------------------------------------------------------------------------