Compare commits
147 Commits
64f0b611ca
...
renovate/o
| Author | SHA1 | Date | |
|---|---|---|---|
| af24b010fc | |||
| f3ec956c7a | |||
| 0fc8beacf8 | |||
| ecbf4080ae | |||
| e1215cfa25 | |||
| 6f2dd2a220 | |||
| ff8efba025 | |||
| d8c1435416 | |||
| eb3178a706 | |||
| b431ca4eae | |||
| ff9a6d9e14 | |||
| ed49a6de32 | |||
| 31c2f22c40 | |||
| 475864389c | |||
| 195400fae8 | |||
| 1227fff1b1 | |||
| 8800a0fea4 | |||
| 884d1376e1 | |||
| 89bf70c388 | |||
| 0499a24ae7 | |||
| e54ce77e43 | |||
| 2df821b28b | |||
| a23b198531 | |||
| ba369a9ea1 | |||
| 1f40450920 | |||
| 51f5b57f47 | |||
| fd2970fa59 | |||
| 14b54501fd | |||
| 1928cfe858 | |||
| 0b7880af88 | |||
| fc00467059 | |||
| f1969c2043 | |||
| acad4bad8b | |||
| 4ce9acd428 | |||
| 2ab52bd713 | |||
| f38e34c1ce | |||
| f87854459f | |||
| 72c4ae2133 | |||
| 7f4ca6aa8e | |||
| c3793aa159 | |||
| 63fc1feaea | |||
| 71d646ff69 | |||
| 48d537d2db | |||
| 136447b9df | |||
| 372949a9e0 | |||
| 4f4549a81e | |||
| b0dd1c21b2 | |||
| d46368f0ce | |||
| 2032dc1d0e | |||
| 9c099230c9 | |||
| f2134cbdb9 | |||
| 97e846c3dc | |||
| 7f16a011b3 | |||
| b32ece3f88 | |||
| 681785ef0d | |||
| a72b6f690b | |||
| 645fb5f4a6 | |||
| a228067cce | |||
| 4f0eb7ce74 | |||
| a7e36299b6 | |||
| 1e7c43e360 | |||
| 2a4a80cc3f | |||
| a50e8c050b | |||
| f7c1b096bc | |||
| 884814064c | |||
| ce0938bc2c | |||
| aabfbd3020 | |||
| 25bc5a3ef2 | |||
| ab52f30eb2 | |||
| 2e0c2e4e14 | |||
| edf896efb0 | |||
| bd7355add9 | |||
| 6d210551af | |||
| abd3c02be6 | |||
| 50749f2108 | |||
| fc7b6d54d1 | |||
| f5d684c5a4 | |||
| 5ea12aa693 | |||
| 5c4f7e4252 | |||
| d9dcde7560 | |||
| 64762a9a4f | |||
| 4542985431 | |||
| 88d4b6461b | |||
| e8f1c85f08 | |||
| 1ed389c18b | |||
| 4320c9698a | |||
| 3a8044dda1 | |||
| 96ca58de12 | |||
| 5ed444ab92 | |||
| 19a5583594 | |||
| a39bcf68cb | |||
| eb08f0bcab | |||
| 87eadb88ef | |||
| 4f74541d1d | |||
| 86f370643e | |||
| 27133b8e3c | |||
| 54fee8a010 | |||
| 9e3289c616 | |||
| a5d647e6ba | |||
| 44add27d5e | |||
| fa17bf8ef6 | |||
| 90e576923d | |||
| ea31746442 | |||
| 3c522149c3 | |||
| ed1b25b403 | |||
| 04d93dd7a5 | |||
| f523e6cd92 | |||
| 35f52ec583 | |||
| 549f8bb48b | |||
| be9bd1a068 | |||
| 2a7be8868c | |||
| e51646ace4 | |||
| 4abd3d6179 | |||
| 0f2e2f876d | |||
| 06b28aac70 | |||
| 9f52e8747c | |||
| 829e19fac3 | |||
| ff323b9d8b | |||
| 5aa99ae4bf | |||
| 96465af441 | |||
| f4fc8811ef | |||
| 3abb48ba60 | |||
| d58cc08082 | |||
| 1675b62967 | |||
| cc29b63d78 | |||
| d816a1f1d9 | |||
| d788070eb8 | |||
| 627f6deb97 | |||
| 668375367a | |||
| 980cf5eef3 | |||
| ccf69a2903 | |||
| 6c6cdab9f4 | |||
| 05efe6c0d3 | |||
| 4f615378a6 | |||
| 118979bde4 | |||
| 009fec3be3 | |||
| 546637c188 | |||
| d315b3f38a | |||
| 94037b252f | |||
| d62d6bdfdd | |||
| 7f73d4fb23 | |||
| 383b09a53e | |||
| c9d69c512c | |||
| 8b1c1b4d04 | |||
| a28781b806 | |||
| 78bdadad06 | |||
| a5b9f9d993 |
@@ -1,7 +0,0 @@
|
|||||||
version = 1
|
|
||||||
|
|
||||||
[[analyzers]]
|
|
||||||
name = "java"
|
|
||||||
|
|
||||||
[analyzers.meta]
|
|
||||||
runtime_version = "16"
|
|
||||||
68
.drone.yml
68
.drone.yml
@@ -1,62 +1,14 @@
|
|||||||
kind: pipeline
|
kind: template
|
||||||
type: docker
|
load: java-build-deploy.yaml
|
||||||
name: build
|
data:
|
||||||
|
arch: arm64
|
||||||
trigger:
|
os: linux
|
||||||
branch:
|
build_branches:
|
||||||
- main
|
- main
|
||||||
event:
|
- develop
|
||||||
|
build_events:
|
||||||
- push
|
- push
|
||||||
- pull_request
|
- pull_request
|
||||||
|
sonar_project_key: HidekoBot
|
||||||
steps:
|
deploy_targets:
|
||||||
# test if it compiles correctly
|
|
||||||
- name: build
|
|
||||||
image: maven:3-eclipse-temurin-16
|
|
||||||
commands:
|
|
||||||
- mvn verify --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V
|
|
||||||
|
|
||||||
# run unit tests
|
|
||||||
- name: test
|
|
||||||
image: maven:3-eclipse-temurin-16
|
|
||||||
commands:
|
|
||||||
- mvn test --no-transfer-progress -B -V
|
|
||||||
|
|
||||||
# run code analysis
|
|
||||||
- name: code-analysis
|
|
||||||
image: maven:3-eclipse-temurin-16
|
|
||||||
commands:
|
|
||||||
- mvn sonar:sonar --no-transfer-progress -Dsonar.projectKey=$SONAR_PROJECT_KEY -Dsonar.host.url=$SONAR_INSTANCE_URL -Dsonar.login=$SONAR_LOGIN_KEY -B -V
|
|
||||||
environment:
|
|
||||||
SONAR_PROJECT_KEY:
|
|
||||||
from_secret: sonar_project_key
|
|
||||||
SONAR_INSTANCE_URL:
|
|
||||||
from_secret: sonar_instance_url
|
|
||||||
SONAR_LOGIN_KEY:
|
|
||||||
from_secret: sonar_login_key
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
kind: pipeline
|
|
||||||
type: docker
|
|
||||||
name: default
|
|
||||||
|
|
||||||
trigger:
|
|
||||||
event:
|
|
||||||
- promote
|
|
||||||
target:
|
|
||||||
- production
|
- production
|
||||||
|
|
||||||
steps:
|
|
||||||
# skip all previous steps because they were already ran in the "build" phase; we don't need to re-analyze the code.
|
|
||||||
|
|
||||||
# upload to maven repository
|
|
||||||
- name: maven-deploy
|
|
||||||
image: maven:3-eclipse-temurin-16
|
|
||||||
commands:
|
|
||||||
- mvn deploy --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V -gs settings.xml -Dmaven.repo.username=$MAVEN_REPO_USERNAME -Dmaven.repo.password=$MAVEN_REPO_PASSWORD
|
|
||||||
environment:
|
|
||||||
MAVEN_REPO_USERNAME:
|
|
||||||
from_secret: maven_repo_username
|
|
||||||
MAVEN_REPO_PASSWORD:
|
|
||||||
from_secret: maven_repo_password
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
target/
|
target/
|
||||||
.idea/
|
.idea/
|
||||||
|
scripts/
|
||||||
*.sqlite
|
*.sqlite
|
||||||
88
.pipelines/java-build-deploy.yaml
Normal file
88
.pipelines/java-build-deploy.yaml
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
---
|
||||||
|
kind: pipeline
|
||||||
|
type: docker
|
||||||
|
name: build
|
||||||
|
platform:
|
||||||
|
os: {{ .input.os }}
|
||||||
|
arch: {{ .input.arch }}
|
||||||
|
|
||||||
|
trigger:
|
||||||
|
branch:
|
||||||
|
{{- range .input.build_branches }}
|
||||||
|
- {{ . }}
|
||||||
|
{{- end }}
|
||||||
|
event:
|
||||||
|
{{- range .input.build_events }}
|
||||||
|
- {{ . }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
# Global project-specific environment variables
|
||||||
|
environment:
|
||||||
|
{{- range .input.envs }}
|
||||||
|
{{ .name }}: {{ .value }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# Test if it compiles correctly
|
||||||
|
- name: build
|
||||||
|
image: maven:3-eclipse-temurin-21
|
||||||
|
commands:
|
||||||
|
- mvn verify --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V
|
||||||
|
|
||||||
|
# Run unit tests
|
||||||
|
- name: test
|
||||||
|
image: maven:3-eclipse-temurin-21
|
||||||
|
commands:
|
||||||
|
- mvn test --no-transfer-progress -B -V
|
||||||
|
|
||||||
|
# Check maven dependencies
|
||||||
|
- name: dependency-check
|
||||||
|
image: owasp/dependency-check:latest
|
||||||
|
commands:
|
||||||
|
- dependency-check --scan /src --format ALL --out /src/target --nvdApiKey $NVD_API_KEY
|
||||||
|
environment:
|
||||||
|
NVD_API_KEY:
|
||||||
|
from_secret: nvd_api_key
|
||||||
|
|
||||||
|
# Run code analysis
|
||||||
|
- name: code-analysis
|
||||||
|
when:
|
||||||
|
event:
|
||||||
|
- push
|
||||||
|
image: maven:3-eclipse-temurin-21
|
||||||
|
commands:
|
||||||
|
- mvn sonar:sonar --no-transfer-progress -Dsonar.projectKey={{ .input.sonar_project_key }} -Dsonar.host.url=$SONAR_INSTANCE_URL -Dsonar.token=$SONAR_LOGIN_KEY -B -V
|
||||||
|
environment:
|
||||||
|
SONAR_INSTANCE_URL:
|
||||||
|
from_secret: sonar_instance_url
|
||||||
|
SONAR_LOGIN_KEY:
|
||||||
|
from_secret: sonar_login_key
|
||||||
|
---
|
||||||
|
kind: pipeline
|
||||||
|
type: kubernetes
|
||||||
|
name: deploy
|
||||||
|
trigger:
|
||||||
|
event:
|
||||||
|
- promote
|
||||||
|
target:
|
||||||
|
{{- range .input.deploy_targets }}
|
||||||
|
- {{ . }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
# Global project-specific environment variables
|
||||||
|
environment:
|
||||||
|
{{- range .input.envs }}
|
||||||
|
{{ .name }}: {{ .value }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# Upload to Maven repository
|
||||||
|
- name: maven-deploy
|
||||||
|
image: maven:3-eclipse-temurin-21
|
||||||
|
commands:
|
||||||
|
- mvn deploy --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V -gs settings.xml -Dmaven.repo.username=$MAVEN_REPO_USERNAME -Dmaven.repo.password=$MAVEN_REPO_PASSWORD
|
||||||
|
environment:
|
||||||
|
MAVEN_REPO_USERNAME:
|
||||||
|
from_secret: maven_repo_username
|
||||||
|
MAVEN_REPO_PASSWORD:
|
||||||
|
from_secret: maven_repo_password
|
||||||
19
README.MD
19
README.MD
@@ -1,9 +1,9 @@
|
|||||||
# HidekoBot
|
# HidekoBot
|
||||||
[](https://sonar.beatrice.wtf/dashboard?id=mind-overflow_HidekoBot_AYWyYHsvX-1Ma0D4pJ59)
|
[](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
|
||||||
[](https://sonar.beatrice.wtf/dashboard?id=mind-overflow_HidekoBot_AYWyYHsvX-1Ma0D4pJ59)
|
[](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
|
||||||
[](https://sonar.beatrice.wtf/dashboard?id=mind-overflow_HidekoBot_AYWyYHsvX-1Ma0D4pJ59)
|
[](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
|
||||||
[](https://drone.beatrice.wtf/mind-overflow/HidekoBot)
|
[](https://drone.beatrice.wtf/bea/HidekoBot)
|
||||||
[](https://sonar.beatrice.wtf/dashboard?id=mind-overflow_HidekoBot_AYWyYHsvX-1Ma0D4pJ59)
|
[](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
|
||||||
|
|
||||||
Hideko is a general-purpose Discord bot.
|
Hideko is a general-purpose Discord bot.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ Additionally available parameters are:
|
|||||||
- **verbose**: log every message that the bot receives, plus additional debugging messages. Very spammy and performance heavy.
|
- **verbose**: log every message that the bot receives, plus additional debugging messages. Very spammy and performance heavy.
|
||||||
- **refresh**: force refresh the slash commands. This is useful in case there was a simple update to a command that did not drastically change it, so no changes are found at bootup (eg: fixing a typo in the command description).
|
- **refresh**: force refresh the slash commands. This is useful in case there was a simple update to a command that did not drastically change it, so no changes are found at bootup (eg: fixing a typo in the command description).
|
||||||
|
|
||||||
*Note: Java 16 or later is required.*
|
*Note: Java 21 or later is required.*
|
||||||
|
|
||||||
## Initial setup
|
## Initial setup
|
||||||
|
|
||||||
@@ -39,3 +39,10 @@ commands support both systems, but some of them are limited in one way or anothe
|
|||||||
The bot currently supports SQLite as a database backend. A database file will be created after the first boot
|
The bot currently supports SQLite as a database backend. A database file will be created after the first boot
|
||||||
in your current directory. Do not delete the database file to avoid corruption and unpredictable
|
in your current directory. Do not delete the database file to avoid corruption and unpredictable
|
||||||
behavior.
|
behavior.
|
||||||
|
|
||||||
|
# Development
|
||||||
|
## Versioning
|
||||||
|
This project uses the `x.y.z-releaseType` schema for releases.
|
||||||
|
Development builds are tagged as `x.y.z-SNAPSHOT` and sometimes pushed to the snapshots Maven repository.
|
||||||
|
Stable builds are tagged as `x.y.z` and always pushed to the releases Maven repository, by promoting the build on
|
||||||
|
[Drone](https://drone.beatrice.wtf/). Currently, promoting stable builds is a manual process.
|
||||||
|
|||||||
65
pom.xml
65
pom.xml
@@ -6,12 +6,15 @@
|
|||||||
|
|
||||||
<groupId>wtf.beatrice.hidekobot</groupId>
|
<groupId>wtf.beatrice.hidekobot</groupId>
|
||||||
<artifactId>HidekoBot</artifactId>
|
<artifactId>HidekoBot</artifactId>
|
||||||
<version>0.5.18</version>
|
<version>0.6.3-SNAPSHOT</version>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>16</maven.compiler.source>
|
<maven.compiler.source>21</maven.compiler.source>
|
||||||
<maven.compiler.target>16</maven.compiler.target>
|
<maven.compiler.target>21</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<sonar.dependencyCheck.htmlReportPath>./target/dependency-check-report.html</sonar.dependencyCheck.htmlReportPath>
|
||||||
|
<sonar.dependencyCheck.jsonReportPath>./target/dependency-check-report.json</sonar.dependencyCheck.jsonReportPath>
|
||||||
|
<sonar.dependencyCheck.summarize>true</sonar.dependencyCheck.summarize>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@@ -19,51 +22,51 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.dv8tion</groupId>
|
<groupId>net.dv8tion</groupId>
|
||||||
<artifactId>JDA</artifactId>
|
<artifactId>JDA</artifactId>
|
||||||
<version>5.0.0-beta.2</version>
|
<version>5.6.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- JDA depends on SLF4J for logging -->
|
<!-- JDA depends on SLF4J for logging -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>2.0.6</version>
|
<version>2.0.17</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-simple</artifactId>
|
<artifactId>slf4j-simple</artifactId>
|
||||||
<version>2.0.6</version>
|
<version>2.0.17</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Dependency used for SQLite database connections-->
|
<!-- Dependency used for SQLite database connections-->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.xerial</groupId>
|
<groupId>org.xerial</groupId>
|
||||||
<artifactId>sqlite-jdbc</artifactId>
|
<artifactId>sqlite-jdbc</artifactId>
|
||||||
<version>3.40.0.0</version>
|
<version>3.51.0.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Dependency used for YAML configuration files -->
|
<!-- Dependency used for YAML configuration files -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.yaml</groupId>
|
<groupId>org.yaml</groupId>
|
||||||
<artifactId>snakeyaml</artifactId>
|
<artifactId>snakeyaml</artifactId>
|
||||||
<version>1.33</version>
|
<version>2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- JSoup is used to parse HTML into JSON objects for better handling in Java -->
|
<!-- JSoup is used to parse HTML into JSON objects for better handling in Java -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jsoup</groupId>
|
<groupId>org.jsoup</groupId>
|
||||||
<artifactId>jsoup</artifactId>
|
<artifactId>jsoup</artifactId>
|
||||||
<version>1.15.3</version>
|
<version>1.21.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Various String manipulation utils -->
|
<!-- Various String manipulation utils -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-text</artifactId>
|
<artifactId>commons-text</artifactId>
|
||||||
<version>1.10.0</version>
|
<version>1.14.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- JSON dependency used for better parsing of JSON files -->
|
<!-- JSON dependency used for better parsing of JSON files -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.json</groupId>
|
<groupId>org.json</groupId>
|
||||||
<artifactId>json</artifactId>
|
<artifactId>json</artifactId>
|
||||||
<version>20220924</version>
|
<version>20250517</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Start Random.org dependencies -->
|
<!-- Start Random.org dependencies -->
|
||||||
@@ -75,12 +78,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.10.1</version>
|
<version>2.13.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-codec</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
<artifactId>commons-codec</artifactId>
|
<artifactId>commons-codec</artifactId>
|
||||||
<version>1.15</version>
|
<version>1.20.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- End Random.org dependencies -->
|
<!-- End Random.org dependencies -->
|
||||||
|
|
||||||
@@ -88,11 +91,22 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-api</artifactId>
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
<version>5.9.2</version>
|
<version>6.0.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<!-- override dependencies to use newer versions -->
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java</artifactId>
|
||||||
|
<version>4.33.0</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<resources>
|
<resources>
|
||||||
@@ -129,13 +143,32 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
<version>3.4.1</version>
|
<version>3.12.0</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.sonarsource.scanner.maven</groupId>
|
<groupId>org.sonarsource.scanner.maven</groupId>
|
||||||
<artifactId>sonar-maven-plugin</artifactId>
|
<artifactId>sonar-maven-plugin</artifactId>
|
||||||
<version>3.9.1.2184</version>
|
<version>5.3.0.6276</version>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.owasp</groupId>
|
||||||
|
<artifactId>dependency-check-maven</artifactId>
|
||||||
|
<version>12.1.8</version>
|
||||||
|
<configuration>
|
||||||
|
<failBuildOnCVSS>8</failBuildOnCVSS>
|
||||||
|
<!--suppress UnresolvedMavenProperty -->
|
||||||
|
<nvdApiKey>${nvdApiKey}</nvdApiKey>
|
||||||
|
<knownExploitedUrl>https://raw.githubusercontent.com/EugenMayer/cisa-known-exploited-mirror/main/known_exploited_vulnerabilities.json</knownExploitedUrl>
|
||||||
|
<formats>
|
||||||
|
<format>html</format>
|
||||||
|
<format>json</format>
|
||||||
|
</formats>
|
||||||
|
<suppressionFiles>
|
||||||
|
<suppressionFile>./suppressions.xml</suppressionFile>
|
||||||
|
</suppressionFiles>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|||||||
3
renovate.json
Normal file
3
renovate.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
|
||||||
|
}
|
||||||
@@ -22,9 +22,14 @@ import java.util.concurrent.ScheduledExecutorService;
|
|||||||
public class Cache
|
public class Cache
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private Cache()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// todo: make this compatible with the message listener's regex
|
// todo: make this compatible with the message listener's regex
|
||||||
private static final String botPrefix = "hideko";
|
private static final String BOT_PREFIX = "hideko";
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(Cache.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(Cache.class);
|
||||||
|
|
||||||
// map to store results of "love calculator", to avoid people re-running the same command until
|
// map to store results of "love calculator", to avoid people re-running the same command until
|
||||||
@@ -38,11 +43,11 @@ public class Cache
|
|||||||
private static DatabaseSource databaseSource = null;
|
private static DatabaseSource databaseSource = null;
|
||||||
private static boolean verbose = false;
|
private static boolean verbose = false;
|
||||||
private static MessageLogger verbosityLogger = null;
|
private static MessageLogger verbosityLogger = null;
|
||||||
private static final long botMaintainerId = 979809420714332260L;
|
private static final long BOT_MAINTAINER_ID = 979809420714332260L;
|
||||||
private static final String expiryTimestampFormat = "yy/MM/dd HH:mm:ss";
|
private static final String EXPIRY_TIMESTAMP_FORMAT = "yy/MM/dd HH:mm:ss";
|
||||||
|
|
||||||
// note: discord sets interactions' expiry time to 15 minutes by default, so we can't go higher than that.
|
// note: discord sets interactions' expiry time to 15 minutes by default, so we can't go higher than that.
|
||||||
private static final long expiryTimeSeconds = 30L;
|
private static final long EXPIRY_TIME_SECONDS = 30L;
|
||||||
|
|
||||||
// used to count e.g. uptime
|
// used to count e.g. uptime
|
||||||
private static LocalDateTime startupTime = null;
|
private static LocalDateTime startupTime = null;
|
||||||
@@ -53,14 +58,14 @@ public class Cache
|
|||||||
// the scheduler that should always be used when running a scheduled task.
|
// the scheduler that should always be used when running a scheduled task.
|
||||||
private static final ScheduledExecutorService taskScheduler = Executors.newSingleThreadScheduledExecutor(); // todo: try-with-resources
|
private static final ScheduledExecutorService taskScheduler = Executors.newSingleThreadScheduledExecutor(); // todo: try-with-resources
|
||||||
|
|
||||||
private static final String execPath = System.getProperty("user.dir");
|
private static final String EXEC_PATH = System.getProperty("user.dir");
|
||||||
private static final String botName = "Hideko";
|
private static final String BOT_NAME = "Hideko";
|
||||||
|
|
||||||
private static SlashCommandListener slashCommandListener = null;
|
private static SlashCommandListener slashCommandListener = null;
|
||||||
private static SlashCommandCompletionListener slashCommandCompletionListener = null;
|
private static SlashCommandCompletionListener slashCommandCompletionListener = null;
|
||||||
private static MessageCommandListener messageCommandListener = null;
|
private static MessageCommandListener messageCommandListener = null;
|
||||||
|
|
||||||
private static final String defaultInviteLink =
|
private static final String DEFAULT_INVITE_LINK =
|
||||||
"https://discord.com/api/oauth2/authorize?client_id=%userid%&scope=bot+applications.commands&permissions=8";
|
"https://discord.com/api/oauth2/authorize?client_id=%userid%&scope=bot+applications.commands&permissions=8";
|
||||||
|
|
||||||
private static String botApplicationId = "";
|
private static String botApplicationId = "";
|
||||||
@@ -74,7 +79,10 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return array of supported resolutions.
|
* @return array of supported resolutions.
|
||||||
*/
|
*/
|
||||||
public static int[] getSupportedAvatarResolutions() { return supportedAvatarResolutions; }
|
public static int[] getSupportedAvatarResolutions()
|
||||||
|
{
|
||||||
|
return supportedAvatarResolutions;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,7 +90,10 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return a boolean which is true if the bot is in verbose-mode
|
* @return a boolean which is true if the bot is in verbose-mode
|
||||||
*/
|
*/
|
||||||
public static synchronized boolean isVerbose() { return verbose; }
|
public static synchronized boolean isVerbose()
|
||||||
|
{
|
||||||
|
return verbose;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the bot's verbosity status at runtime.
|
* Set the bot's verbosity status at runtime.
|
||||||
@@ -94,20 +105,16 @@ public class Cache
|
|||||||
{
|
{
|
||||||
verbose = v;
|
verbose = v;
|
||||||
|
|
||||||
if(v)
|
|
||||||
{
|
|
||||||
if(verbosityLogger == null)
|
|
||||||
{
|
|
||||||
verbosityLogger = new MessageLogger();
|
|
||||||
}
|
|
||||||
|
|
||||||
HidekoBot.getAPI().addEventListener(verbosityLogger);
|
|
||||||
} else {
|
|
||||||
if (verbosityLogger != null)
|
if (verbosityLogger != null)
|
||||||
{
|
{
|
||||||
HidekoBot.getAPI().removeEventListener(verbosityLogger);
|
HidekoBot.getAPI().removeEventListener(verbosityLogger);
|
||||||
verbosityLogger = null;
|
verbosityLogger = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (v)
|
||||||
|
{
|
||||||
|
verbosityLogger = new MessageLogger();
|
||||||
|
HidekoBot.getAPI().addEventListener(verbosityLogger);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,7 +123,8 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return a long of the account's id
|
* @return a long of the account's id
|
||||||
*/
|
*/
|
||||||
public static long getBotOwnerId() {
|
public static long getBotOwnerId()
|
||||||
|
{
|
||||||
return configurationSource == null ? 0L : (Long) configurationSource.getConfigValue(ConfigurationEntry.BOT_OWNER_ID);
|
return configurationSource == null ? 0L : (Long) configurationSource.getConfigValue(ConfigurationEntry.BOT_OWNER_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +134,8 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return a String of the bot's token.
|
* @return a String of the bot's token.
|
||||||
*/
|
*/
|
||||||
public static String getBotToken() {
|
public static String getBotToken()
|
||||||
|
{
|
||||||
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_TOKEN);
|
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_TOKEN);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,7 +146,10 @@ public class Cache
|
|||||||
* @return a long of the account's id
|
* @return a long of the account's id
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public static long getBotMaintainerId() { return botMaintainerId; }
|
public static long getBotMaintainerId()
|
||||||
|
{
|
||||||
|
return BOT_MAINTAINER_ID;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the bot's application id.
|
* Set the bot's application id.
|
||||||
@@ -154,15 +166,19 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return a string of the bot's application id
|
* @return a string of the bot's application id
|
||||||
*/
|
*/
|
||||||
public static String getBotApplicationId() { return botApplicationId; }
|
public static String getBotApplicationId()
|
||||||
|
{
|
||||||
|
return botApplicationId;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Function to generate an invite link for the bot
|
* Function to generate an invite link for the bot
|
||||||
*
|
*
|
||||||
* @return a string containing the invite link
|
* @return a string containing the invite link
|
||||||
*/
|
*/
|
||||||
public static String getInviteUrl() {
|
public static String getInviteUrl()
|
||||||
return defaultInviteLink.replace("%userid%", botApplicationId);
|
{
|
||||||
|
return DEFAULT_INVITE_LINK.replace("%userid%", botApplicationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -180,7 +196,10 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return the DatabaseSource instance.
|
* @return the DatabaseSource instance.
|
||||||
*/
|
*/
|
||||||
public static @Nullable DatabaseSource getDatabaseSource() { return databaseSource; }
|
public static @Nullable DatabaseSource getDatabaseSource()
|
||||||
|
{
|
||||||
|
return databaseSource;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the properties source instance loaded from the JAR archive.
|
* Set the properties source instance loaded from the JAR archive.
|
||||||
@@ -197,42 +216,66 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return the String of the DateTimeFormatter format.
|
* @return the String of the DateTimeFormatter format.
|
||||||
*/
|
*/
|
||||||
public static String getExpiryTimestampFormat(){ return expiryTimestampFormat; }
|
public static String getExpiryTimestampFormat()
|
||||||
|
{
|
||||||
|
return EXPIRY_TIMESTAMP_FORMAT;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the amount of seconds after which a message expires.
|
* Get the amount of seconds after which a message expires.
|
||||||
*
|
*
|
||||||
* @return long value of the expiry seconds.
|
* @return long value of the expiry seconds.
|
||||||
*/
|
*/
|
||||||
public static long getExpiryTimeSeconds() { return expiryTimeSeconds; }
|
public static long getExpiryTimeSeconds()
|
||||||
|
{
|
||||||
|
return EXPIRY_TIME_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static String getBotName() { return botName; }
|
public static String getBotName()
|
||||||
|
{
|
||||||
|
return BOT_NAME;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the bot's version.
|
* Get the bot's version.
|
||||||
*
|
*
|
||||||
* @return a String of the bot version.
|
* @return a String of the bot version.
|
||||||
*/
|
*/
|
||||||
public static String getBotVersion() {
|
public static String getBotVersion()
|
||||||
|
{
|
||||||
return propertiesSource.getProperty("bot.version");
|
return propertiesSource.getProperty("bot.version");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the bot's source code URL.
|
||||||
|
*
|
||||||
|
* @return a String containing the base URL of the repository, including a <b>trailing slash</b>.
|
||||||
|
*/
|
||||||
|
public static String getRepositoryUrl()
|
||||||
|
{
|
||||||
|
String url = propertiesSource.getProperty("repo.base_url");
|
||||||
|
return url.endsWith("/") ? url : url + "/";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the bot's global color.
|
* Get the bot's global color.
|
||||||
*
|
*
|
||||||
* @return the Color object.
|
* @return the Color object.
|
||||||
*/
|
*/
|
||||||
public static Color getBotColor() {
|
public static Color getBotColor()
|
||||||
|
{
|
||||||
Color defaultColor = Color.PINK;
|
Color defaultColor = Color.PINK;
|
||||||
if (configurationSource == null) return defaultColor;
|
if (configurationSource == null) return defaultColor;
|
||||||
String colorName = (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_COLOR);
|
String colorName = (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_COLOR);
|
||||||
|
|
||||||
Color color = null;
|
Color color = null;
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
Field field = Color.class.getField(colorName);
|
Field field = Color.class.getField(colorName);
|
||||||
color = (Color) field.get(null);
|
color = (Color) field.get(null);
|
||||||
} catch (RuntimeException | NoSuchFieldException | IllegalAccessException e) {
|
} catch (RuntimeException | NoSuchFieldException | IllegalAccessException e)
|
||||||
|
{
|
||||||
LOGGER.error("Unknown color: {}", colorName);
|
LOGGER.error("Unknown color: {}", colorName);
|
||||||
}
|
}
|
||||||
return color == null ? defaultColor : color;
|
return color == null ? defaultColor : color;
|
||||||
@@ -241,21 +284,36 @@ public class Cache
|
|||||||
|
|
||||||
//todo javadocs
|
//todo javadocs
|
||||||
public static void setSlashCommandListener(SlashCommandListener commandListener)
|
public static void setSlashCommandListener(SlashCommandListener commandListener)
|
||||||
{ slashCommandListener = commandListener; }
|
{
|
||||||
|
slashCommandListener = commandListener;
|
||||||
|
}
|
||||||
|
|
||||||
public static SlashCommandListener getSlashCommandListener() { return slashCommandListener; }
|
public static SlashCommandListener getSlashCommandListener()
|
||||||
|
{
|
||||||
|
return slashCommandListener;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void setSlashCommandCompletionListener(SlashCommandCompletionListener commandCompletionListener)
|
public static void setSlashCommandCompletionListener(SlashCommandCompletionListener commandCompletionListener)
|
||||||
{ slashCommandCompletionListener = commandCompletionListener; }
|
{
|
||||||
|
slashCommandCompletionListener = commandCompletionListener;
|
||||||
|
}
|
||||||
|
|
||||||
public static SlashCommandCompletionListener getSlashCommandCompletionListener() { return slashCommandCompletionListener; }
|
public static SlashCommandCompletionListener getSlashCommandCompletionListener()
|
||||||
|
{
|
||||||
|
return slashCommandCompletionListener;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void setMessageCommandListener(MessageCommandListener commandListener)
|
public static void setMessageCommandListener(MessageCommandListener commandListener)
|
||||||
{ messageCommandListener = commandListener; }
|
{
|
||||||
|
messageCommandListener = commandListener;
|
||||||
|
}
|
||||||
|
|
||||||
public static MessageCommandListener getMessageCommandListener() { return messageCommandListener; }
|
public static MessageCommandListener getMessageCommandListener()
|
||||||
|
{
|
||||||
|
return messageCommandListener;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the bot's startup time. Generally only used at boot time.
|
* Set the bot's startup time. Generally only used at boot time.
|
||||||
@@ -263,7 +321,9 @@ public class Cache
|
|||||||
* @param time a LocalDateTime of the startup moment.
|
* @param time a LocalDateTime of the startup moment.
|
||||||
*/
|
*/
|
||||||
public static void setStartupTime(LocalDateTime time)
|
public static void setStartupTime(LocalDateTime time)
|
||||||
{ startupTime = time; }
|
{
|
||||||
|
startupTime = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -271,37 +331,54 @@ public class Cache
|
|||||||
*
|
*
|
||||||
* @return a LocalDateTime object of the startup instant.
|
* @return a LocalDateTime object of the startup instant.
|
||||||
*/
|
*/
|
||||||
public static LocalDateTime getStartupTime() { return startupTime; }
|
public static LocalDateTime getStartupTime()
|
||||||
|
{
|
||||||
|
return startupTime;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the time of when the bot was created.
|
* Get the time of when the bot was created.
|
||||||
*
|
*
|
||||||
* @return a LocalDateTime object of the first commit's instant.
|
* @return a LocalDateTime object of the first commit's instant.
|
||||||
*/
|
*/
|
||||||
public static LocalDateTime getBotBirthDate() { return botBirthDate; }
|
public static LocalDateTime getBotBirthDate()
|
||||||
|
{
|
||||||
|
return botBirthDate;
|
||||||
|
}
|
||||||
|
|
||||||
public static String getFullHeartBeatLink() {
|
public static String getFullHeartBeatLink()
|
||||||
|
{
|
||||||
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.HEARTBEAT_LINK);
|
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.HEARTBEAT_LINK);
|
||||||
}
|
}
|
||||||
|
|
||||||
//todo javadocs
|
//todo javadocs
|
||||||
public static String getExecPath() { return execPath; }
|
public static String getExecPath()
|
||||||
|
{
|
||||||
|
return EXEC_PATH;
|
||||||
|
}
|
||||||
|
|
||||||
/*private static ConfigurationSource getConfigurationSource()
|
/*private static ConfigurationSource getConfigurationSource()
|
||||||
{ return configurationSource; }*/
|
{ return configurationSource; }*/
|
||||||
|
|
||||||
public static String getRandomOrgApiKey() {
|
public static String getRandomOrgApiKey()
|
||||||
|
{
|
||||||
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.RANDOM_ORG_API_KEY);
|
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.RANDOM_ORG_API_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setConfigurationSource(ConfigurationSource configurationSource)
|
public static void setConfigurationSource(ConfigurationSource configurationSource)
|
||||||
{ Cache.configurationSource = configurationSource; }
|
{
|
||||||
|
Cache.configurationSource = configurationSource;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the bot's prefix
|
* Get the bot's prefix
|
||||||
*
|
*
|
||||||
* @return a String of the bot's prefix.
|
* @return a String of the bot's prefix.
|
||||||
*/
|
*/
|
||||||
public static String getBotPrefix() { return botPrefix; }
|
public static String getBotPrefix()
|
||||||
|
{
|
||||||
|
return BOT_PREFIX;
|
||||||
|
}
|
||||||
|
|
||||||
public static void cacheLoveCalculatorValue(String userId1, String userId2, int value)
|
public static void cacheLoveCalculatorValue(String userId1, String userId2, int value)
|
||||||
{
|
{
|
||||||
@@ -326,7 +403,8 @@ public class Cache
|
|||||||
loveCalculatorValues.remove(userId2 + "|" + userId1);
|
loveCalculatorValues.remove(userId2 + "|" + userId1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ScheduledExecutorService getTaskScheduler() {
|
public static ScheduledExecutorService getTaskScheduler()
|
||||||
|
{
|
||||||
return taskScheduler;
|
return taskScheduler;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import net.dv8tion.jda.api.OnlineStatus;
|
|||||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import sun.misc.Signal;
|
|
||||||
import wtf.beatrice.hidekobot.commands.completer.ProfileImageCommandCompleter;
|
import wtf.beatrice.hidekobot.commands.completer.ProfileImageCommandCompleter;
|
||||||
import wtf.beatrice.hidekobot.commands.message.HelloCommand;
|
import wtf.beatrice.hidekobot.commands.message.HelloCommand;
|
||||||
import wtf.beatrice.hidekobot.commands.slash.*;
|
import wtf.beatrice.hidekobot.commands.slash.*;
|
||||||
@@ -77,12 +76,12 @@ public class HidekoBot
|
|||||||
);
|
);
|
||||||
|
|
||||||
jda = jdaBuilder.build().awaitReady();
|
jda = jdaBuilder.build().awaitReady();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e)
|
||||||
|
{
|
||||||
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
|
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
|
||||||
Thread.currentThread().interrupt(); // send interrupt to the thread.
|
Thread.currentThread().interrupt(); // send interrupt to the thread.
|
||||||
shutdown(); // if we failed connecting and authenticating, then quit.
|
shutdown(); // if we failed connecting and authenticating, then quit.
|
||||||
}
|
} catch (Exception e)
|
||||||
catch (Exception e)
|
|
||||||
{
|
{
|
||||||
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
|
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
|
||||||
shutdown(); // if we failed connecting and authenticating, then quit.
|
shutdown(); // if we failed connecting and authenticating, then quit.
|
||||||
@@ -95,9 +94,10 @@ public class HidekoBot
|
|||||||
// store if we have to force refresh commands despite no apparent changes.
|
// store if we have to force refresh commands despite no apparent changes.
|
||||||
boolean forceUpdateCommands = false;
|
boolean forceUpdateCommands = false;
|
||||||
|
|
||||||
// if there is more than 1 arg, then iterate through them because we have additional things to do.
|
// if there is at least one arg, then iterate through them because we have additional things to do.
|
||||||
// we are doing this at the end because we might need the API to be already initialized for some things.
|
// we are doing this at the end because we might need the API to be already initialized for some things.
|
||||||
if(args.length > 1) {
|
if (args.length > 0)
|
||||||
|
{
|
||||||
List<String> argsList = new ArrayList<>(Arrays.asList(args));
|
List<String> argsList = new ArrayList<>(Arrays.asList(args));
|
||||||
|
|
||||||
|
|
||||||
@@ -188,8 +188,11 @@ public class HidekoBot
|
|||||||
|
|
||||||
// update slash commands (delayed)
|
// update slash commands (delayed)
|
||||||
final boolean finalForceUpdateCommands = forceUpdateCommands;
|
final boolean finalForceUpdateCommands = forceUpdateCommands;
|
||||||
Executors.newSingleThreadScheduledExecutor().schedule(() -> // todo: try-with-resources
|
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
|
||||||
CommandUtil.updateSlashCommands(finalForceUpdateCommands), 1, TimeUnit.SECONDS);
|
{
|
||||||
|
executor.schedule(() -> CommandUtil.updateSlashCommands(finalForceUpdateCommands),
|
||||||
|
1, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
// set the bot's status
|
// set the bot's status
|
||||||
jda.getPresence().setStatus(OnlineStatus.ONLINE);
|
jda.getPresence().setStatus(OnlineStatus.ONLINE);
|
||||||
@@ -206,7 +209,8 @@ public class HidekoBot
|
|||||||
// load data here...
|
// load data here...
|
||||||
|
|
||||||
LOGGER.info("Database data loaded into memory!");
|
LOGGER.info("Database data loaded into memory!");
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
LOGGER.error("Error initializing database connection!");
|
LOGGER.error("Error initializing database connection!");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +229,7 @@ public class HidekoBot
|
|||||||
}
|
}
|
||||||
|
|
||||||
// register shutdown interrupt signal listener for proper shutdown.
|
// register shutdown interrupt signal listener for proper shutdown.
|
||||||
Signal.handle(new Signal("INT"), signal -> shutdown());
|
Runtime.getRuntime().addShutdownHook(new Thread(HidekoBot::preShutdown));
|
||||||
|
|
||||||
// set startup time.
|
// set startup time.
|
||||||
Cache.setStartupTime(LocalDateTime.now());
|
Cache.setStartupTime(LocalDateTime.now());
|
||||||
@@ -239,6 +243,7 @@ public class HidekoBot
|
|||||||
LOGGER.info("Invite Link: {}", Cache.getInviteUrl());
|
LOGGER.info("Invite Link: {}", Cache.getInviteUrl());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JDA getAPI()
|
public static JDA getAPI()
|
||||||
{
|
{
|
||||||
return jda;
|
return jda;
|
||||||
@@ -246,9 +251,14 @@ public class HidekoBot
|
|||||||
|
|
||||||
public static void shutdown()
|
public static void shutdown()
|
||||||
{
|
{
|
||||||
LOGGER.warn("WARNING! Shutting down!");
|
preShutdown();
|
||||||
if(jda != null) jda.shutdown();
|
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void preShutdown()
|
||||||
|
{
|
||||||
|
LOGGER.warn("WARNING! Shutting down!");
|
||||||
|
if (jda != null) jda.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import java.util.LinkedList;
|
|||||||
|
|
||||||
public class Alias
|
public class Alias
|
||||||
{
|
{
|
||||||
|
private Alias()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static String generateNiceAliases(MessageCommand command)
|
public static String generateNiceAliases(MessageCommand command)
|
||||||
{
|
{
|
||||||
LinkedList<String> aliases = command.getCommandLabels();
|
LinkedList<String> aliases = command.getCommandLabels();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import net.dv8tion.jda.api.entities.MessageEmbed;
|
|||||||
import wtf.beatrice.hidekobot.Cache;
|
import wtf.beatrice.hidekobot.Cache;
|
||||||
import wtf.beatrice.hidekobot.HidekoBot;
|
import wtf.beatrice.hidekobot.HidekoBot;
|
||||||
import wtf.beatrice.hidekobot.util.FormatUtil;
|
import wtf.beatrice.hidekobot.util.FormatUtil;
|
||||||
|
import wtf.beatrice.hidekobot.util.RandomUtil;
|
||||||
|
|
||||||
import java.lang.management.ManagementFactory;
|
import java.lang.management.ManagementFactory;
|
||||||
import java.text.DecimalFormat;
|
import java.text.DecimalFormat;
|
||||||
@@ -12,6 +13,11 @@ import java.util.List;
|
|||||||
|
|
||||||
public class BotInfo
|
public class BotInfo
|
||||||
{
|
{
|
||||||
|
private BotInfo()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static MessageEmbed generateEmbed(List<String> commandLabels)
|
public static MessageEmbed generateEmbed(List<String> commandLabels)
|
||||||
{
|
{
|
||||||
EmbedBuilder embedBuilder = new EmbedBuilder();
|
EmbedBuilder embedBuilder = new EmbedBuilder();
|
||||||
@@ -48,25 +54,38 @@ public class BotInfo
|
|||||||
// keep track of how many total commands we have
|
// keep track of how many total commands we have
|
||||||
int commandsCount = 0;
|
int commandsCount = 0;
|
||||||
|
|
||||||
// message commands info fields
|
// message commands info field
|
||||||
StringBuilder messageCommandsInfoBuilder = new StringBuilder();
|
String messageCommandsInfo;
|
||||||
if (Cache.getMessageCommandListener() == null)
|
if (Cache.getMessageCommandListener() == null)
|
||||||
messageCommandsInfoBuilder.append("❌ disabled");
|
messageCommandsInfo = "❌ disabled";
|
||||||
else {
|
else
|
||||||
messageCommandsInfoBuilder.append("✅ available");
|
{
|
||||||
|
messageCommandsInfo = "✅ available";
|
||||||
commandsCount += Cache.getMessageCommandListener().getRegisteredCommands().size();
|
commandsCount += Cache.getMessageCommandListener().getRegisteredCommands().size();
|
||||||
}
|
}
|
||||||
embedBuilder.addField("Message commands", messageCommandsInfoBuilder.toString(), true);
|
embedBuilder.addField("Message commands", messageCommandsInfo, true);
|
||||||
|
|
||||||
// slash commands info fields
|
// slash commands info field
|
||||||
StringBuilder slashCommandsInfoBuilder = new StringBuilder();
|
String slashCommandsInfo;
|
||||||
if (Cache.getMessageCommandListener() == null)
|
if (Cache.getMessageCommandListener() == null)
|
||||||
slashCommandsInfoBuilder.append("❌ disabled");
|
slashCommandsInfo = "❌ disabled";
|
||||||
else {
|
else
|
||||||
slashCommandsInfoBuilder.append("✅ available");
|
{
|
||||||
|
slashCommandsInfo = "✅ available";
|
||||||
commandsCount += Cache.getSlashCommandListener().getRegisteredCommands().size();
|
commandsCount += Cache.getSlashCommandListener().getRegisteredCommands().size();
|
||||||
}
|
}
|
||||||
embedBuilder.addField("Slash commands", slashCommandsInfoBuilder.toString(), true);
|
embedBuilder.addField("Slash commands", slashCommandsInfo, true);
|
||||||
|
|
||||||
|
// random.org integration field
|
||||||
|
String randomOrgInfo;
|
||||||
|
if (RandomUtil.isRandomOrgKeyValid())
|
||||||
|
{
|
||||||
|
randomOrgInfo = "✅ connected";
|
||||||
|
} else
|
||||||
|
{
|
||||||
|
randomOrgInfo = "❌ disabled";
|
||||||
|
}
|
||||||
|
embedBuilder.addField("Random.org", randomOrgInfo, true);
|
||||||
|
|
||||||
// commands count fields
|
// commands count fields
|
||||||
embedBuilder.addField("Total commands", "Loaded: `" + commandsCount + "`", true);
|
embedBuilder.addField("Total commands", "Loaded: `" + commandsCount + "`", true);
|
||||||
@@ -94,9 +113,10 @@ public class BotInfo
|
|||||||
embedBuilder.addField("Uptime", FormatUtil.getNiceTimeDiff(Cache.getStartupTime()), true);
|
embedBuilder.addField("Uptime", FormatUtil.getNiceTimeDiff(Cache.getStartupTime()), true);
|
||||||
|
|
||||||
// issue tracker field
|
// issue tracker field
|
||||||
|
|
||||||
|
String link = "[Issue tracker](" + Cache.getRepositoryUrl() + "issues)";
|
||||||
embedBuilder.addField("Support",
|
embedBuilder.addField("Support",
|
||||||
"[Issue tracker](https://git.beatrice.wtf/mind-overflow/HidekoBot/issues)",
|
link, true);
|
||||||
true); //todo: we should probably make this a final field in the config class
|
|
||||||
|
|
||||||
// bot birthday field
|
// bot birthday field
|
||||||
embedBuilder.addField("Bot age",
|
embedBuilder.addField("Bot age",
|
||||||
|
|||||||
@@ -14,23 +14,32 @@ import java.util.List;
|
|||||||
|
|
||||||
public class ClearChat
|
public class ClearChat
|
||||||
{
|
{
|
||||||
|
private ClearChat()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static String getLabel() {
|
public static String getLabel()
|
||||||
|
{
|
||||||
return "clear";
|
return "clear";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getDescription() {
|
public static String getDescription()
|
||||||
|
{
|
||||||
return "Clear the current channel's chat.";
|
return "Clear the current channel's chat.";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Permission getPermission() {
|
public static Permission getPermission()
|
||||||
|
{
|
||||||
return Permission.MESSAGE_MANAGE;
|
return Permission.MESSAGE_MANAGE;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String checkDMs(Channel channel)
|
public static String checkDMs(Channel channel)
|
||||||
{
|
{
|
||||||
if (!(channel instanceof TextChannel))
|
if (!(channel instanceof TextChannel))
|
||||||
{ return "\uD83D\uDE22 Sorry! I can't delete messages here."; }
|
{
|
||||||
|
return "\uD83D\uDE22 Sorry! I can't delete messages here.";
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -38,7 +47,9 @@ public class ClearChat
|
|||||||
public static String checkDeleteAmount(int toDeleteAmount)
|
public static String checkDeleteAmount(int toDeleteAmount)
|
||||||
{
|
{
|
||||||
if (toDeleteAmount <= 0)
|
if (toDeleteAmount <= 0)
|
||||||
{ return "\uD83D\uDE22 Sorry, I can't delete that amount of messages!"; }
|
{
|
||||||
|
return "\uD83D\uDE22 Sorry, I can't delete that amount of messages!";
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -78,11 +89,10 @@ public class ClearChat
|
|||||||
// set how many messages to delete for this iteration (usually <limit> unless there's a remainder)
|
// set how many messages to delete for this iteration (usually <limit> unless there's a remainder)
|
||||||
int iterationSize = limit;
|
int iterationSize = limit;
|
||||||
|
|
||||||
// if we are at the last iteration...
|
// if we are at the last iteration... check if we have <limit> or fewer messages to delete
|
||||||
if(iteration+1 == iterations)
|
if (iteration + 1 == iterations && remainder != 0)
|
||||||
{
|
{
|
||||||
// check if we have <limit> or fewer messages to delete
|
iterationSize = remainder;
|
||||||
if(remainder != 0) iterationSize = remainder;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (iterationSize == 1)
|
if (iterationSize == 1)
|
||||||
@@ -94,7 +104,8 @@ public class ClearChat
|
|||||||
else outOfBounds = true;
|
else outOfBounds = true;
|
||||||
// increase deleted counter by 1
|
// increase deleted counter by 1
|
||||||
deleted++;
|
deleted++;
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
// get the last <iterationSize - 1> messages.
|
// get the last <iterationSize - 1> messages.
|
||||||
MessageHistory.MessageRetrieveAction action = channel.getHistoryBefore(messageId, iterationSize - 1);
|
MessageHistory.MessageRetrieveAction action = channel.getHistoryBefore(messageId, iterationSize - 1);
|
||||||
// note: first one is the most recent, last one is the oldest message.
|
// note: first one is the most recent, last one is the oldest message.
|
||||||
@@ -107,25 +118,26 @@ public class ClearChat
|
|||||||
if (messages.size() <= 1)
|
if (messages.size() <= 1)
|
||||||
{
|
{
|
||||||
outOfBounds = true;
|
outOfBounds = true;
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
// before deleting, we need to grab the <previous to the oldest> message's id for next iteration.
|
// before deleting, we need to grab the <previous to the oldest> message's id for next iteration.
|
||||||
action = channel.getHistoryBefore(messages.get(messages.size() - 1).getIdLong(), 1);
|
action = channel.getHistoryBefore(messages.getLast().getIdLong(), 1);
|
||||||
|
|
||||||
List<Message> previousMessage = action.complete().getRetrievedHistory();
|
List<Message> previousMessage = action.complete().getRetrievedHistory();
|
||||||
|
|
||||||
// if that message exists (we are not out of bounds)... store it
|
// if that message exists (we are not out of bounds)... store it
|
||||||
if(!previousMessage.isEmpty()) messageId = previousMessage.get(0).getIdLong();
|
if (!previousMessage.isEmpty()) messageId = previousMessage.getFirst().getIdLong();
|
||||||
else outOfBounds = true;
|
else outOfBounds = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// queue messages for deletion
|
// queue messages for deletion
|
||||||
if (messages.size() == 1)
|
if (messages.size() == 1)
|
||||||
{
|
{
|
||||||
messages.get(0).delete().queue();
|
messages.getFirst().delete().queue();
|
||||||
}
|
} else if (!messages.isEmpty())
|
||||||
else if(!messages.isEmpty())
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
((TextChannel) channel).deleteMessages(messages).complete();
|
((TextChannel) channel).deleteMessages(messages).complete();
|
||||||
/* alternatively, we could use purgeMessages, which is smarter...
|
/* alternatively, we could use purgeMessages, which is smarter...
|
||||||
however, it also tries to delete messages older than 2 weeks
|
however, it also tries to delete messages older than 2 weeks
|
||||||
@@ -161,12 +173,16 @@ public class ClearChat
|
|||||||
} else if (deleted == 1)
|
} else if (deleted == 1)
|
||||||
{
|
{
|
||||||
return "✂ Cleared 1 message!";
|
return "✂ Cleared 1 message!";
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
return "✂ Cleared " + deleted + " messages!";
|
return "✂ Cleared " + deleted + " messages!";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// cap the amount to avoid abuse.
|
// cap the amount to avoid abuse.
|
||||||
public static int getMaxAmount() { return 1000; }
|
public static int getMaxAmount()
|
||||||
|
{
|
||||||
|
return 1000;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,8 +14,13 @@ import java.util.List;
|
|||||||
public class CoinFlip
|
public class CoinFlip
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private CoinFlip()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static Button getReflipButton() {
|
public static Button getReflipButton()
|
||||||
|
{
|
||||||
return Button.primary("coinflip_reflip", "Flip again")
|
return Button.primary("coinflip_reflip", "Flip again")
|
||||||
.withEmoji(Emoji.fromUnicode("\uD83E\uDE99"));
|
.withEmoji(Emoji.fromUnicode("\uD83E\uDE99"));
|
||||||
}
|
}
|
||||||
@@ -28,7 +33,8 @@ public class CoinFlip
|
|||||||
if (rand == 1)
|
if (rand == 1)
|
||||||
{
|
{
|
||||||
msg = ":coin: It's **Heads**!";
|
msg = ":coin: It's **Heads**!";
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
msg = "It's **Tails**! :coin:";
|
msg = "It's **Tails**! :coin:";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +62,8 @@ public class CoinFlip
|
|||||||
{
|
{
|
||||||
// set the command as expiring and restrict it to the user who ran it
|
// set the command as expiring and restrict it to the user who ran it
|
||||||
trackAndRestrict(message, event.getUser());
|
trackAndRestrict(message, event.getUser());
|
||||||
}, (error) -> {});
|
}, (error) -> {
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void trackAndRestrict(Message replyMessage, User user)
|
public static void trackAndRestrict(Message replyMessage, User user)
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public class DiceRoll
|
public class DiceRoll
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private DiceRoll()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static MessageResponse buildResponse(User author, String[] args)
|
public static MessageResponse buildResponse(User author, String[] args)
|
||||||
{
|
{
|
||||||
LinkedHashMap<Dice, Integer> dicesToRoll = new LinkedHashMap<>();
|
LinkedHashMap<Dice, Integer> dicesToRoll = new LinkedHashMap<>();
|
||||||
@@ -39,7 +45,8 @@ public class DiceRoll
|
|||||||
if (currentDice == null)
|
if (currentDice == null)
|
||||||
{
|
{
|
||||||
currentDice = new Dice(6);
|
currentDice = new Dice(6);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
currentDice = new Dice(currentDice);
|
currentDice = new Dice(currentDice);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,8 +58,7 @@ public class DiceRoll
|
|||||||
lastPushedDice = currentDice.getUUID();
|
lastPushedDice = currentDice.getUUID();
|
||||||
dicesToRoll.put(currentDice, currentAmount);
|
dicesToRoll.put(currentDice, currentAmount);
|
||||||
totalRolls += currentAmount;
|
totalRolls += currentAmount;
|
||||||
}
|
} else if (arg.matches(diceRegex))
|
||||||
else if(arg.matches(diceRegex))
|
|
||||||
{
|
{
|
||||||
int sides = Integer.parseInt(arg.substring(1));
|
int sides = Integer.parseInt(arg.substring(1));
|
||||||
|
|
||||||
@@ -133,13 +139,16 @@ public class DiceRoll
|
|||||||
int total = 0;
|
int total = 0;
|
||||||
|
|
||||||
int previousDiceSides = 0;
|
int previousDiceSides = 0;
|
||||||
for (Dice dice : rolledDices) {
|
for (Dice dice : rolledDices)
|
||||||
|
{
|
||||||
int diceSize = dice.getSides();
|
int diceSize = dice.getSides();
|
||||||
|
|
||||||
if (previousDiceSides != diceSize) {
|
if (previousDiceSides != diceSize)
|
||||||
|
{
|
||||||
message.append("\nd").append(diceSize).append(": ");
|
message.append("\nd").append(diceSize).append(": ");
|
||||||
previousDiceSides = diceSize;
|
previousDiceSides = diceSize;
|
||||||
} else if (previousDiceSides != 0) {
|
} else if (previousDiceSides != 0)
|
||||||
|
{
|
||||||
message.append(", ");
|
message.append(", ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ import wtf.beatrice.hidekobot.HidekoBot;
|
|||||||
public class Invite
|
public class Invite
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private Invite()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static MessageEmbed generateEmbed()
|
public static MessageEmbed generateEmbed()
|
||||||
{
|
{
|
||||||
EmbedBuilder embedBuilder = new EmbedBuilder();
|
EmbedBuilder embedBuilder = new EmbedBuilder();
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
public class LoveCalculator
|
public class LoveCalculator
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private LoveCalculator()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static MessageEmbed buildEmbedAndCacheResult(User author, User user1, User user2)
|
public static MessageEmbed buildEmbedAndCacheResult(User author, User user1, User user2)
|
||||||
{
|
{
|
||||||
String userId1 = user1.getId();
|
String userId1 = user1.getId();
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ import java.util.List;
|
|||||||
public class MagicBall
|
public class MagicBall
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private MagicBall()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static LinkedList<String> getLabels()
|
public static LinkedList<String> getLabels()
|
||||||
{
|
{
|
||||||
return new LinkedList<>(Arrays.asList("8ball", "8b", "eightball", "magicball"));
|
return new LinkedList<>(Arrays.asList("8ball", "8b", "eightball", "magicball"));
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ import wtf.beatrice.hidekobot.objects.MessageResponse;
|
|||||||
|
|
||||||
public class ProfileImage
|
public class ProfileImage
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private ProfileImage()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static int parseResolution(int resolution)
|
public static int parseResolution(int resolution)
|
||||||
{
|
{
|
||||||
int[] acceptedSizes = Cache.getSupportedAvatarResolutions();
|
int[] acceptedSizes = Cache.getSupportedAvatarResolutions();
|
||||||
@@ -15,9 +21,11 @@ public class ProfileImage
|
|||||||
// method to find closest value to accepted values
|
// method to find closest value to accepted values
|
||||||
int distance = Math.abs(acceptedSizes[0] - resolution);
|
int distance = Math.abs(acceptedSizes[0] - resolution);
|
||||||
int idx = 0;
|
int idx = 0;
|
||||||
for(int c = 1; c < acceptedSizes.length; c++){
|
for (int c = 1; c < acceptedSizes.length; c++)
|
||||||
|
{
|
||||||
int cdistance = Math.abs(acceptedSizes[c] - resolution);
|
int cdistance = Math.abs(acceptedSizes[c] - resolution);
|
||||||
if(cdistance < distance){
|
if (cdistance < distance)
|
||||||
|
{
|
||||||
idx = c;
|
idx = c;
|
||||||
distance = cdistance;
|
distance = cdistance;
|
||||||
}
|
}
|
||||||
@@ -39,7 +47,8 @@ public class ProfileImage
|
|||||||
{
|
{
|
||||||
resolutionString = resolution + " × " + resolution;
|
resolutionString = resolution + " × " + resolution;
|
||||||
imageLink = user.getEffectiveAvatar().getUrl(resolution);
|
imageLink = user.getEffectiveAvatar().getUrl(resolution);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
int verticalRes = 361 * resolution / 1024;
|
int verticalRes = 361 * resolution / 1024;
|
||||||
resolutionString = resolution + " × " + verticalRes;
|
resolutionString = resolution + " × " + verticalRes;
|
||||||
if (bannerProxy != null)
|
if (bannerProxy != null)
|
||||||
@@ -67,7 +76,8 @@ public class ProfileImage
|
|||||||
if (imageType == ImageType.AVATAR)
|
if (imageType == ImageType.AVATAR)
|
||||||
{
|
{
|
||||||
currLink = user.getEffectiveAvatar().getUrl(currSize);
|
currLink = user.getEffectiveAvatar().getUrl(currSize);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
if (bannerProxy == null) break;
|
if (bannerProxy == null) break;
|
||||||
currLink = bannerProxy.getUrl(currSize);
|
currLink = bannerProxy.getUrl(currSize);
|
||||||
}
|
}
|
||||||
@@ -82,15 +92,16 @@ public class ProfileImage
|
|||||||
embedBuilder.addField("Available resolutions", links.toString(), false);
|
embedBuilder.addField("Available resolutions", links.toString(), false);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (imageLink != null)
|
if (imageLink != null)
|
||||||
embedBuilder.setImage(imageLink);
|
embedBuilder.setImage(imageLink);
|
||||||
|
|
||||||
|
|
||||||
if(imageLink == null) {
|
if (imageLink == null)
|
||||||
|
{
|
||||||
String error = "I couldn't find " + user.getAsMention() + "'s " + imageTypeName + "!";
|
String error = "I couldn't find " + user.getAsMention() + "'s " + imageTypeName + "!";
|
||||||
return new MessageResponse(error, null);
|
return new MessageResponse(error, null);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
return new MessageResponse(null, embedBuilder.build());
|
return new MessageResponse(null, embedBuilder.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ import net.dv8tion.jda.api.Permission;
|
|||||||
public class Say
|
public class Say
|
||||||
{
|
{
|
||||||
|
|
||||||
public static Permission getPermission() {
|
private Say()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Permission getPermission()
|
||||||
|
{
|
||||||
return Permission.MESSAGE_MANAGE;
|
return Permission.MESSAGE_MANAGE;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,9 +35,15 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
public class Trivia
|
public class Trivia
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private Trivia()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Trivia.class);
|
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Trivia.class);
|
||||||
private static final String triviaLink = "https://opentdb.com/api.php?amount=10&type=multiple&category=";
|
private static final String TRIVIA_API_LINK = "https://opentdb.com/api.php?amount=10&type=multiple&category=";
|
||||||
private static final String categoriesLink = "https://opentdb.com/api_category.php";
|
private static final String TRIVIA_API_CATEGORIES_LINK = "https://opentdb.com/api_category.php";
|
||||||
|
|
||||||
public static List<String> channelsRunningTrivia = new ArrayList<>();
|
public static List<String> channelsRunningTrivia = new ArrayList<>();
|
||||||
|
|
||||||
@@ -47,14 +53,23 @@ public class Trivia
|
|||||||
// first string is the channelId, the list contain all score records for that channel
|
// first string is the channelId, the list contain all score records for that channel
|
||||||
public static HashMap<String, LinkedList<TriviaScore>> channelAndScores = new HashMap<>();
|
public static HashMap<String, LinkedList<TriviaScore>> channelAndScores = new HashMap<>();
|
||||||
|
|
||||||
public static String getTriviaLink(int categoryId) {return triviaLink + categoryId; }
|
public static String getTriviaLink(int categoryId)
|
||||||
public static String getCategoriesLink() {return categoriesLink; }
|
{
|
||||||
|
return TRIVIA_API_LINK + categoryId;
|
||||||
|
}
|
||||||
|
|
||||||
public static String getNoDMsError() {
|
public static String getCategoriesLink()
|
||||||
|
{
|
||||||
|
return TRIVIA_API_CATEGORIES_LINK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getNoDMsError()
|
||||||
|
{
|
||||||
return "\uD83D\uDE22 Sorry! Trivia doesn't work in DMs.";
|
return "\uD83D\uDE22 Sorry! Trivia doesn't work in DMs.";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getTriviaAlreadyRunningError() {
|
public static String getTriviaAlreadyRunningError()
|
||||||
|
{
|
||||||
// todo nicer looking
|
// todo nicer looking
|
||||||
return "Trivia is already running here!";
|
return "Trivia is already running here!";
|
||||||
}
|
}
|
||||||
@@ -97,7 +112,8 @@ public class Trivia
|
|||||||
|
|
||||||
public static JSONObject fetchJson(String link)
|
public static JSONObject fetchJson(String link)
|
||||||
{
|
{
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
URL url = new URL(link);
|
URL url = new URL(link);
|
||||||
URLConnection connection = url.openConnection();
|
URLConnection connection = url.openConnection();
|
||||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
@@ -110,7 +126,8 @@ public class Trivia
|
|||||||
}
|
}
|
||||||
bufferedReader.close();
|
bufferedReader.close();
|
||||||
return new JSONObject(jsonStrBuilder.toString());
|
return new JSONObject(jsonStrBuilder.toString());
|
||||||
} catch (IOException e) {
|
} catch (IOException e)
|
||||||
|
{
|
||||||
LOGGER.error("JSON Parsing Exception", e);
|
LOGGER.error("JSON Parsing Exception", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,14 +210,16 @@ public class Trivia
|
|||||||
event.reply(user.getAsMention() + " got it right! \uD83E\uDD73 (**+3**)").queue();
|
event.reply(user.getAsMention() + " got it right! \uD83E\uDD73 (**+3**)").queue();
|
||||||
currentUserScore.changeScore(3);
|
currentUserScore.changeScore(3);
|
||||||
|
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.reply("❌ " + user.getAsMention() + ", that's not the right answer! (**-1**)").queue();
|
event.reply("❌ " + user.getAsMention() + ", that's not the right answer! (**-1**)").queue();
|
||||||
currentUserScore.changeScore(-1);
|
currentUserScore.changeScore(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
scores.add(currentUserScore);
|
scores.add(currentUserScore);
|
||||||
channelAndScores.put(channelId, scores);
|
channelAndScores.put(channelId, scores);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.reply("☹️ " + user.getAsMention() + ", you can't answer twice!")
|
event.reply("☹️ " + user.getAsMention() + ", you can't answer twice!")
|
||||||
.queue(interaction ->
|
.queue(interaction ->
|
||||||
Cache.getTaskScheduler().schedule(() ->
|
Cache.getTaskScheduler().schedule(() ->
|
||||||
@@ -225,7 +244,8 @@ public class Trivia
|
|||||||
responders.add(userId);
|
responders.add(userId);
|
||||||
channelAndWhoResponded.put(channelId, responders);
|
channelAndWhoResponded.put(channelId, responders);
|
||||||
return true; // response was successfully tracked
|
return true; // response was successfully tracked
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
return false; // response wasn't tracked because there already was an entry
|
return false; // response wasn't tracked because there already was an entry
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,7 +286,8 @@ public class Trivia
|
|||||||
Message err = event.reply("Trivia is already running here!").complete().retrieveOriginal().complete();
|
Message err = event.reply("Trivia is already running here!").complete().retrieveOriginal().complete();
|
||||||
Cache.getTaskScheduler().schedule(() -> err.delete().queue(), 10, TimeUnit.SECONDS);
|
Cache.getTaskScheduler().schedule(() -> err.delete().queue(), 10, TimeUnit.SECONDS);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
// todo nicer looking
|
// todo nicer looking
|
||||||
event.reply("Starting new Trivia session!").queue();
|
event.reply("Starting new Trivia session!").queue();
|
||||||
}
|
}
|
||||||
@@ -283,7 +304,8 @@ public class Trivia
|
|||||||
Trivia.channelsRunningTrivia.add(channel.getId());
|
Trivia.channelsRunningTrivia.add(channel.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum AnswerType {
|
public enum AnswerType
|
||||||
|
{
|
||||||
CORRECT, WRONG
|
CORRECT, WRONG
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,11 +25,19 @@ import java.util.List;
|
|||||||
public class UrbanDictionary
|
public class UrbanDictionary
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private UrbanDictionary()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static LinkedList<String> getCommandLabels()
|
public static LinkedList<String> getCommandLabels()
|
||||||
{ return new LinkedList<>(Arrays.asList("urban", "urbandictionary", "ud")); }
|
{
|
||||||
|
return new LinkedList<>(Arrays.asList("urban", "urbandictionary", "ud"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static String getBaseUrl() {
|
public static String getBaseUrl()
|
||||||
|
{
|
||||||
return "https://www.urbandictionary.com/define.php?term=";
|
return "https://www.urbandictionary.com/define.php?term=";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,7 +59,8 @@ public class UrbanDictionary
|
|||||||
.withEmoji(Emoji.fromFormatted("\uD83D\uDDD1️"));
|
.withEmoji(Emoji.fromFormatted("\uD83D\uDDD1️"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getNoArgsError() {
|
public static String getNoArgsError()
|
||||||
|
{
|
||||||
return "\uD83D\uDE22 I need to know what to search for!";
|
return "\uD83D\uDE22 I need to know what to search for!";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,7 +123,8 @@ public class UrbanDictionary
|
|||||||
DatabaseSource database = Cache.getDatabaseSource();
|
DatabaseSource database = Cache.getDatabaseSource();
|
||||||
|
|
||||||
// check if the user interacting is the same one who ran the command
|
// check if the user interacting is the same one who ran the command
|
||||||
if (!(database.isUserTrackedFor(event.getUser().getId(), messageId))) {
|
if (!(database.isUserTrackedFor(event.getUser().getId(), messageId)))
|
||||||
|
{
|
||||||
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
|
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -152,14 +162,16 @@ public class UrbanDictionary
|
|||||||
if (page > 0)
|
if (page > 0)
|
||||||
{
|
{
|
||||||
components.add(UrbanDictionary.getPreviousPageButton().asEnabled());
|
components.add(UrbanDictionary.getPreviousPageButton().asEnabled());
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
components.add(UrbanDictionary.getPreviousPageButton().asDisabled());
|
components.add(UrbanDictionary.getPreviousPageButton().asDisabled());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (page + 1 == search.getPages())
|
if (page + 1 == search.getPages())
|
||||||
{
|
{
|
||||||
components.add(UrbanDictionary.getNextPageButton().asDisabled());
|
components.add(UrbanDictionary.getNextPageButton().asDisabled());
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
components.add(UrbanDictionary.getNextPageButton().asEnabled());
|
components.add(UrbanDictionary.getNextPageButton().asEnabled());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,10 +275,10 @@ public class UrbanDictionary
|
|||||||
htmlContributor.indexOf("</a>") + 4);
|
htmlContributor.indexOf("</a>") + 4);
|
||||||
|
|
||||||
contributorsNames.add(htmlContributorName
|
contributorsNames.add(htmlContributorName
|
||||||
.replaceAll("<.*?>", "")); // remove all html tags;
|
.replaceAll("<.*?>", "")); // remove all html tags
|
||||||
|
|
||||||
submissionDates.add(htmlSubmitDate
|
submissionDates.add(htmlSubmitDate
|
||||||
.replaceAll("<.*?>", "")); // remove all html tags;
|
.replaceAll("<.*?>", "")); // remove all html tags
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,39 +290,48 @@ public class UrbanDictionary
|
|||||||
pages = submissionDates.size();
|
pages = submissionDates.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getPlaintextMeanings() {
|
public List<String> getPlaintextMeanings()
|
||||||
|
{
|
||||||
return this.plaintextMeanings;
|
return this.plaintextMeanings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getPlaintextExamples() {
|
public List<String> getPlaintextExamples()
|
||||||
|
{
|
||||||
return this.plaintextExamples;
|
return this.plaintextExamples;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getContributorsNames() {
|
public List<String> getContributorsNames()
|
||||||
|
{
|
||||||
return this.contributorsNames;
|
return this.contributorsNames;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getSubmissionDates() {
|
public List<String> getSubmissionDates()
|
||||||
|
{
|
||||||
return this.submissionDates;
|
return this.submissionDates;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSerializedMeanings() {
|
public String getSerializedMeanings()
|
||||||
|
{
|
||||||
return serializedMeanings;
|
return serializedMeanings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSerializedExamples() {
|
public String getSerializedExamples()
|
||||||
|
{
|
||||||
return serializedExamples;
|
return serializedExamples;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSerializedContributors() {
|
public String getSerializedContributors()
|
||||||
|
{
|
||||||
return serializedContributors;
|
return serializedContributors;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSerializedDates() {
|
public String getSerializedDates()
|
||||||
|
{
|
||||||
return serializedDates;
|
return serializedDates;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getPages() {
|
public int getPages()
|
||||||
|
{
|
||||||
return pages;
|
return pages;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,11 @@ import java.util.concurrent.TimeUnit;
|
|||||||
public class UserPunishment
|
public class UserPunishment
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private UserPunishment()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
private static final Duration maxTimeoutDuration = Duration.of(28, ChronoUnit.DAYS);
|
private static final Duration maxTimeoutDuration = Duration.of(28, ChronoUnit.DAYS);
|
||||||
private static final Duration minTimeoutDuration = Duration.of(30, ChronoUnit.SECONDS);
|
private static final Duration minTimeoutDuration = Duration.of(30, ChronoUnit.SECONDS);
|
||||||
|
|
||||||
@@ -128,7 +133,8 @@ public class UserPunishment
|
|||||||
String mentionedId = mentions.get(0).getId();
|
String mentionedId = mentions.get(0).getId();
|
||||||
User mentioned = null;
|
User mentioned = null;
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
mentioned = HidekoBot.getAPI().retrieveUserById(mentionedId).complete();
|
mentioned = HidekoBot.getAPI().retrieveUserById(mentionedId).complete();
|
||||||
} catch (RuntimeException ignored)
|
} catch (RuntimeException ignored)
|
||||||
{
|
{
|
||||||
@@ -168,11 +174,14 @@ public class UserPunishment
|
|||||||
AuditableRestAction<Void> punishmentAction = null;
|
AuditableRestAction<Void> punishmentAction = null;
|
||||||
boolean impossible = false;
|
boolean impossible = false;
|
||||||
|
|
||||||
try {
|
try
|
||||||
switch (punishmentType) {
|
{
|
||||||
|
switch (punishmentType)
|
||||||
|
{
|
||||||
case BAN -> punishmentAction = guild.ban(mentioned, 0, TimeUnit.SECONDS);
|
case BAN -> punishmentAction = guild.ban(mentioned, 0, TimeUnit.SECONDS);
|
||||||
case KICK -> punishmentAction = guild.kick(mentioned);
|
case KICK -> punishmentAction = guild.kick(mentioned);
|
||||||
case TIMEOUT -> {
|
case TIMEOUT ->
|
||||||
|
{
|
||||||
if (args != null)
|
if (args != null)
|
||||||
{
|
{
|
||||||
String durationStr = args[1];
|
String durationStr = args[1];
|
||||||
@@ -197,7 +206,8 @@ public class UserPunishment
|
|||||||
punishmentAction = guild.timeoutFor(mentioned, duration);
|
punishmentAction = guild.timeoutFor(mentioned, duration);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (RuntimeException ignored) {
|
} catch (RuntimeException ignored)
|
||||||
|
{
|
||||||
impossible = true;
|
impossible = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,7 +224,8 @@ public class UserPunishment
|
|||||||
if (!reason.isEmpty() && !reasonBuilder.isEmpty())
|
if (!reason.isEmpty() && !reasonBuilder.isEmpty())
|
||||||
punishmentAction.reason("[" + author.getAsTag() + "] " + reason);
|
punishmentAction.reason("[" + author.getAsTag() + "] " + reason);
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
punishmentAction.complete();
|
punishmentAction.complete();
|
||||||
} catch (RuntimeException ignored)
|
} catch (RuntimeException ignored)
|
||||||
{
|
{
|
||||||
@@ -244,7 +255,8 @@ public class UserPunishment
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum PunishmentType {
|
public enum PunishmentType
|
||||||
|
{
|
||||||
KICK("kicked"),
|
KICK("kicked"),
|
||||||
BAN("banned"),
|
BAN("banned"),
|
||||||
TIMEOUT("timed out"),
|
TIMEOUT("timed out"),
|
||||||
|
|||||||
@@ -13,12 +13,14 @@ import java.util.List;
|
|||||||
public class ProfileImageCommandCompleter extends SlashArgumentsCompleterImpl
|
public class ProfileImageCommandCompleter extends SlashArgumentsCompleterImpl
|
||||||
{
|
{
|
||||||
|
|
||||||
public ProfileImageCommandCompleter(SlashCommand parentCommand) {
|
public ProfileImageCommandCompleter(SlashCommand parentCommand)
|
||||||
|
{
|
||||||
super(parentCommand);
|
super(parentCommand);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event) {
|
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event)
|
||||||
|
{
|
||||||
if (event.getFocusedOption().getName().equals("size"))
|
if (event.getFocusedOption().getName().equals("size"))
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|||||||
@@ -17,36 +17,42 @@ public class AliasCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Arrays.asList("alias", "aliases"));
|
return new LinkedList<>(Arrays.asList("alias", "aliases"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "See other command aliases.";
|
return "See other command aliases.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<command>";
|
return "<command>";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import net.dv8tion.jda.api.entities.User;
|
|||||||
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
import wtf.beatrice.hidekobot.Cache;
|
|
||||||
import wtf.beatrice.hidekobot.HidekoBot;
|
import wtf.beatrice.hidekobot.HidekoBot;
|
||||||
import wtf.beatrice.hidekobot.commands.base.ProfileImage;
|
import wtf.beatrice.hidekobot.commands.base.ProfileImage;
|
||||||
import wtf.beatrice.hidekobot.objects.MessageResponse;
|
import wtf.beatrice.hidekobot.objects.MessageResponse;
|
||||||
@@ -21,44 +20,48 @@ public class AvatarCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("avatar"));
|
return new LinkedList<>(Collections.singletonList("avatar"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get someone's avatar, or your own. You can additionally specify a resolution.";
|
return "Get someone's avatar, or your own. You can additionally specify a resolution.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "[mentioned user] [resolution]";
|
return "[mentioned user] [resolution]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
||||||
{
|
{
|
||||||
int[] acceptedSizes = Cache.getSupportedAvatarResolutions();
|
|
||||||
|
|
||||||
User user;
|
User user;
|
||||||
int resolution = -1;
|
int resolution = -1;
|
||||||
|
|
||||||
@@ -66,13 +69,17 @@ public class AvatarCommand implements MessageCommand
|
|||||||
// (mentions are handled differently by a specific method)
|
// (mentions are handled differently by a specific method)
|
||||||
boolean resFound = false;
|
boolean resFound = false;
|
||||||
|
|
||||||
for (String arg : args) {
|
for (String arg : args)
|
||||||
try {
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
int givenRes = Integer.parseInt(arg);
|
int givenRes = Integer.parseInt(arg);
|
||||||
resolution = ProfileImage.parseResolution(givenRes);
|
resolution = ProfileImage.parseResolution(givenRes);
|
||||||
resFound = true;
|
resFound = true;
|
||||||
break;
|
break;
|
||||||
} catch (NumberFormatException ignored) {
|
} catch (NumberFormatException ignored)
|
||||||
|
{
|
||||||
|
// ignored because we're running a check after this block
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,36 +17,42 @@ public class BanCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("ban"));
|
return new LinkedList<>(Collections.singletonList("ban"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return new ArrayList<Permission>(Collections.singletonList(Permission.BAN_MEMBERS));
|
return new ArrayList<Permission>(Collections.singletonList(Permission.BAN_MEMBERS));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.MODERATION;
|
return CommandCategory.MODERATION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Ban the mentioned user.";
|
return "Ban the mentioned user.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<mentioned user> [reason]";
|
return "<mentioned user> [reason]";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,36 +20,42 @@ public class BannerCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("banner"));
|
return new LinkedList<>(Collections.singletonList("banner"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get someone's profile banner, or your own.";
|
return "Get someone's profile banner, or your own.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "[mentioned user] [resolution]";
|
return "[mentioned user] [resolution]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,13 +69,17 @@ public class BannerCommand implements MessageCommand
|
|||||||
// (mentions are handled differently by a specific method)
|
// (mentions are handled differently by a specific method)
|
||||||
boolean resFound = false;
|
boolean resFound = false;
|
||||||
|
|
||||||
for (String arg : args) {
|
for (String arg : args)
|
||||||
try {
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
int givenRes = Integer.parseInt(arg);
|
int givenRes = Integer.parseInt(arg);
|
||||||
resolution = ProfileImage.parseResolution(givenRes);
|
resolution = ProfileImage.parseResolution(givenRes);
|
||||||
resFound = true;
|
resFound = true;
|
||||||
break;
|
break;
|
||||||
} catch (NumberFormatException ignored) {
|
} catch (NumberFormatException ignored)
|
||||||
|
{
|
||||||
|
// ignored because we're running a check after this block
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,46 +18,54 @@ public class BotInfoCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Arrays.asList("botinfo", "info"));
|
return new LinkedList<>(Arrays.asList("botinfo", "info"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get general info about the bot.";
|
return "Get general info about the bot.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runCommand(MessageReceivedEvent event, String label, String[] args) {
|
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
||||||
|
{
|
||||||
|
|
||||||
// get a list of message commands
|
// get a list of message commands
|
||||||
LinkedList<MessageCommand> messageCommands = Cache.getMessageCommandListener().getRegisteredCommands();
|
LinkedList<MessageCommand> messageCommands = Cache.getMessageCommandListener().getRegisteredCommands();
|
||||||
LinkedList<String> commandNames = new LinkedList<>();
|
LinkedList<String> commandNames = new LinkedList<>();
|
||||||
for (MessageCommand command : messageCommands) {
|
for (MessageCommand command : messageCommands)
|
||||||
|
{
|
||||||
commandNames.add(command.getCommandLabels().get(0));
|
commandNames.add(command.getCommandLabels().get(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,44 +19,51 @@ public class ClearCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList(ClearChat.getLabel()));
|
return new LinkedList<>(Collections.singletonList(ClearChat.getLabel()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() { return Collections.singletonList(ClearChat.getPermission()); }
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
|
return Collections.singletonList(ClearChat.getPermission());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.MODERATION;
|
return CommandCategory.MODERATION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Clear the current channel's chat history.";
|
return "Clear the current channel's chat history.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "[amount]";
|
return "[amount]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
||||||
{
|
{
|
||||||
String senderId = event.getMessage().getAuthor().getId();
|
|
||||||
|
|
||||||
// check if user is trying to run command in dms.
|
// check if user is trying to run command in dms.
|
||||||
String error = ClearChat.checkDMs(event.getChannel());
|
String error = ClearChat.checkDMs(event.getChannel());
|
||||||
if (error != null) {
|
if (error != null)
|
||||||
|
{
|
||||||
event.getMessage().reply(error).queue();
|
event.getMessage().reply(error).queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -66,7 +73,8 @@ public class ClearCommand implements MessageCommand
|
|||||||
if (args.length == 0) toDeleteAmount = 1;
|
if (args.length == 0) toDeleteAmount = 1;
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
toDeleteAmount = Integer.parseInt(args[0]);
|
toDeleteAmount = Integer.parseInt(args[0]);
|
||||||
} catch (NumberFormatException e)
|
} catch (NumberFormatException e)
|
||||||
{
|
{
|
||||||
@@ -78,7 +86,8 @@ public class ClearCommand implements MessageCommand
|
|||||||
if (toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0;
|
if (toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0;
|
||||||
|
|
||||||
error = ClearChat.checkDeleteAmount(toDeleteAmount);
|
error = ClearChat.checkDeleteAmount(toDeleteAmount);
|
||||||
if (error != null) {
|
if (error != null)
|
||||||
|
{
|
||||||
event.getMessage().reply(error).queue();
|
event.getMessage().reply(error).queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,41 +16,48 @@ public class CoinFlipCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Arrays.asList("coinflip", "flip", "flipcoin"));
|
return new LinkedList<>(Arrays.asList("coinflip", "flip", "flipcoin"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // null because it can be used anywhere
|
return null; // null because it can be used anywhere
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Flip a coin.";
|
return "Flip a coin.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runCommand(MessageReceivedEvent event, String label, String[] args) {
|
public void runCommand(MessageReceivedEvent event, String label, String[] args)
|
||||||
|
{
|
||||||
|
|
||||||
// perform coin flip
|
// perform coin flip
|
||||||
event.getMessage().reply(CoinFlip.genRandom())
|
event.getMessage().reply(CoinFlip.genRandom())
|
||||||
@@ -59,6 +66,7 @@ public class CoinFlipCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
// set the command as expiring and restrict it to the user who ran it
|
// set the command as expiring and restrict it to the user who ran it
|
||||||
CoinFlip.trackAndRestrict(message, event.getAuthor());
|
CoinFlip.trackAndRestrict(message, event.getAuthor());
|
||||||
}, (error) -> {});
|
}, (error) -> {
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,41 +16,49 @@ import java.util.List;
|
|||||||
public class DiceRollCommand implements MessageCommand
|
public class DiceRollCommand implements MessageCommand
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Arrays.asList("diceroll", "droll", "roll"));
|
return new LinkedList<>(Arrays.asList("diceroll", "droll", "roll"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
return "Roll dice. You can roll multiple dice at the same time." +
|
{
|
||||||
"\nExamples:" +
|
return """
|
||||||
"\n - `d8 10` to roll an 8-sided die 10 times." +
|
Roll dice. You can roll multiple dice at the same time.
|
||||||
"\n - `d12 3 d5 10` to roll a 12-sided die 3 times, and then a 5-sided die 10 times." +
|
Examples:
|
||||||
"\n - `30` to roll a standard 6-sided die 30 times." +
|
- `d8 10` to roll an 8-sided die 10 times.
|
||||||
"\n - `d10` to roll a 10-sided die once.";
|
- `d12 3 d5 10` to roll a 12-sided die 3 times, and then a 5-sided die 10 times.
|
||||||
|
- `30` to roll a standard 6-sided die 30 times.
|
||||||
|
- `d10` to roll a 10-sided die once.
|
||||||
|
""";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "[dice size] [rolls]";
|
return "[dice size] [rolls]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,33 +15,41 @@ public class HelloCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Arrays.asList("hi", "hello", "heya"));
|
return new LinkedList<>(Arrays.asList("hi", "hello", "heya"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() { return null; }
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get pinged by the bot.";
|
return "Get pinged by the bot.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,44 +11,49 @@ import wtf.beatrice.hidekobot.commands.base.Alias;
|
|||||||
import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
|
import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
|
||||||
import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
|
import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.*;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class HelpCommand implements MessageCommand
|
public class HelpCommand implements MessageCommand
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("help"));
|
return new LinkedList<>(Collections.singletonList("help"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() { return null; }
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get general help on the bot. Specify a command if you want specific help about that command.";
|
return "Get general help on the bot. Specify a command if you want specific help about that command.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "[command]";
|
return "[command]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,10 +87,11 @@ public class HelpCommand implements MessageCommand
|
|||||||
"\nYou will find a list of commands organized in categories below.",
|
"\nYou will find a list of commands organized in categories below.",
|
||||||
false);
|
false);
|
||||||
|
|
||||||
for(CommandCategory category : commandCategories.keySet())
|
for (Map.Entry<CommandCategory, LinkedList<MessageCommand>> entry : commandCategories.entrySet())
|
||||||
{
|
{
|
||||||
StringBuilder commandsList = new StringBuilder();
|
StringBuilder commandsList = new StringBuilder();
|
||||||
LinkedList<MessageCommand> commandsOfThisCategory = commandCategories.get(category);
|
CommandCategory category = entry.getKey();
|
||||||
|
LinkedList<MessageCommand> commandsOfThisCategory = entry.getValue();
|
||||||
|
|
||||||
for (int pos = 0; pos < commandsOfThisCategory.size(); pos++)
|
for (int pos = 0; pos < commandsOfThisCategory.size(); pos++)
|
||||||
{
|
{
|
||||||
@@ -104,7 +110,8 @@ public class HelpCommand implements MessageCommand
|
|||||||
}
|
}
|
||||||
|
|
||||||
event.getMessage().replyEmbeds(embedBuilder.build()).queue();
|
event.getMessage().replyEmbeds(embedBuilder.build()).queue();
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
|
|
||||||
String commandLabel = args[0].toLowerCase();
|
String commandLabel = args[0].toLowerCase();
|
||||||
MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel);
|
MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel);
|
||||||
@@ -127,7 +134,8 @@ public class HelpCommand implements MessageCommand
|
|||||||
if (permissions == null)
|
if (permissions == null)
|
||||||
{
|
{
|
||||||
permissionsStringBuilder = new StringBuilder("Available to everyone");
|
permissionsStringBuilder = new StringBuilder("Available to everyone");
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
for (int i = 0; i < permissions.size(); i++)
|
for (int i = 0; i < permissions.size(); i++)
|
||||||
{
|
{
|
||||||
Permission permission = permissions.get(i);
|
Permission permission = permissions.get(i);
|
||||||
|
|||||||
@@ -19,36 +19,42 @@ public class InviteCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("invite"));
|
return new LinkedList<>(Collections.singletonList("invite"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Get the bot's invite link.";
|
return "Get the bot's invite link.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.MODERATION;
|
return CommandCategory.MODERATION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +76,8 @@ public class InviteCommand implements MessageCommand
|
|||||||
.queue();
|
.queue();
|
||||||
event.getMessage().addReaction(Emoji.fromUnicode("✅")).queue();
|
event.getMessage().addReaction(Emoji.fromUnicode("✅")).queue();
|
||||||
}, error -> event.getMessage().addReaction(Emoji.fromUnicode("❌")).queue());
|
}, error -> event.getMessage().addReaction(Emoji.fromUnicode("❌")).queue());
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.getMessage()
|
event.getMessage()
|
||||||
.replyEmbeds(inviteEmbed)
|
.replyEmbeds(inviteEmbed)
|
||||||
.addActionRow(inviteButton)
|
.addActionRow(inviteButton)
|
||||||
|
|||||||
@@ -17,36 +17,42 @@ public class KickCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("kick"));
|
return new LinkedList<>(Collections.singletonList("kick"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return new ArrayList<Permission>(Collections.singletonList(Permission.KICK_MEMBERS));
|
return new ArrayList<Permission>(Collections.singletonList(Permission.KICK_MEMBERS));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.MODERATION;
|
return CommandCategory.MODERATION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Kick the mentioned user from the guild.";
|
return "Kick the mentioned user from the guild.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<mentioned user> [reason]";
|
return "<mentioned user> [reason]";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,30 +29,35 @@ public class LoveCalculatorCommand implements MessageCommand
|
|||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; //anyone can use it
|
return null; //anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Calculate how much two people love each other. You can mention two people or just one.";
|
return "Calculate how much two people love each other. You can mention two people or just one.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<person 1> [person 2]";
|
return "<person 1> [person 2]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +85,8 @@ public class LoveCalculatorCommand implements MessageCommand
|
|||||||
if (mentions.size() == 1)
|
if (mentions.size() == 1)
|
||||||
{
|
{
|
||||||
user2 = event.getAuthor();
|
user2 = event.getAuthor();
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
mentionedUserId = mentions.get(1).getId();
|
mentionedUserId = mentions.get(1).getId();
|
||||||
user2 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete();
|
user2 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,36 +15,42 @@ public class MagicBallCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return MagicBall.getLabels();
|
return MagicBall.getLabels();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; // anyone can use it
|
return null; // anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Ask a question to the Magic Ball.";
|
return "Ask a question to the Magic Ball.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<question>";
|
return "<question>";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package wtf.beatrice.hidekobot.commands.message;
|
package wtf.beatrice.hidekobot.commands.message;
|
||||||
|
|
||||||
import net.dv8tion.jda.api.Permission;
|
import net.dv8tion.jda.api.Permission;
|
||||||
|
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
|
||||||
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
@@ -17,34 +18,42 @@ public class SayCommand implements MessageCommand
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("say"));
|
return new LinkedList<>(Collections.singletonList("say"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() { return Collections.singletonList(Say.getPermission()); }
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
|
return Collections.singletonList(Say.getPermission());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Make the bot say something for you.";
|
return "Make the bot say something for you.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<text>";
|
return "<text>";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.TOOLS;
|
return CommandCategory.TOOLS;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,14 +65,23 @@ public class SayCommand implements MessageCommand
|
|||||||
if (args.length != 0 && !args[0].isEmpty())
|
if (args.length != 0 && !args[0].isEmpty())
|
||||||
{
|
{
|
||||||
messageContent = args[0];
|
messageContent = args[0];
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.getMessage().reply("\uD83D\uDE20 Hey, you have to tell me what to say!")
|
event.getMessage().reply("\uD83D\uDE20 Hey, you have to tell me what to say!")
|
||||||
.queue();
|
.queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
event.getChannel().sendMessage(messageContent).queue();
|
event.getChannel().sendMessage(messageContent).queue();
|
||||||
event.getMessage().delete().queue();
|
|
||||||
|
|
||||||
|
if (event.getChannel() instanceof TextChannel)
|
||||||
|
{
|
||||||
|
event.getMessage().delete().queue(response -> {
|
||||||
|
// nothing to do with the response
|
||||||
|
}, error -> {
|
||||||
|
// ignore the error if we couldn't delete it, we were probably missing permissions
|
||||||
|
// without this block it would print a stack trace in console
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,36 +17,42 @@ public class TimeoutCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("timeout"));
|
return new LinkedList<>(Collections.singletonList("timeout"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return new ArrayList<Permission>(Collections.singletonList(Permission.MODERATE_MEMBERS));
|
return new ArrayList<Permission>(Collections.singletonList(Permission.MODERATE_MEMBERS));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.MODERATION;
|
return CommandCategory.MODERATION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Timeout the mentioned user.";
|
return "Timeout the mentioned user.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<mentioned user> <duration> [reason]";
|
return "<mentioned user> <duration> [reason]";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,36 +23,42 @@ public class TriviaCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return new LinkedList<>(Collections.singletonList("trivia"));
|
return new LinkedList<>(Collections.singletonList("trivia"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Start a Trivia session and play with others!";
|
return "Start a Trivia session and play with others!";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +89,8 @@ public class TriviaCommand implements MessageCommand
|
|||||||
if (response.content() != null) responseAction = recvMessage.reply(response.content());
|
if (response.content() != null) responseAction = recvMessage.reply(response.content());
|
||||||
else if (response.embed() != null) responseAction = recvMessage.replyEmbeds(response.embed());
|
else if (response.embed() != null) responseAction = recvMessage.replyEmbeds(response.embed());
|
||||||
|
|
||||||
if(responseAction != null) {
|
if (responseAction != null)
|
||||||
|
{
|
||||||
if (response.components() != null) responseAction = responseAction.addActionRow(response.components());
|
if (response.components() != null) responseAction = responseAction.addActionRow(response.components());
|
||||||
|
|
||||||
responseAction.queue(message -> {
|
responseAction.queue(message -> {
|
||||||
|
|||||||
@@ -21,36 +21,42 @@ public class UrbanDictionaryCommand implements MessageCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LinkedList<String> getCommandLabels() {
|
public LinkedList<String> getCommandLabels()
|
||||||
|
{
|
||||||
return UrbanDictionary.getCommandLabels();
|
return UrbanDictionary.getCommandLabels();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public List<Permission> getPermissions() {
|
public List<Permission> getPermissions()
|
||||||
|
{
|
||||||
return null; //anyone can use it
|
return null; //anyone can use it
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean passRawArgs() {
|
public boolean passRawArgs()
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription()
|
||||||
|
{
|
||||||
return "Look something up in the Urban Dictionary.";
|
return "Look something up in the Urban Dictionary.";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public String getUsage() {
|
public String getUsage()
|
||||||
|
{
|
||||||
return "<query>";
|
return "<query>";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public CommandCategory getCategory() {
|
public CommandCategory getCategory()
|
||||||
|
{
|
||||||
return CommandCategory.FUN;
|
return CommandCategory.FUN;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +72,8 @@ public class UrbanDictionaryCommand implements MessageCommand
|
|||||||
|
|
||||||
// sanitize args by only keeping letters and numbers, and adding "+" instead of spaces for HTML parsing
|
// sanitize args by only keeping letters and numbers, and adding "+" instead of spaces for HTML parsing
|
||||||
StringBuilder termBuilder = new StringBuilder();
|
StringBuilder termBuilder = new StringBuilder();
|
||||||
for (int i = 0; i < args.length; i++) {
|
for (int i = 0; i < args.length; i++)
|
||||||
|
{
|
||||||
String arg = args[i];
|
String arg = args[i];
|
||||||
termBuilder.append(arg);
|
termBuilder.append(arg);
|
||||||
|
|
||||||
@@ -79,9 +86,11 @@ public class UrbanDictionaryCommand implements MessageCommand
|
|||||||
|
|
||||||
Document doc;
|
Document doc;
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
doc = Jsoup.connect(url).get();
|
doc = Jsoup.connect(url).get();
|
||||||
} catch (IOException e) {
|
} catch (IOException e)
|
||||||
|
{
|
||||||
event.getMessage().reply(UrbanDictionary.getTermNotFoundError()).queue();
|
event.getMessage().reply(UrbanDictionary.getTermNotFoundError()).queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
|
|||||||
public class AvatarCommand extends SlashCommandImpl
|
public class AvatarCommand extends SlashCommandImpl
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return Commands.slash("avatar", "Get someone's profile picture.")
|
return Commands.slash("avatar", "Get someone's profile picture.")
|
||||||
.addOption(OptionType.USER, "user", "User you want to grab the avatar of.")
|
.addOption(OptionType.USER, "user", "User you want to grab the avatar of.")
|
||||||
.addOption(OptionType.INTEGER, "size", "The size of the returned image.",
|
.addOption(OptionType.INTEGER, "size", "The size of the returned image.",
|
||||||
@@ -35,7 +36,8 @@ public class AvatarCommand extends SlashCommandImpl
|
|||||||
if (userArg != null)
|
if (userArg != null)
|
||||||
{
|
{
|
||||||
user = userArg.getAsUser();
|
user = userArg.getAsUser();
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
user = event.getUser();
|
user = event.getUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +45,8 @@ public class AvatarCommand extends SlashCommandImpl
|
|||||||
if (sizeArg != null)
|
if (sizeArg != null)
|
||||||
{
|
{
|
||||||
resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
|
resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
resolution = ProfileImage.parseResolution(512);
|
resolution = ProfileImage.parseResolution(512);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
|
|||||||
public class BannerCommand extends SlashCommandImpl
|
public class BannerCommand extends SlashCommandImpl
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return Commands.slash("banner", "Get someone's profile banner.")
|
return Commands.slash("banner", "Get someone's profile banner.")
|
||||||
.addOption(OptionType.USER, "user", "User you want to grab the banner of.")
|
.addOption(OptionType.USER, "user", "User you want to grab the banner of.")
|
||||||
.addOption(OptionType.INTEGER, "size", "The size of the returned image.",
|
.addOption(OptionType.INTEGER, "size", "The size of the returned image.",
|
||||||
@@ -35,7 +36,8 @@ public class BannerCommand extends SlashCommandImpl
|
|||||||
if (userArg != null)
|
if (userArg != null)
|
||||||
{
|
{
|
||||||
user = userArg.getAsUser();
|
user = userArg.getAsUser();
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
user = event.getUser();
|
user = event.getUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +45,8 @@ public class BannerCommand extends SlashCommandImpl
|
|||||||
if (sizeArg != null)
|
if (sizeArg != null)
|
||||||
{
|
{
|
||||||
resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
|
resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
resolution = ProfileImage.parseResolution(512);
|
resolution = ProfileImage.parseResolution(512);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ import java.util.List;
|
|||||||
public class BotInfoCommand extends SlashCommandImpl
|
public class BotInfoCommand extends SlashCommandImpl
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return Commands.slash("botinfo", "Get info about the bot.");
|
return Commands.slash("botinfo", "Get info about the bot.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ public class ClearCommand extends SlashCommandImpl
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return Commands.slash(ClearChat.getLabel(),
|
return Commands.slash(ClearChat.getLabel(),
|
||||||
ClearChat.getDescription())
|
ClearChat.getDescription())
|
||||||
.addOption(OptionType.INTEGER, "amount", "The amount of messages to delete.")
|
.addOption(OptionType.INTEGER, "amount", "The amount of messages to delete.")
|
||||||
|
|||||||
@@ -29,12 +29,11 @@ public class CoinFlipCommand extends SlashCommandImpl
|
|||||||
interaction.retrieveOriginal().queue((message) ->
|
interaction.retrieveOriginal().queue((message) ->
|
||||||
{
|
{
|
||||||
CoinFlip.trackAndRestrict(message, event.getUser());
|
CoinFlip.trackAndRestrict(message, event.getUser());
|
||||||
}, (error) -> {});
|
}, (error) -> {
|
||||||
}, (error) -> {});
|
});
|
||||||
|
}, (error) -> {
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ import wtf.beatrice.hidekobot.HidekoBot;
|
|||||||
import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
|
import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
|
||||||
|
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class DieCommand extends SlashCommandImpl
|
public class DieCommand extends SlashCommandImpl
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return Commands.slash("die", "Stop the bot's process.")
|
return Commands.slash("die", "Stop the bot's process.")
|
||||||
.setDefaultPermissions(DefaultMemberPermissions.DISABLED);
|
.setDefaultPermissions(DefaultMemberPermissions.DISABLED);
|
||||||
}
|
}
|
||||||
@@ -26,9 +28,13 @@ public class DieCommand extends SlashCommandImpl
|
|||||||
if (Cache.getBotOwnerId() != event.getUser().getIdLong())
|
if (Cache.getBotOwnerId() != event.getUser().getIdLong())
|
||||||
{
|
{
|
||||||
event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue();
|
event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue();
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.reply("Going to sleep! Cya ✨").queue();
|
event.reply("Going to sleep! Cya ✨").queue();
|
||||||
Executors.newSingleThreadScheduledExecutor().schedule(HidekoBot::shutdown, 3, TimeUnit.SECONDS);
|
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
|
||||||
|
{
|
||||||
|
executor.schedule(HidekoBot::shutdown, 3, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ public class LoveCalculatorCommand extends SlashCommandImpl
|
|||||||
if (firsUserArg != null)
|
if (firsUserArg != null)
|
||||||
{
|
{
|
||||||
firstUser = firsUserArg.getAsUser(); //todo null check?
|
firstUser = firsUserArg.getAsUser(); //todo null check?
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
event.reply("\uD83D\uDE22 I need to know who to check! Please mention them.")
|
event.reply("\uD83D\uDE22 I need to know who to check! Please mention them.")
|
||||||
.setEphemeral(true)
|
.setEphemeral(true)
|
||||||
.queue();
|
.queue();
|
||||||
@@ -51,7 +52,8 @@ public class LoveCalculatorCommand extends SlashCommandImpl
|
|||||||
if (secondUserArg != null)
|
if (secondUserArg != null)
|
||||||
{
|
{
|
||||||
secondUser = secondUserArg.getAsUser(); //todo null check?
|
secondUser = secondUserArg.getAsUser(); //todo null check?
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
secondUser = event.getUser();
|
secondUser = event.getUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,9 +54,11 @@ public class UrbanDictionaryCommand extends SlashCommandImpl
|
|||||||
|
|
||||||
Document doc;
|
Document doc;
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
doc = Jsoup.connect(url).get();
|
doc = Jsoup.connect(url).get();
|
||||||
} catch (IOException e) {
|
} catch (IOException e)
|
||||||
|
{
|
||||||
event.reply(UrbanDictionary.getTermNotFoundError())
|
event.reply(UrbanDictionary.getTermNotFoundError())
|
||||||
.setEphemeral(true)
|
.setEphemeral(true)
|
||||||
.queue();
|
.queue();
|
||||||
|
|||||||
@@ -14,12 +14,20 @@ public enum ConfigurationEntry
|
|||||||
|
|
||||||
private String path;
|
private String path;
|
||||||
private Object defaultValue;
|
private Object defaultValue;
|
||||||
|
|
||||||
ConfigurationEntry(String path, Object defaultValue)
|
ConfigurationEntry(String path, Object defaultValue)
|
||||||
{
|
{
|
||||||
this.path = path;
|
this.path = path;
|
||||||
this.defaultValue = defaultValue;
|
this.defaultValue = defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPath() { return path; }
|
public String getPath()
|
||||||
public Object getDefaultValue() { return defaultValue; }
|
{
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getDefaultValue()
|
||||||
|
{
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ package wtf.beatrice.hidekobot.datasources;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.yaml.snakeyaml.DumperOptions;
|
import org.yaml.snakeyaml.DumperOptions;
|
||||||
|
import org.yaml.snakeyaml.LoaderOptions;
|
||||||
import org.yaml.snakeyaml.Yaml;
|
import org.yaml.snakeyaml.Yaml;
|
||||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
import wtf.beatrice.hidekobot.HidekoBot;
|
import wtf.beatrice.hidekobot.HidekoBot;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class ConfigurationSource
|
public class ConfigurationSource
|
||||||
{
|
{
|
||||||
@@ -47,26 +49,32 @@ public class ConfigurationSource
|
|||||||
if (!fsConfigFile.exists())
|
if (!fsConfigFile.exists())
|
||||||
{
|
{
|
||||||
// try to create config file
|
// try to create config file
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
if (!fsConfigFile.createNewFile())
|
if (!fsConfigFile.createNewFile())
|
||||||
{
|
{
|
||||||
LOGGER.error("We tried creating a file that already exists!");
|
LOGGER.error("We tried creating a file that already exists!");
|
||||||
HidekoBot.shutdown();
|
HidekoBot.shutdown();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
} catch (IOException e)
|
||||||
catch (IOException e) {
|
{
|
||||||
LOGGER.error("Error creating configuration file!", e);
|
LOGGER.error("Error creating configuration file!", e);
|
||||||
HidekoBot.shutdown();
|
HidekoBot.shutdown();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// load the YAML file from the filesystem
|
// load the YAML file from the filesystem
|
||||||
Yaml fsConfigYaml = new Yaml(new SafeConstructor());
|
LoaderOptions options = new LoaderOptions();
|
||||||
|
Yaml fsConfigYaml = new Yaml(new SafeConstructor(options));
|
||||||
LinkedHashMap<String, Object> fsConfigContents = null; // map holding all file entries
|
LinkedHashMap<String, Object> fsConfigContents = null; // map holding all file entries
|
||||||
try (InputStream fsConfigStream = new FileInputStream(fsConfigFile))
|
try (InputStream fsConfigStream = new FileInputStream(fsConfigFile))
|
||||||
{ fsConfigContents = fsConfigYaml.load(fsConfigStream); }
|
{
|
||||||
catch (IOException e) { LOGGER.error(e.getMessage()); }
|
fsConfigContents = fsConfigYaml.load(fsConfigStream);
|
||||||
|
} catch (IOException e)
|
||||||
|
{
|
||||||
|
LOGGER.error(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
if (fsConfigContents == null) // if file contents are empty or corrupted...
|
if (fsConfigContents == null) // if file contents are empty or corrupted...
|
||||||
@@ -94,19 +102,24 @@ public class ConfigurationSource
|
|||||||
// create a new mixed map that will take existing values from the non-missing keys
|
// create a new mixed map that will take existing values from the non-missing keys
|
||||||
// and fill everything else with the default values
|
// and fill everything else with the default values
|
||||||
LinkedHashMap<String, Object> filledEntries = new LinkedHashMap<>();
|
LinkedHashMap<String, Object> filledEntries = new LinkedHashMap<>();
|
||||||
for(String key : internalConfigContents.keySet())
|
|
||||||
|
for (Map.Entry<String, Object> entry : internalConfigContents.entrySet())
|
||||||
{
|
{
|
||||||
|
String key = entry.getKey();
|
||||||
|
|
||||||
if (fsConfigContents.containsKey(key))
|
if (fsConfigContents.containsKey(key))
|
||||||
{
|
{
|
||||||
// if the key already exists, copy the original value
|
// if the key already exists, copy the original value
|
||||||
filledEntries.put(key, fsConfigContents.get(key));
|
filledEntries.put(key, fsConfigContents.get(key));
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
// else, copy the value from the example config file
|
// else, copy the value from the example config file
|
||||||
filledEntries.put(key, internalConfigContents.get(key));
|
filledEntries.put(key, entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
// new writer to actually write the contents to the file
|
// new writer to actually write the contents to the file
|
||||||
PrintWriter missingKeysWriter = new PrintWriter(fsConfigFile);
|
PrintWriter missingKeysWriter = new PrintWriter(fsConfigFile);
|
||||||
|
|
||||||
@@ -119,7 +132,8 @@ public class ConfigurationSource
|
|||||||
// create the yaml object and dump the values to filesystem
|
// create the yaml object and dump the values to filesystem
|
||||||
Yaml yaml = new Yaml(dumperOptions);
|
Yaml yaml = new Yaml(dumperOptions);
|
||||||
yaml.dump(filledEntries, missingKeysWriter);
|
yaml.dump(filledEntries, missingKeysWriter);
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e)
|
||||||
|
{
|
||||||
LOGGER.error(e.getMessage());
|
LOGGER.error(e.getMessage());
|
||||||
HidekoBot.shutdown();
|
HidekoBot.shutdown();
|
||||||
return;
|
return;
|
||||||
@@ -127,7 +141,8 @@ public class ConfigurationSource
|
|||||||
|
|
||||||
// finally, dump all entries to cache.
|
// finally, dump all entries to cache.
|
||||||
loadConfig(filledEntries);
|
loadConfig(filledEntries);
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
// if no key is missing, just cache all entries and values from filesystem.
|
// if no key is missing, just cache all entries and values from filesystem.
|
||||||
loadConfig(fsConfigContents);
|
loadConfig(fsConfigContents);
|
||||||
}
|
}
|
||||||
@@ -138,6 +153,7 @@ public class ConfigurationSource
|
|||||||
{
|
{
|
||||||
this.configurationEntries.putAll(configurationEntries);
|
this.configurationEntries.putAll(configurationEntries);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object getConfigValue(ConfigurationEntry key)
|
public Object getConfigValue(ConfigurationEntry key)
|
||||||
{
|
{
|
||||||
return configurationEntries.get(key.getPath());
|
return configurationEntries.get(key.getPath());
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ public class DatabaseSource
|
|||||||
{
|
{
|
||||||
|
|
||||||
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DatabaseSource.class);
|
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DatabaseSource.class);
|
||||||
private static final String sqliteURL = "jdbc:sqlite:%path%";
|
private static final String JDBC_URL = "jdbc:sqlite:%path%";
|
||||||
private Connection dbConnection = null;
|
private Connection dbConnection = null;
|
||||||
private final String dbPath;
|
private final String dbPath;
|
||||||
|
|
||||||
@@ -32,15 +32,17 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public boolean connect()
|
public boolean connect()
|
||||||
{
|
{
|
||||||
String url = sqliteURL.replace("%path%", dbPath);
|
String url = JDBC_URL.replace("%path%", dbPath);
|
||||||
|
|
||||||
if (!close()) return false;
|
if (!close()) return false;
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
dbConnection = DriverManager.getConnection(url);
|
dbConnection = DriverManager.getConnection(url);
|
||||||
LOGGER.info("Database connection established!");
|
LOGGER.info("Database connection established!");
|
||||||
return true;
|
return true;
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -52,12 +54,14 @@ public class DatabaseSource
|
|||||||
{
|
{
|
||||||
if (dbConnection != null)
|
if (dbConnection != null)
|
||||||
{
|
{
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
if (!dbConnection.isClosed())
|
if (!dbConnection.isClosed())
|
||||||
{
|
{
|
||||||
dbConnection.close();
|
dbConnection.close();
|
||||||
}
|
}
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -94,42 +98,47 @@ public class DatabaseSource
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
//todo: javadocs
|
//todo: javadocs
|
||||||
|
|
||||||
public boolean initDb()
|
public boolean initDb()
|
||||||
{
|
{
|
||||||
List<String> newTables = new ArrayList<>();
|
List<String> newTables = new ArrayList<>();
|
||||||
|
|
||||||
newTables.add("CREATE TABLE IF NOT EXISTS pending_disabled_messages (" +
|
newTables.add("""
|
||||||
"guild_id TEXT NOT NULL, " +
|
CREATE TABLE IF NOT EXISTS pending_disabled_messages (
|
||||||
"channel_id TEXT NOT NULL," +
|
guild_id TEXT NOT NULL,
|
||||||
"message_id TEXT NOT NULL," +
|
channel_id TEXT NOT NULL,
|
||||||
"expiry_timestamp TEXT NOT NULL " +
|
message_id TEXT NOT NULL,
|
||||||
");");
|
expiry_timestamp TEXT NOT NULL);
|
||||||
|
""");
|
||||||
|
|
||||||
newTables.add("CREATE TABLE IF NOT EXISTS command_runners (" +
|
newTables.add("""
|
||||||
"guild_id TEXT NOT NULL, " +
|
CREATE TABLE IF NOT EXISTS command_runners (
|
||||||
"channel_id TEXT NOT NULL," + // channel the command was run in
|
guild_id TEXT NOT NULL,
|
||||||
"message_id TEXT NOT NULL," + // message id of the bot's response
|
channel_id TEXT NOT NULL,
|
||||||
"user_id TEXT NOT NULL, " + // user who ran the command
|
message_id TEXT NOT NULL,
|
||||||
"channel_type TEXT NOT NULL" + // channel type (PRIVATE, FORUM, ...)
|
user_id TEXT NOT NULL,
|
||||||
");");
|
channel_type TEXT NOT NULL);
|
||||||
|
""");
|
||||||
|
|
||||||
newTables.add("CREATE TABLE IF NOT EXISTS urban_dictionary (" +
|
newTables.add("""
|
||||||
"message_id TEXT NOT NULL, " + // message id of the bot's response
|
CREATE TABLE IF NOT EXISTS urban_dictionary (
|
||||||
"page INTEGER NOT NULL," + // page that we are currently on
|
message_id TEXT NOT NULL,
|
||||||
"meanings TEXT NOT NULL," + // list of all meanings, serialized and encoded
|
page INTEGER NOT NULL,
|
||||||
"examples TEXT NOT NULL, " + // list of all examples, serialized and encoded
|
meanings TEXT NOT NULL,
|
||||||
"contributors TEXT NOT NULL, " + // list of all contributors, serialized and encoded
|
examples TEXT NOT NULL,
|
||||||
"dates TEXT NOT NULL, " + // list of all submission dates, serialized and encoded
|
contributors TEXT NOT NULL,
|
||||||
"term TEXT NOT NULL" + // the term that was searched
|
dates TEXT NOT NULL,
|
||||||
");");
|
term TEXT NOT NULL
|
||||||
|
);
|
||||||
|
""");
|
||||||
|
|
||||||
for (String sql : newTables)
|
for (String sql : newTables)
|
||||||
{
|
{
|
||||||
try (Statement stmt = dbConnection.createStatement()) {
|
try (Statement stmt = dbConnection.createStatement())
|
||||||
|
{
|
||||||
// execute the statement
|
// execute the statement
|
||||||
stmt.execute(sql);
|
stmt.execute(sql);
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -147,7 +156,8 @@ public class DatabaseSource
|
|||||||
if (!(channelType.isGuild()))
|
if (!(channelType.isGuild()))
|
||||||
{
|
{
|
||||||
guildId = userId;
|
guildId = userId;
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
guildId = message.getGuild().getId();
|
guildId = message.getGuild().getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,9 +165,11 @@ public class DatabaseSource
|
|||||||
String messageId = message.getId();
|
String messageId = message.getId();
|
||||||
|
|
||||||
|
|
||||||
String query = "INSERT INTO command_runners " +
|
String query = """
|
||||||
"(guild_id, channel_id, message_id, user_id, channel_type) VALUES " +
|
INSERT INTO command_runners
|
||||||
" (?, ?, ?, ?, ?);";
|
(guild_id, channel_id, message_id, user_id, channel_type) VALUES
|
||||||
|
(?, ?, ?, ?, ?);
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -187,9 +199,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public ChannelType getTrackedMessageChannelType(String messageId)
|
public ChannelType getTrackedMessageChannelType(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT channel_type " +
|
String query = """
|
||||||
"FROM command_runners " +
|
SELECT channel_type
|
||||||
"WHERE message_id = ?;";
|
FROM command_runners
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -202,7 +216,8 @@ public class DatabaseSource
|
|||||||
return ChannelType.valueOf(channelTypeName);
|
return ChannelType.valueOf(channelTypeName);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,9 +227,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getTrackedReplyUserId(String messageId)
|
public String getTrackedReplyUserId(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT user_id " +
|
String query = """
|
||||||
"FROM command_runners " +
|
SELECT user_id
|
||||||
"WHERE message_id = ?;";
|
FROM command_runners
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -226,7 +243,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("user_id");
|
return resultSet.getString("user_id");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,7 +261,8 @@ public class DatabaseSource
|
|||||||
if (!(channelType.isGuild()))
|
if (!(channelType.isGuild()))
|
||||||
{
|
{
|
||||||
guildId = "PRIVATE";
|
guildId = "PRIVATE";
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
guildId = message.getGuild().getId();
|
guildId = message.getGuild().getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,9 +271,11 @@ public class DatabaseSource
|
|||||||
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
|
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
|
||||||
String expiryTimeFormatted = dateTimeFormatter.format(expiryTime);
|
String expiryTimeFormatted = dateTimeFormatter.format(expiryTime);
|
||||||
|
|
||||||
String query = "INSERT INTO pending_disabled_messages " +
|
String query = """
|
||||||
"(guild_id, channel_id, message_id, expiry_timestamp) VALUES " +
|
INSERT INTO pending_disabled_messages
|
||||||
" (?, ?, ?, ?);";
|
(guild_id, channel_id, message_id, expiry_timestamp) VALUES
|
||||||
|
(?, ?, ?, ?);
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -278,8 +299,10 @@ public class DatabaseSource
|
|||||||
{
|
{
|
||||||
List<String> messages = new ArrayList<>();
|
List<String> messages = new ArrayList<>();
|
||||||
|
|
||||||
String query = "SELECT message_id " +
|
String query = """
|
||||||
"FROM pending_disabled_messages ";
|
SELECT message_id
|
||||||
|
FROM pending_disabled_messages;
|
||||||
|
""";
|
||||||
|
|
||||||
try (Statement statement = dbConnection.createStatement())
|
try (Statement statement = dbConnection.createStatement())
|
||||||
{
|
{
|
||||||
@@ -289,7 +312,8 @@ public class DatabaseSource
|
|||||||
{
|
{
|
||||||
messages.add(resultSet.getString("message_id"));
|
messages.add(resultSet.getString("message_id"));
|
||||||
}
|
}
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,9 +361,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getQueuedExpiringMessageExpiryDate(String messageId)
|
public String getQueuedExpiringMessageExpiryDate(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT expiry_timestamp " +
|
String query = """
|
||||||
"FROM pending_disabled_messages " +
|
SELECT expiry_timestamp
|
||||||
"WHERE message_id = ?;";
|
FROM pending_disabled_messages
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -351,7 +377,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("expiry_timestamp");
|
return resultSet.getString("expiry_timestamp");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -360,9 +387,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getQueuedExpiringMessageChannel(String messageId)
|
public String getQueuedExpiringMessageChannel(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT channel_id " +
|
String query = """
|
||||||
"FROM pending_disabled_messages " +
|
SELECT channel_id
|
||||||
"WHERE message_id = ?;";
|
FROM pending_disabled_messages
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -374,7 +403,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("channel_id");
|
return resultSet.getString("channel_id");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,9 +413,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getQueuedExpiringMessageGuild(String messageId)
|
public String getQueuedExpiringMessageGuild(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT guild_id " +
|
String query = """
|
||||||
"FROM pending_disabled_messages " +
|
SELECT guild_id
|
||||||
"WHERE message_id = ?;";
|
FROM pending_disabled_messages
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -397,7 +429,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("guild_id");
|
return resultSet.getString("guild_id");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,9 +442,11 @@ public class DatabaseSource
|
|||||||
Message message, String term)
|
Message message, String term)
|
||||||
{
|
{
|
||||||
|
|
||||||
String query = "INSERT INTO urban_dictionary " +
|
String query = """
|
||||||
"(message_id, page, meanings, examples, contributors, dates, term) VALUES " +
|
INSERT INTO urban_dictionary
|
||||||
" (?, ?, ?, ?, ?, ?, ?);";
|
(message_id, page, meanings, examples, contributors, dates, term) VALUES
|
||||||
|
(?, ?, ?, ?, ?, ?, ?);
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -436,9 +471,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public int getUrbanPage(String messageId)
|
public int getUrbanPage(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT page " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT page
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -450,7 +487,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getInt("page");
|
return resultSet.getInt("page");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -459,9 +497,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getUrbanMeanings(String messageId)
|
public String getUrbanMeanings(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT meanings " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT meanings
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -473,7 +513,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("meanings");
|
return resultSet.getString("meanings");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,9 +523,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getUrbanExamples(String messageId)
|
public String getUrbanExamples(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT examples " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT examples
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -496,7 +539,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("examples");
|
return resultSet.getString("examples");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -505,9 +549,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getUrbanContributors(String messageId)
|
public String getUrbanContributors(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT contributors " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT contributors
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -519,7 +565,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("contributors");
|
return resultSet.getString("contributors");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -528,9 +575,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getUrbanDates(String messageId)
|
public String getUrbanDates(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT dates " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT dates
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -542,7 +591,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("dates");
|
return resultSet.getString("dates");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -551,9 +601,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public String getUrbanTerm(String messageId)
|
public String getUrbanTerm(String messageId)
|
||||||
{
|
{
|
||||||
String query = "SELECT term " +
|
String query = """
|
||||||
"FROM urban_dictionary " +
|
SELECT term
|
||||||
"WHERE message_id = ?;";
|
FROM urban_dictionary
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -565,7 +617,8 @@ public class DatabaseSource
|
|||||||
return resultSet.getString("term");
|
return resultSet.getString("term");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -574,9 +627,11 @@ public class DatabaseSource
|
|||||||
|
|
||||||
public boolean setUrbanPage(String messageId, int page)
|
public boolean setUrbanPage(String messageId, int page)
|
||||||
{
|
{
|
||||||
String query = "UPDATE urban_dictionary " +
|
String query = """
|
||||||
"SET page = ? " +
|
UPDATE urban_dictionary
|
||||||
"WHERE message_id = ?;";
|
SET page = ?
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -586,7 +641,8 @@ public class DatabaseSource
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -600,9 +656,11 @@ public class DatabaseSource
|
|||||||
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
|
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
|
||||||
String expiryTimeFormatted = dateTimeFormatter.format(expiryTime);
|
String expiryTimeFormatted = dateTimeFormatter.format(expiryTime);
|
||||||
|
|
||||||
String query = "UPDATE pending_disabled_messages " +
|
String query = """
|
||||||
"SET expiry_timestamp = ? " +
|
UPDATE pending_disabled_messages
|
||||||
"WHERE message_id = ?;";
|
SET expiry_timestamp = ?
|
||||||
|
WHERE message_id = ?;
|
||||||
|
""";
|
||||||
|
|
||||||
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
|
||||||
{
|
{
|
||||||
@@ -612,7 +670,8 @@ public class DatabaseSource
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e)
|
||||||
|
{
|
||||||
logException(e);
|
logException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ public class PropertiesSource
|
|||||||
{
|
{
|
||||||
properties.load(internalPropertiesStream);
|
properties.load(internalPropertiesStream);
|
||||||
|
|
||||||
}
|
} catch (IOException e)
|
||||||
catch (IOException e) {
|
{
|
||||||
LOGGER.error(e.getMessage());
|
LOGGER.error(e.getMessage());
|
||||||
HidekoBot.shutdown();
|
HidekoBot.shutdown();
|
||||||
return;
|
return;
|
||||||
@@ -34,5 +34,7 @@ public class PropertiesSource
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getProperty(String property)
|
public String getProperty(String property)
|
||||||
{ return properties == null ? "" : properties.getProperty(property); }
|
{
|
||||||
|
return properties == null ? "" : properties.getProperty(property);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package wtf.beatrice.hidekobot.listeners;
|
|||||||
|
|
||||||
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
|
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
|
||||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import wtf.beatrice.hidekobot.commands.base.CoinFlip;
|
import wtf.beatrice.hidekobot.commands.base.CoinFlip;
|
||||||
import wtf.beatrice.hidekobot.commands.base.Trivia;
|
import wtf.beatrice.hidekobot.commands.base.Trivia;
|
||||||
import wtf.beatrice.hidekobot.commands.base.UrbanDictionary;
|
import wtf.beatrice.hidekobot.commands.base.UrbanDictionary;
|
||||||
@@ -10,11 +12,14 @@ import wtf.beatrice.hidekobot.util.CommandUtil;
|
|||||||
public class ButtonInteractionListener extends ListenerAdapter
|
public class ButtonInteractionListener extends ListenerAdapter
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(ButtonInteractionListener.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onButtonInteraction(ButtonInteractionEvent event)
|
public void onButtonInteraction(ButtonInteractionEvent event)
|
||||||
{
|
{
|
||||||
|
|
||||||
switch (event.getComponentId().toLowerCase()) {
|
switch (event.getComponentId().toLowerCase())
|
||||||
|
{
|
||||||
|
|
||||||
// coinflip
|
// coinflip
|
||||||
case "coinflip_reflip" -> CoinFlip.buttonReFlip(event);
|
case "coinflip_reflip" -> CoinFlip.buttonReFlip(event);
|
||||||
@@ -31,6 +36,10 @@ public class ButtonInteractionListener extends ListenerAdapter
|
|||||||
case "trivia_wrong_1", "trivia_wrong_2", "trivia_wrong_3" ->
|
case "trivia_wrong_1", "trivia_wrong_2", "trivia_wrong_3" ->
|
||||||
Trivia.handleAnswer(event, Trivia.AnswerType.WRONG);
|
Trivia.handleAnswer(event, Trivia.AnswerType.WRONG);
|
||||||
|
|
||||||
|
// error handling
|
||||||
|
default -> LOGGER.warn("Received unhandled {}", event.getClass().getSimpleName());
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import wtf.beatrice.hidekobot.Cache;
|
|||||||
import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
|
import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
|
||||||
import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
|
import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
|
||||||
import wtf.beatrice.hidekobot.objects.comparators.MessageCommandAliasesComparator;
|
import wtf.beatrice.hidekobot.objects.comparators.MessageCommandAliasesComparator;
|
||||||
import wtf.beatrice.hidekobot.util.Logger;
|
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@@ -20,13 +19,13 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
|
|
||||||
// map storing command labels and command object alphabetically.
|
// map storing command labels and command object alphabetically.
|
||||||
private final TreeMap<LinkedList<String>, MessageCommand> registeredCommands =
|
private final TreeMap<LinkedList<String>, MessageCommand> registeredCommands =
|
||||||
new TreeMap<LinkedList<String>, MessageCommand>(new MessageCommandAliasesComparator());
|
new TreeMap<>(new MessageCommandAliasesComparator());
|
||||||
|
|
||||||
// map commands and their categories.
|
// map commands and their categories.
|
||||||
// this is not strictly needed but it's better to have it so we avoid looping every time we need to check the cat.
|
// this is not strictly needed but it's better to have it so we avoid looping every time we need to check the cat.
|
||||||
LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>();
|
LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>();
|
||||||
|
|
||||||
private final String commandRegex = "(?i)^(hideko|hde)\\b";
|
private static final String COMMAND_REGEX = "(?i)^(hideko|hde)\\b";
|
||||||
// (?i) -> case insensitive flag
|
// (?i) -> case insensitive flag
|
||||||
// ^ -> start of string (not in middle of a sentence)
|
// ^ -> start of string (not in middle of a sentence)
|
||||||
// \b -> the word has to end here
|
// \b -> the word has to end here
|
||||||
@@ -39,12 +38,16 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
|
|
||||||
public MessageCommand getRegisteredCommand(String label)
|
public MessageCommand getRegisteredCommand(String label)
|
||||||
{
|
{
|
||||||
for(LinkedList<String> aliases : registeredCommands.keySet())
|
for (Map.Entry<LinkedList<String>, MessageCommand> entry : registeredCommands.entrySet())
|
||||||
{
|
{
|
||||||
|
LinkedList<String> aliases = entry.getKey();
|
||||||
|
|
||||||
for (String currentAlias : aliases)
|
for (String currentAlias : aliases)
|
||||||
{
|
{
|
||||||
if (label.equals(currentAlias))
|
if (label.equals(currentAlias))
|
||||||
{ return registeredCommands.get(aliases); }
|
{
|
||||||
|
return entry.getValue();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,10 +55,9 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
}
|
}
|
||||||
|
|
||||||
public LinkedList<MessageCommand> getRegisteredCommands()
|
public LinkedList<MessageCommand> getRegisteredCommands()
|
||||||
{ return new LinkedList<>(registeredCommands.values()); }
|
{
|
||||||
|
return new LinkedList<>(registeredCommands.values());
|
||||||
|
}
|
||||||
private final Logger logger = new Logger(MessageCommandListener.class);
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onMessageReceived(@NotNull MessageReceivedEvent event)
|
public void onMessageReceived(@NotNull MessageReceivedEvent event)
|
||||||
@@ -67,11 +69,11 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
String eventMessage = event.getMessage().getContentRaw();
|
String eventMessage = event.getMessage().getContentRaw();
|
||||||
|
|
||||||
// check if the sent message matches the bot activation regex (prefix, name, ...)
|
// check if the sent message matches the bot activation regex (prefix, name, ...)
|
||||||
if(!eventMessage.toLowerCase().matches("(?s)" + commandRegex + ".*"))
|
if (!eventMessage.toLowerCase().matches("(?s)" + COMMAND_REGEX + ".*"))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// generate args from the string
|
// generate args from the string
|
||||||
String argsString = eventMessage.replaceAll(commandRegex + "\\s*", "");
|
String argsString = eventMessage.replaceAll(COMMAND_REGEX + "\\s*", "");
|
||||||
|
|
||||||
|
|
||||||
// if no args were specified apart from the bot prefix
|
// if no args were specified apart from the bot prefix
|
||||||
@@ -115,16 +117,13 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
{
|
{
|
||||||
Member member = event.getMember();
|
Member member = event.getMember();
|
||||||
GuildChannel channel = event.getGuildChannel(); //todo: what about forum post
|
GuildChannel channel = event.getGuildChannel(); //todo: what about forum post
|
||||||
if(member != null)
|
if (member != null && !member.hasPermission(channel, requiredPermissions))
|
||||||
{
|
|
||||||
if(!member.hasPermission(channel, requiredPermissions))
|
|
||||||
{
|
{
|
||||||
event.getMessage()
|
event.getMessage()
|
||||||
.reply("You do not have permissions to run this command!")
|
.reply("You do not have permissions to run this command!")
|
||||||
.queue(); // todo prettier
|
.queue(); // todo prettier
|
||||||
// todo: queue message deletion in 15 seconds or so
|
// todo: queue message deletion in 15 seconds or so
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,8 +137,7 @@ public class MessageCommandListener extends ListenerAdapter
|
|||||||
argsString = argsString.replaceAll("^[\\S]+\\s*", "");
|
argsString = argsString.replaceAll("^[\\S]+\\s*", "");
|
||||||
// pass all other arguments as a single argument as the first array element
|
// pass all other arguments as a single argument as the first array element
|
||||||
commandArgs = new String[]{argsString};
|
commandArgs = new String[]{argsString};
|
||||||
}
|
} else
|
||||||
else
|
|
||||||
{
|
{
|
||||||
// copy all split arguments to the array, except from the command label
|
// copy all split arguments to the array, except from the command label
|
||||||
commandArgs = Arrays.copyOfRange(argsRaw, 1, argsRaw.length);
|
commandArgs = Arrays.copyOfRange(argsRaw, 1, argsRaw.length);
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ public class MessageLogger extends ListenerAdapter
|
|||||||
{
|
{
|
||||||
// this class only gets loaded as a listener if verbosity is set to true on startup.
|
// this class only gets loaded as a listener if verbosity is set to true on startup.
|
||||||
|
|
||||||
private static final String guildChannelFormat = "[%guild%] [#%channel%] %user%: %message%";
|
private static final String GUILD_MESSAGE_LOG_FORMAT = "[%guild%] [#%channel%] %user%: %message%";
|
||||||
private static final String dmFormat = "[DM] %user%: %message%";
|
private static final String DIRECT_MESSAGE_LOG_FORMAT = "[DM] %user%: %message%";
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogger.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogger.class);
|
||||||
|
|
||||||
@@ -25,18 +25,17 @@ public class MessageLogger extends ListenerAdapter
|
|||||||
String userName = event.getAuthor().getAsTag();
|
String userName = event.getAuthor().getAsTag();
|
||||||
String message = event.getMessage().getContentDisplay();
|
String message = event.getMessage().getContentDisplay();
|
||||||
|
|
||||||
if(event.getChannel() instanceof TextChannel)
|
if (event.getChannel() instanceof TextChannel channel)
|
||||||
{
|
{
|
||||||
String guildName = ((TextChannel) event.getChannel()).getGuild().getName();
|
String guildName = channel.getGuild().getName();
|
||||||
String channelName = event.getChannel().getName();
|
String channelName = event.getChannel().getName();
|
||||||
|
|
||||||
toLog = guildChannelFormat
|
toLog = GUILD_MESSAGE_LOG_FORMAT
|
||||||
.replace("%guild%", guildName)
|
.replace("%guild%", guildName)
|
||||||
.replace("%channel%", channelName);
|
.replace("%channel%", channelName);
|
||||||
}
|
} else if (event.getChannel() instanceof PrivateChannel)
|
||||||
else if(event.getChannel() instanceof PrivateChannel)
|
|
||||||
{
|
{
|
||||||
toLog = dmFormat;
|
toLog = DIRECT_MESSAGE_LOG_FORMAT;
|
||||||
}
|
}
|
||||||
|
|
||||||
toLog = toLog
|
toLog = toLog
|
||||||
|
|||||||
@@ -2,18 +2,26 @@ package wtf.beatrice.hidekobot.listeners;
|
|||||||
|
|
||||||
import net.dv8tion.jda.api.events.interaction.component.StringSelectInteractionEvent;
|
import net.dv8tion.jda.api.events.interaction.component.StringSelectInteractionEvent;
|
||||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import wtf.beatrice.hidekobot.commands.base.Trivia;
|
import wtf.beatrice.hidekobot.commands.base.Trivia;
|
||||||
|
|
||||||
public class SelectMenuInteractionListener extends ListenerAdapter
|
public class SelectMenuInteractionListener extends ListenerAdapter
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(SelectMenuInteractionListener.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onStringSelectInteraction(StringSelectInteractionEvent event)
|
public void onStringSelectInteraction(StringSelectInteractionEvent event)
|
||||||
{
|
{
|
||||||
switch (event.getComponentId().toLowerCase()) {
|
switch (event.getComponentId().toLowerCase())
|
||||||
|
{
|
||||||
|
|
||||||
// trivia
|
// trivia
|
||||||
case "trivia_categories" -> Trivia.handleMenuSelection(event);
|
case "trivia_categories" -> Trivia.handleMenuSelection(event);
|
||||||
|
|
||||||
|
// error handling
|
||||||
|
default -> LOGGER.warn("Received unhandled {}", event.getClass().getSimpleName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,10 +21,15 @@ public class SlashCommandCompletionListener extends ListenerAdapter
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SlashArgumentsCompleter getRegisteredCompleter(String label)
|
public SlashArgumentsCompleter getRegisteredCompleter(String label)
|
||||||
{ return registeredCompleters.get(label); }
|
{
|
||||||
|
return registeredCompleters.get(label);
|
||||||
|
}
|
||||||
|
|
||||||
public LinkedList<SlashArgumentsCompleter> getRegisteredCompleters()
|
public LinkedList<SlashArgumentsCompleter> getRegisteredCompleters()
|
||||||
{ return new LinkedList<>(registeredCompleters.values()); }
|
{
|
||||||
|
return new LinkedList<>(registeredCompleters.values());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event)
|
public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -21,10 +21,14 @@ public class SlashCommandListener extends ListenerAdapter
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SlashCommand getRegisteredCommand(String label)
|
public SlashCommand getRegisteredCommand(String label)
|
||||||
{ return registeredCommands.get(label); }
|
{
|
||||||
|
return registeredCommands.get(label);
|
||||||
|
}
|
||||||
|
|
||||||
public LinkedList<SlashCommand> getRegisteredCommands()
|
public LinkedList<SlashCommand> getRegisteredCommands()
|
||||||
{ return new LinkedList<>(registeredCommands.values()); }
|
{
|
||||||
|
return new LinkedList<>(registeredCommands.values());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event)
|
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event)
|
||||||
|
|||||||
@@ -9,10 +9,12 @@ import java.util.Objects;
|
|||||||
|
|
||||||
public record MessageResponse(@Nullable String content,
|
public record MessageResponse(@Nullable String content,
|
||||||
@Nullable MessageEmbed embed,
|
@Nullable MessageEmbed embed,
|
||||||
@Nullable ItemComponent... components) {
|
@Nullable ItemComponent... components)
|
||||||
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o)
|
||||||
|
{
|
||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
if (o == null || getClass() != o.getClass()) return false;
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
MessageResponse response = (MessageResponse) o;
|
MessageResponse response = (MessageResponse) o;
|
||||||
@@ -22,14 +24,16 @@ public record MessageResponse(@Nullable String content,
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode()
|
||||||
|
{
|
||||||
int result = Objects.hash(content, embed);
|
int result = Objects.hash(content, embed);
|
||||||
result = 31 * result + Arrays.hashCode(components);
|
result = 31 * result + Arrays.hashCode(components);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString()
|
||||||
|
{
|
||||||
return "MessageResponse{" +
|
return "MessageResponse{" +
|
||||||
"content=" + content +
|
"content=" + content +
|
||||||
", embed=" + embed +
|
", embed=" + embed +
|
||||||
|
|||||||
@@ -9,10 +9,14 @@ public enum CommandCategory
|
|||||||
;
|
;
|
||||||
|
|
||||||
private String emoji;
|
private String emoji;
|
||||||
|
|
||||||
CommandCategory(String emoji)
|
CommandCategory(String emoji)
|
||||||
{
|
{
|
||||||
this.emoji = emoji;
|
this.emoji = emoji;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getEmoji() { return emoji; }
|
public String getEmoji()
|
||||||
|
{
|
||||||
|
return emoji;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,9 +70,7 @@ public interface MessageCommand
|
|||||||
*
|
*
|
||||||
* @param event the received message event. It should not be used for parsing message contents data as
|
* @param event the received message event. It should not be used for parsing message contents data as
|
||||||
* the arguments already account for it in a better way.
|
* the arguments already account for it in a better way.
|
||||||
*
|
|
||||||
* @param label the command label that was used, taken from all available command aliases.
|
* @param label the command label that was used, taken from all available command aliases.
|
||||||
*
|
|
||||||
* @param args a pre-formatted list of arguments, excluding the bot prefix and the command name.
|
* @param args a pre-formatted list of arguments, excluding the bot prefix and the command name.
|
||||||
* This is useful because command logic won't have to change in case the bot prefix is changed,
|
* This is useful because command logic won't have to change in case the bot prefix is changed,
|
||||||
* removed, or we switch to another method of triggering commands (ping, trigger words, ...).
|
* removed, or we switch to another method of triggering commands (ping, trigger words, ...).
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ public interface SlashArgumentsCompleter
|
|||||||
* @return the command object.
|
* @return the command object.
|
||||||
*/
|
*/
|
||||||
SlashCommand getCommand();
|
SlashCommand getCommand();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run the argument-completion logic by parsing the event and replying accordingly.
|
* Run the argument-completion logic by parsing the event and replying accordingly.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ import org.jetbrains.annotations.NotNull;
|
|||||||
public class SlashArgumentsCompleterImpl implements SlashArgumentsCompleter
|
public class SlashArgumentsCompleterImpl implements SlashArgumentsCompleter
|
||||||
{
|
{
|
||||||
private final SlashCommand parentCommand;
|
private final SlashCommand parentCommand;
|
||||||
|
|
||||||
public SlashArgumentsCompleterImpl(SlashCommand parentCommand)
|
public SlashArgumentsCompleterImpl(SlashCommand parentCommand)
|
||||||
{
|
{
|
||||||
this.parentCommand = parentCommand;
|
this.parentCommand = parentCommand;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SlashCommand getCommand()
|
public SlashCommand getCommand()
|
||||||
{ return parentCommand; }
|
{
|
||||||
|
return parentCommand;
|
||||||
|
}
|
||||||
|
|
||||||
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event)
|
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ public interface SlashCommand
|
|||||||
* @return the command data object.
|
* @return the command data object.
|
||||||
*/
|
*/
|
||||||
CommandData getSlashCommandData();
|
CommandData getSlashCommandData();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run the command logic by parsing the event and replying accordingly.
|
* Run the command logic by parsing the event and replying accordingly.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -8,17 +8,20 @@ public class SlashCommandImpl implements SlashCommand
|
|||||||
{
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getCommandName() {
|
public String getCommandName()
|
||||||
|
{
|
||||||
return getSlashCommandData().getName();
|
return getSlashCommandData().getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CommandData getSlashCommandData() {
|
public CommandData getSlashCommandData()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) {
|
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
|
||||||
|
{
|
||||||
event.reply("Base command implementation").queue();
|
event.reply("Base command implementation").queue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,12 @@ import java.util.LinkedList;
|
|||||||
/**
|
/**
|
||||||
* This class gets two linked lists, and compares their first value alphabetically.
|
* This class gets two linked lists, and compares their first value alphabetically.
|
||||||
*/
|
*/
|
||||||
public class MessageCommandAliasesComparator implements Comparator<LinkedList<String>> {
|
public class MessageCommandAliasesComparator implements Comparator<LinkedList<String>>
|
||||||
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(LinkedList<String> linkedList, LinkedList<String> t1) {
|
public int compare(LinkedList<String> linkedList, LinkedList<String> t1)
|
||||||
|
{
|
||||||
|
|
||||||
if (linkedList.isEmpty()) return 0;
|
if (linkedList.isEmpty()) return 0;
|
||||||
if (t1.isEmpty()) return 0;
|
if (t1.isEmpty()) return 0;
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ import java.util.Comparator;
|
|||||||
/**
|
/**
|
||||||
* This class gets two trivia categories, and compares them by their name.
|
* This class gets two trivia categories, and compares them by their name.
|
||||||
*/
|
*/
|
||||||
public class TriviaCategoryComparator implements Comparator<TriviaCategory> {
|
public class TriviaCategoryComparator implements Comparator<TriviaCategory>
|
||||||
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(TriviaCategory o1, TriviaCategory o2) {
|
public int compare(TriviaCategory o1, TriviaCategory o2)
|
||||||
|
{
|
||||||
return CharSequence.compare(o1.categoryName(), o2.categoryName());
|
return CharSequence.compare(o1.categoryName(), o2.categoryName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ import java.util.Comparator;
|
|||||||
/**
|
/**
|
||||||
* This class gets two trivia scores, and compares their score.
|
* This class gets two trivia scores, and compares their score.
|
||||||
*/
|
*/
|
||||||
public class TriviaScoreComparator implements Comparator<TriviaScore> {
|
public class TriviaScoreComparator implements Comparator<TriviaScore>
|
||||||
|
{
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(TriviaScore o1, TriviaScore o2) {
|
public int compare(TriviaScore o1, TriviaScore o2)
|
||||||
|
{
|
||||||
return Integer.compare(o2.getScore(), o1.getScore()); // inverted, because higher number should come first
|
return Integer.compare(o2.getScore(), o1.getScore()); // inverted, because higher number should come first
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package wtf.beatrice.hidekobot.objects.fun;
|
package wtf.beatrice.hidekobot.objects.fun;
|
||||||
|
|
||||||
public record TriviaCategory(String categoryName, int categoryId) {
|
public record TriviaCategory(String categoryName, int categoryId)
|
||||||
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package wtf.beatrice.hidekobot.objects.fun;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public record TriviaQuestion(String question, String correctAnswer,
|
public record TriviaQuestion(String question, String correctAnswer,
|
||||||
List<String> wrongAnswers) {
|
List<String> wrongAnswers)
|
||||||
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,9 +18,15 @@ public class TriviaScore
|
|||||||
score += add;
|
score += add;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getScore() { return score; }
|
public int getScore()
|
||||||
|
{
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
public User getUser() { return user; }
|
public User getUser()
|
||||||
|
{
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString()
|
public String toString()
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class ExpiredMessageTask implements Runnable {
|
public class ExpiredMessageTask implements Runnable
|
||||||
|
{
|
||||||
|
|
||||||
private final DateTimeFormatter formatter;
|
private final DateTimeFormatter formatter;
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(ExpiredMessageTask.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(ExpiredMessageTask.class);
|
||||||
@@ -26,7 +27,8 @@ public class ExpiredMessageTask implements Runnable {
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run()
|
||||||
|
{
|
||||||
|
|
||||||
databaseSource = Cache.getDatabaseSource();
|
databaseSource = Cache.getDatabaseSource();
|
||||||
if (databaseSource == null) return;
|
if (databaseSource == null) return;
|
||||||
@@ -42,7 +44,7 @@ public class ExpiredMessageTask implements Runnable {
|
|||||||
if (Cache.isVerbose()) LOGGER.info("expired check: {}", messageId);
|
if (Cache.isVerbose()) LOGGER.info("expired check: {}", messageId);
|
||||||
|
|
||||||
String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId);
|
String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId);
|
||||||
if(expiryTimestamp == null || expiryTimestamp.equals("")) // if missing timestamp
|
if (expiryTimestamp == null || expiryTimestamp.isEmpty()) // if missing timestamp
|
||||||
{
|
{
|
||||||
// count it as already expired
|
// count it as already expired
|
||||||
databaseSource.untrackExpiredMessage(messageId);
|
databaseSource.untrackExpiredMessage(messageId);
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ public class HeartBeatTask implements Runnable
|
|||||||
String urlString = Cache.getFullHeartBeatLink();
|
String urlString = Cache.getFullHeartBeatLink();
|
||||||
if (urlString == null || urlString.isEmpty()) return;
|
if (urlString == null || urlString.isEmpty()) return;
|
||||||
|
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
|
|
||||||
URL heartbeatUrl = new URL(urlString);
|
URL heartbeatUrl = new URL(urlString);
|
||||||
|
|
||||||
@@ -32,13 +33,13 @@ public class HeartBeatTask implements Runnable
|
|||||||
{
|
{
|
||||||
// only log ok response codes when verbosity is enabled
|
// only log ok response codes when verbosity is enabled
|
||||||
if (Cache.isVerbose()) LOGGER.info("Heartbeat response code: {}", responseCode);
|
if (Cache.isVerbose()) LOGGER.info("Heartbeat response code: {}", responseCode);
|
||||||
}
|
} else
|
||||||
else
|
|
||||||
{
|
{
|
||||||
LOGGER.error("Heartbeat returned problematic response code: {}", responseCode);
|
LOGGER.error("Heartbeat returned problematic response code: {}", responseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e)
|
||||||
|
{
|
||||||
LOGGER.error("Error while trying to push heartbeat", e);
|
LOGGER.error("Error while trying to push heartbeat", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ public class StatusUpdateTask implements Runnable
|
|||||||
);
|
);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run()
|
||||||
|
{
|
||||||
int randomPos = RandomUtil.getRandomNumber(0, statuses.size() - 1);
|
int randomPos = RandomUtil.getRandomNumber(0, statuses.size() - 1);
|
||||||
String status = statuses.get(randomPos) + " | " + Cache.getBotPrefix() + " help";
|
String status = statuses.get(randomPos) + " | " + Cache.getBotPrefix() + " help";
|
||||||
HidekoBot.getAPI().getPresence().setActivity(Activity.playing(status));
|
HidekoBot.getAPI().getPresence().setActivity(Activity.playing(status));
|
||||||
|
|||||||
@@ -93,12 +93,14 @@ public class TriviaTask implements Runnable
|
|||||||
previousScore = score;
|
previousScore = score;
|
||||||
topScore = score;
|
topScore = score;
|
||||||
pos = 1;
|
pos = 1;
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
if (score != previousScore) pos++;
|
if (score != previousScore) pos++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pos == 1) winners.add(user);
|
if (pos == 1) winners.add(user);
|
||||||
else {
|
else
|
||||||
|
{
|
||||||
othersBuilder.append("\n").append(pos)
|
othersBuilder.append("\n").append(pos)
|
||||||
.append(" | ").append(user)
|
.append(" | ").append(user)
|
||||||
.append(": ").append(score).append(" points");
|
.append(": ").append(score).append(" points");
|
||||||
@@ -113,7 +115,8 @@ public class TriviaTask implements Runnable
|
|||||||
if (i + 1 != winners.size())
|
if (i + 1 != winners.size())
|
||||||
{
|
{
|
||||||
winnersBuilder.append(", "); // separate with comma except on last run
|
winnersBuilder.append(", "); // separate with comma except on last run
|
||||||
} else {
|
} else
|
||||||
|
{
|
||||||
winnersBuilder.append(": ").append(topScore).append(" points \uD83C\uDF89");
|
winnersBuilder.append(": ").append(topScore).append(" points \uD83C\uDF89");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,11 @@ public class CommandUtil
|
|||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);
|
||||||
|
|
||||||
|
private CommandUtil()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Function to delete a message when a user clicks the "delete" button attached to that message.
|
* Function to delete a message when a user clicks the "delete" button attached to that message.
|
||||||
* This will check in the database if that user ran the command originally.
|
* This will check in the database if that user ran the command originally.
|
||||||
@@ -36,7 +41,8 @@ public class CommandUtil
|
|||||||
public static void delete(ButtonInteractionEvent event)
|
public static void delete(ButtonInteractionEvent event)
|
||||||
{
|
{
|
||||||
// check if the user interacting is the same one who ran the command
|
// check if the user interacting is the same one who ran the command
|
||||||
if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) {
|
if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
|
||||||
|
{
|
||||||
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
|
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -60,7 +66,9 @@ public class CommandUtil
|
|||||||
// populate commands list from registered commands
|
// populate commands list from registered commands
|
||||||
List<CommandData> allCommands = new ArrayList<>();
|
List<CommandData> allCommands = new ArrayList<>();
|
||||||
for (SlashCommand cmd : Cache.getSlashCommandListener().getRegisteredCommands())
|
for (SlashCommand cmd : Cache.getSlashCommandListener().getRegisteredCommands())
|
||||||
{ allCommands.add(cmd.getSlashCommandData()); }
|
{
|
||||||
|
allCommands.add(cmd.getSlashCommandData());
|
||||||
|
}
|
||||||
|
|
||||||
JDA jdaInstance = HidekoBot.getAPI();
|
JDA jdaInstance = HidekoBot.getAPI();
|
||||||
|
|
||||||
@@ -185,8 +193,7 @@ public class CommandUtil
|
|||||||
}
|
}
|
||||||
|
|
||||||
textChannel = user.openPrivateChannel().complete();
|
textChannel = user.openPrivateChannel().complete();
|
||||||
}
|
} else
|
||||||
else
|
|
||||||
{
|
{
|
||||||
String guildId = databaseSource.getQueuedExpiringMessageGuild(messageId);
|
String guildId = databaseSource.getQueuedExpiringMessageGuild(messageId);
|
||||||
Guild guild = guildId == null ? null : HidekoBot.getAPI().getGuildById(guildId);
|
Guild guild = guildId == null ? null : HidekoBot.getAPI().getGuildById(guildId);
|
||||||
|
|||||||
@@ -12,17 +12,21 @@ import java.util.Arrays;
|
|||||||
public class FormatUtil
|
public class FormatUtil
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private FormatUtil()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
// cosmetic string to print on startup.
|
// cosmetic string to print on startup.
|
||||||
private static final String LOGO = """
|
private static final String LOGO = """
|
||||||
|
\s
|
||||||
██╗░░██╗██╗██████╗░███████╗██╗░░██╗░█████╗░
|
██╗░░██╗██╗██████╗░███████╗██╗░░██╗░█████╗░
|
||||||
██║░░██║██║██╔══██╗██╔════╝██║░██╔╝██╔══██╗
|
██║░░██║██║██╔══██╗██╔════╝██║░██╔╝██╔══██╗
|
||||||
███████║██║██║░░██║█████╗░░█████═╝░██║░░██║
|
███████║██║██║░░██║█████╗░░█████═╝░██║░░██║
|
||||||
██╔══██║██║██║░░██║██╔══╝░░██╔═██╗░██║░░██║
|
██╔══██║██║██║░░██║██╔══╝░░██╔═██╗░██║░░██║
|
||||||
██║░░██║██║██████╔╝███████╗██║░╚██╗╚█████╔╝
|
██║░░██║██║██████╔╝███████╗██║░╚██╗╚█████╔╝
|
||||||
╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░
|
╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░
|
||||||
""";
|
\s""";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,32 +63,28 @@ public class FormatUtil
|
|||||||
*/
|
*/
|
||||||
public static String getNiceDuration(Duration duration)
|
public static String getNiceDuration(Duration duration)
|
||||||
{
|
{
|
||||||
long seconds = duration.toSecondsPart();
|
|
||||||
long minutes = duration.toMinutesPart();
|
|
||||||
long hours = duration.toHoursPart();
|
|
||||||
long days = duration.toDays();
|
long days = duration.toDays();
|
||||||
|
long hours = duration.toHoursPart();
|
||||||
|
long minutes = duration.toMinutesPart();
|
||||||
|
long seconds = duration.toSecondsPart();
|
||||||
|
|
||||||
StringBuilder uptimeStringBuilder = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
if(days == 0)
|
if (days > 0)
|
||||||
{
|
{
|
||||||
if(hours == 0)
|
sb.append(days).append("d ");
|
||||||
|
sb.append(hours).append("h ");
|
||||||
|
sb.append(minutes).append("m ");
|
||||||
|
} else if (hours > 0)
|
||||||
{
|
{
|
||||||
if(minutes == 0)
|
sb.append(hours).append("h ");
|
||||||
{} else { // i know this if has an empty body but i feel like this reads better
|
sb.append(minutes).append("m ");
|
||||||
uptimeStringBuilder.append(minutes).append("m ");
|
} else if (minutes > 0)
|
||||||
|
{
|
||||||
|
sb.append(minutes).append("m ");
|
||||||
}
|
}
|
||||||
} else {
|
sb.append(seconds).append("s");
|
||||||
uptimeStringBuilder.append(hours).append("h ");
|
|
||||||
uptimeStringBuilder.append(minutes).append("m ");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
uptimeStringBuilder.append(days).append("d ");
|
|
||||||
uptimeStringBuilder.append(hours).append("h ");
|
|
||||||
uptimeStringBuilder.append(minutes).append("m ");
|
|
||||||
}
|
|
||||||
uptimeStringBuilder.append(seconds).append("s ");
|
|
||||||
|
|
||||||
return uptimeStringBuilder.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -143,7 +143,7 @@ public class FormatUtil
|
|||||||
// we won't do any sanitization, because this is a private method, and
|
// we won't do any sanitization, because this is a private method, and
|
||||||
// we are only accessing it with things that we know for sure are already sanitized.
|
// we are only accessing it with things that we know for sure are already sanitized.
|
||||||
unitName = unitName.toLowerCase();
|
unitName = unitName.toLowerCase();
|
||||||
TemporalUnit timeUnit = null;
|
TemporalUnit timeUnit;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
parsing table
|
parsing table
|
||||||
@@ -161,6 +161,7 @@ public class FormatUtil
|
|||||||
case "m", "mi", "min", "minute", "minutes" -> timeUnit = ChronoUnit.MINUTES;
|
case "m", "mi", "min", "minute", "minutes" -> timeUnit = ChronoUnit.MINUTES;
|
||||||
case "h", "ho", "hr", "hour", "hours" -> timeUnit = ChronoUnit.HOURS;
|
case "h", "ho", "hr", "hour", "hours" -> timeUnit = ChronoUnit.HOURS;
|
||||||
case "d", "day", "days" -> timeUnit = ChronoUnit.DAYS;
|
case "d", "day", "days" -> timeUnit = ChronoUnit.DAYS;
|
||||||
|
default -> timeUnit = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return timeUnit;
|
return timeUnit;
|
||||||
|
|||||||
@@ -3,21 +3,22 @@ package wtf.beatrice.hidekobot.util;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
@Deprecated
|
@Deprecated(since = "0.5.16", forRemoval = true)
|
||||||
public class Logger
|
public class Logger<T>
|
||||||
{
|
{
|
||||||
|
|
||||||
// objects that we need to have for a properly formatted message
|
// objects that we need to have for a properly formatted message
|
||||||
private String className;
|
private final String className;
|
||||||
private final String format = "[%date% %time%] [%class%] %message%";
|
private final String format = "[%date% %time%] [%class%] %message%";
|
||||||
private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
|
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
|
||||||
|
|
||||||
|
|
||||||
// when initializing a new logger, save variables in that instance
|
// when initializing a new logger, save variables in that instance
|
||||||
public Logger(Class logClass)
|
public Logger(Class<T> logClass)
|
||||||
{
|
{
|
||||||
className = logClass.getSimpleName();
|
className = logClass.getSimpleName();
|
||||||
}
|
}
|
||||||
@@ -49,7 +50,10 @@ public class Logger
|
|||||||
{
|
{
|
||||||
// create a new scheduled executor with an anonymous runnable...
|
// create a new scheduled executor with an anonymous runnable...
|
||||||
//... after waiting <delay> seconds.
|
//... after waiting <delay> seconds.
|
||||||
Executors.newSingleThreadScheduledExecutor().schedule(() -> log(message), delay, TimeUnit.SECONDS);
|
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
|
||||||
|
{
|
||||||
|
executor.schedule(() -> log(message), delay, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ import java.util.Random;
|
|||||||
public class RandomUtil
|
public class RandomUtil
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private RandomUtil()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
// the Random instance that we should always use when looking for an RNG based thing.
|
// the Random instance that we should always use when looking for an RNG based thing.
|
||||||
// the seed is updated periodically, if the random.org integration is enabled.
|
// the seed is updated periodically, if the random.org integration is enabled.
|
||||||
private static Random randomInstance = new SecureRandom();
|
private static Random randomInstance = new SecureRandom();
|
||||||
@@ -43,7 +48,8 @@ public class RandomUtil
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Random getRandom() {
|
public static Random getRandom()
|
||||||
|
{
|
||||||
return randomInstance;
|
return randomInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,29 +10,38 @@ import java.util.List;
|
|||||||
public class SerializationUtil
|
public class SerializationUtil
|
||||||
{
|
{
|
||||||
|
|
||||||
public static String serializeBase64(List dataList) {
|
private SerializationUtil()
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> String serializeBase64(List<T> dataList)
|
||||||
|
{
|
||||||
|
|
||||||
try (ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
try (ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
||||||
ObjectOutputStream so = new ObjectOutputStream(bo)) {
|
ObjectOutputStream so = new ObjectOutputStream(bo))
|
||||||
|
{
|
||||||
so.writeObject(dataList);
|
so.writeObject(dataList);
|
||||||
so.flush();
|
so.flush();
|
||||||
return Base64.getEncoder().encodeToString(bo.toByteArray());
|
return Base64.getEncoder().encodeToString(bo.toByteArray());
|
||||||
}
|
} catch (IOException e)
|
||||||
catch (IOException e) {
|
{
|
||||||
throw new SerializationException("Error during serialization", e);
|
throw new SerializationException("Error during serialization", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static LinkedList deserializeBase64(String dataStr) {
|
public static <T> LinkedList<T> deserializeBase64(String dataStr)
|
||||||
|
{
|
||||||
|
|
||||||
byte[] b = Base64.getDecoder().decode(dataStr);
|
byte[] b = Base64.getDecoder().decode(dataStr);
|
||||||
ByteArrayInputStream bi = new ByteArrayInputStream(b);
|
ByteArrayInputStream bi = new ByteArrayInputStream(b);
|
||||||
ObjectInputStream si;
|
ObjectInputStream si;
|
||||||
try {
|
try
|
||||||
|
{
|
||||||
si = new ObjectInputStream(bi);
|
si = new ObjectInputStream(bi);
|
||||||
return LinkedList.class.cast(si.readObject());
|
return LinkedList.class.cast(si.readObject());
|
||||||
}
|
} catch (IOException | ClassNotFoundException e)
|
||||||
catch (IOException | ClassNotFoundException e) {
|
{
|
||||||
throw new SerializationException("Error during deserialization", e);
|
throw new SerializationException("Error during deserialization", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
bot.version=${project.version}
|
bot.version=${project.version}
|
||||||
|
repo.base_url=https://git.beatrice.wtf/bea/HidekoBot/
|
||||||
12
suppressions.xml
Normal file
12
suppressions.xml
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd">
|
||||||
|
<!--
|
||||||
|
<suppress>
|
||||||
|
<notes><![CDATA[
|
||||||
|
file name: snakeyaml-1.33.jar
|
||||||
|
]]></notes>
|
||||||
|
<packageUrl regex="true">^pkg:maven/org\.yaml/snakeyaml@.*$</packageUrl>
|
||||||
|
<cve>CVE-2021-4235</cve>
|
||||||
|
</suppress>
|
||||||
|
-->
|
||||||
|
</suppressions>
|
||||||
Reference in New Issue
Block a user