├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── examples
├── README.md
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── examples
│ ├── package-info.java
│ ├── doc
│ └── Author.java
│ └── command
│ ├── ShutdownCommand.java
│ ├── PingCommand.java
│ ├── ServerinfoCommand.java
│ ├── GuildlistCommand.java
│ ├── RoleinfoCommand.java
│ └── AboutCommand.java
├── oauth2
├── README.md
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── oauth2
│ ├── exceptions
│ ├── InvalidStateException.java
│ └── MissingScopeException.java
│ ├── state
│ ├── DefaultStateController.java
│ └── StateController.java
│ ├── session
│ ├── Session.java
│ ├── SessionController.java
│ ├── DefaultSessionController.java
│ └── SessionData.java
│ ├── requests
│ ├── OAuth2URL.java
│ ├── OAuth2Requester.java
│ └── OAuth2Action.java
│ ├── entities
│ ├── impl
│ │ ├── OAuth2GuildImpl.java
│ │ ├── OAuth2UserImpl.java
│ │ └── OAuth2ClientImpl.java
│ ├── OAuth2Guild.java
│ └── OAuth2User.java
│ ├── Scope.java
│ └── OAuth2Client.java
├── commons
├── README.md
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── commons
│ ├── package-info.java
│ ├── JDAUtilitiesInfo.java
│ └── utils
│ ├── SafeIdUtil.java
│ └── FixedSizeCache.java
├── .gitattributes
├── menu
├── README.md
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── menu
│ └── package-info.java
├── doc
├── README.md
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── doc
│ ├── package-info.java
│ ├── standard
│ ├── Errors.java
│ ├── RequiredPermissions.java
│ ├── Error.java
│ └── CommandInfo.java
│ ├── ConvertedBy.java
│ ├── DocMultiple.java
│ └── DocConverter.java
├── gradle.properties
├── settings.gradle
├── .editorconfig
├── .gitignore
├── .github
├── PULL_REQUEST_TEMPLATE.md
└── ISSUE_TEMPLATE.md
├── command
├── build.gradle
├── README.md
└── src
│ └── main
│ └── java
│ └── com
│ └── jagrosh
│ └── jdautilities
│ └── command
│ ├── AnnotatedModuleCompiler.java
│ ├── GuildSettingsManager.java
│ ├── GuildSettingsProvider.java
│ ├── package-info.java
│ ├── CommandListener.java
│ ├── impl
│ └── AnnotatedModuleCompilerImpl.java
│ └── annotation
│ └── JDACommand.java
├── gradlew.bat
├── README.md
└── gradlew
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JDA-Applications/JDA-Utilities/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | # Examples Package
2 |
3 | Contains various examples demonstrating some functionality of the other packages
4 | that are part of this library.
5 |
--------------------------------------------------------------------------------
/oauth2/README.md:
--------------------------------------------------------------------------------
1 | # Oauth2 Package
2 |
3 | Tools for interacting with Discord's Oauth2 API, as documented [here](https://discord.com/developers/docs/topics/oauth2)
4 |
--------------------------------------------------------------------------------
/commons/README.md:
--------------------------------------------------------------------------------
1 | # Commons Package
2 |
3 | Contains various tools and resources used throughout the other packages contained in
4 | this library, such as **EventWaiter** and **FinderUtil**.
5 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | gradlew binary
2 |
3 | .gitattributes text eol=crlf
4 |
5 | *.java text eol=crlf
6 | *.gradle text eol=crlf
7 | *.properties text eol=crlf
8 | *.md text eol=crlf
9 |
10 | * text=auto
11 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/menu/README.md:
--------------------------------------------------------------------------------
1 | # Menu Package
2 |
3 | Interactive, organized, dynamic menus for your Discord bot.
4 |
5 | This framework is great for giving your users a beautiful interactive response
6 | to anything, from paginating items, to labelled options with reaction buttons.
7 |
8 | **Note:** This package makes heavy use of `EventWaiter`, which is a part of the
9 | [commons package](https://github.com/JDA-Applications/JDA-Utilities/tree/master/commons).
10 |
--------------------------------------------------------------------------------
/doc/README.md:
--------------------------------------------------------------------------------
1 | # Doc Package
2 |
3 | Flexible runtime documentation for any bot's commands. With the CommandDoc system,
4 | any bot can have organized, formatted, and detailed documentation of it's functions.
5 |
6 | ```java
7 | @CommandInfo
8 | (
9 | name = {"mycommand", "coolcommand"},
10 | description = "Use this command if you are cool! B)",
11 | requirements = {"You must be cool."}
12 | )
13 | @Error("You are not cool enough to use this command :(")
14 | public class MyCommand
15 | {
16 | // ...
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | bintrayUsername=
18 | bintrayApiKey=
19 |
--------------------------------------------------------------------------------
/commons/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 | }
19 |
--------------------------------------------------------------------------------
/doc/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 |
19 | compile commons()
20 | }
21 |
--------------------------------------------------------------------------------
/menu/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 | compile findbugs()
19 | compile commons()
20 | }
21 |
--------------------------------------------------------------------------------
/oauth2/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 | compile findbugs()
19 | compile json()
20 |
21 | compile commons()
22 | }
23 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | rootProject.name = 'JDA-Utilities'
17 |
18 | include ':command'
19 | include ':commons'
20 | include ':doc'
21 | include ':examples'
22 | include ':menu'
23 | include ':oauth2'
24 |
--------------------------------------------------------------------------------
/examples/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 | compile slf4j()
19 |
20 | compile commons()
21 | compile command()
22 | compile menu()
23 | compile doc()
24 | }
25 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | root = true
16 |
17 | [*]
18 | end_of_line = crlf
19 | insert_final_newline = true
20 |
21 | [gradlew]
22 | end_of_line = lf
23 |
24 | [*.{java, md, gradle, properties}]
25 | charset = utf-8
26 | indent_style = space
27 | indent_size = 4
28 |
--------------------------------------------------------------------------------
/doc/src/main/java/com/jagrosh/jdautilities/doc/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * Items in this package pertain to the {@link com.jagrosh.jdautilities.doc.DocGenerator DocGenerator}.
19 | */
20 | package com.jagrosh.jdautilities.doc;
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # gradle
16 | **/build/
17 | /.gradle/
18 | /gradle.properties
19 |
20 | # eclipse files
21 | .classpath
22 | .project
23 | .settings/
24 | /bin/
25 |
26 | # intellij files
27 | **/out/
28 | .idea/
29 | *.iml
30 | *.ipr
31 | *.iws
32 |
33 | # netbeans files
34 | /target/
35 | /.nb-gradle/
36 | *.nb-gradle-properties
37 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | [contributing]: https://github.com/DV8FromTheWorld/JDA/wiki/5%29-Contributing
2 | [pull-request]: https://github.com/JDA-Applications/JDA-Utilities/pulls
3 |
4 | ## Pull Request
5 |
6 | #### Pull Request Checklist
7 | Please follow the following steps before opening this PR.
8 | PRs that do not complete the checklist will be subject to denial for
9 | missing information.
10 |
11 | - [ ] I have checked the [pull request page][pull-request] for upcoming
12 | or merged features/bug fixes.
13 | - [ ] I have read JDA's [contributing guidelines][contributing].
14 |
15 | #### Pull Request Information
16 | Check and fill in the blanks for all that apply:
17 |
18 | - [ ] My PR fixes a bug, error, or other issue with the library's codebase.
19 | - [ ] My PR is for the `______` module of the JDA-Utilities library.
20 | - [ ] My PR creates a new module for the JDA-Utilities library: `______`.
21 |
22 | #### Description
23 |
24 | Describe your PR here.
25 |
--------------------------------------------------------------------------------
/command/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | dependencies {
17 | compileOnly jda()
18 | compile slf4j()
19 | compile okhttp()
20 | compile findbugs()
21 | compile json()
22 |
23 | compile commons()
24 | }
25 |
26 | javadoc {
27 | exclude 'com/jagrosh/jdautilities/commandclient/impl'
28 | }
29 |
--------------------------------------------------------------------------------
/command/README.md:
--------------------------------------------------------------------------------
1 | # Command Package
2 |
3 | A easy to use, powerful, and highly flexible command framework for bots using JDA.
4 |
5 | This package includes all the tools necessary to start a fully functioning JDA bot
6 | with commands, making use of the **Command Client**.
7 |
8 | ```java
9 | public class MyBot
10 | {
11 | public static void main(String[] args)
12 | {
13 | CommandClientBuilder builder = new CommandClientBuilder();
14 |
15 | // Set your bot's prefix
16 | builder.setPrefix("!");
17 | builder.setAlternatePrefix("+");
18 |
19 | // Add commands
20 | builder.addCommand(new CoolCommand());
21 |
22 | // Customize per-guild unique settings
23 | builder.setGuildSettingsManager(new MyBotsGuildSettingsManager());
24 |
25 | CommandClient client = builder.build();
26 |
27 | new JDABuilder(AccountType.BOT)
28 | // ...
29 | .addEventListener(client) // Add the new CommandClient as a listener
30 | // ...
31 | .buildAsync();
32 | }
33 | }
34 | ```
35 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/exceptions/InvalidStateException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.exceptions;
17 |
18 | /**
19 | * Exception raised when the provided OAuth2 state is not valid.
20 | *
21 | *
Not to be confused with {@link java.lang.IllegalStateException IllegalStateException}
22 | *
23 | * @author John Grosh (john.a.grosh@gmail.com)
24 | */
25 | public class InvalidStateException extends Exception
26 | {
27 | public InvalidStateException(String message)
28 | {
29 | super(message);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/examples/src/main/java/com/jagrosh/jdautilities/examples/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * Common package for all available example classes.
19 | *
20 | *
The contents of this package are summarized as follows: 21 | *
The contents of this package are summarized as follows: 22 | *
Only annotations with this annotation applied to it are valid for processing
26 | * via an instance of {@link com.jagrosh.jdautilities.doc.DocGenerator DocGenerator}.
27 | *
28 | * @see DocConverter
29 | *
30 | * @since 2.0
31 | * @author Kaidan Gustave
32 | */
33 | @Documented
34 | @Retention(RetentionPolicy.RUNTIME)
35 | @Target(ElementType.ANNOTATION_TYPE)
36 | public @interface ConvertedBy
37 | {
38 | /**
39 | * The {@link com.jagrosh.jdautilities.doc.DocConverter DocConverter}
40 | * Class that the annotation this is applied to provides to
41 | * {@link com.jagrosh.jdautilities.doc.DocConverter#read(Annotation)
42 | * DocConverter#read(Annotation)}.
43 | *
44 | * @return The DocConverter Class to use.
45 | */
46 | Class extends DocConverter> value();
47 | }
48 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/state/DefaultStateController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.state;
17 |
18 | import java.util.HashMap;
19 |
20 | /**
21 | * The default {@link com.jagrosh.jdautilities.oauth2.state.StateController StateController} implementation.
22 | *
23 | * @author John Grosh (john.a.grosh@gmail.com)
24 | */
25 | public class DefaultStateController implements StateController
26 | {
27 | private final static String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
28 | private final HashMap Naturally, states should be unique, and attempting to
23 | * generate a redirect using a previously used state should
24 | * return {@code null} instead of a new redirect URI.
25 | *
26 | * @author John Grosh (john.a.grosh@gmail.com)
27 | */
28 | public interface StateController
29 | {
30 | /**
31 | * Generates a new state string using the provided redirect URI.
32 | *
33 | * @param redirectUri
34 | * The redirect URI that will be used with this state.
35 | *
36 | * @return The state string.
37 | */
38 | String generateNewState(String redirectUri);
39 |
40 | /**
41 | * Consumes a state to get the corresponding redirect URI.
42 | *
43 | * Once this method is called for a specific state, it
44 | * should return null for all future calls of that same state.
45 | *
46 | * @param state
47 | * The state.
48 | *
49 | * @return The redirect URI, or {@code null} if the state does not exist.
50 | */
51 | String consumeState(String state);
52 | }
53 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | [download]: https://bintray.com/jagrosh/maven/JDA-Utilities/_latestVersion
2 | [guild]: https://discord.gg/0hMr4ce0tIk3pSjp
3 | [stack overflow]: https://stackoverflow.com/questions/tagged/java
4 | [issues]: https://github.com/JDA-Applications/JDA-Utilities/issues
5 | [jda-issues]: https://github.com/DV8FromTheWorld/JDA/issues
6 | [examples-module]: https://github.com/JDA-Applications/JDA-Utilities/tree/master/examples
7 | [jda-u-projects]: https://github.com/JDA-Applications/JDA-Utilities#projects
8 |
9 | ## Issue
10 |
11 | #### Issue Checklist
12 | Please follow the following steps before opening this issue. Please note that this entire package makes HEAVY usage of the
43 | * {@link com.jagrosh.jdautilities.commons.waiter.EventWaiter EventWaiter}.
44 | */
45 | package com.jagrosh.jdautilities.menu;
46 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/session/Session.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.session;
17 |
18 | import com.jagrosh.jdautilities.oauth2.Scope;
19 | import java.time.OffsetDateTime;
20 |
21 | /**
22 | * Implementable data type used to allow access to data regarding OAuth2 sessions.
23 | *
24 | * This can be used with a proper {@link com.jagrosh.jdautilities.oauth2.OAuth2Client OAuth2Client}
25 | * to get information on the logged in {@link com.jagrosh.jdautilities.oauth2.entities.OAuth2User User},
26 | * as well as {@link com.jagrosh.jdautilities.oauth2.entities.OAuth2Guild Guilds} they are on.
27 | *
28 | * @author John Grosh (john.a.grosh@gmail.com)
29 | * @author Kaidan Gustave
30 | */
31 | public interface Session
32 | {
33 | /**
34 | * Gets the session's access token.
35 | *
36 | * @return The session's access token.
37 | */
38 | String getAccessToken();
39 |
40 | /**
41 | * Gets the session's refresh token.
42 | *
43 | * @return The session's refresh token.
44 | */
45 | String getRefreshToken();
46 |
47 | /**
48 | * Gets the session's {@link com.jagrosh.jdautilities.oauth2.Scope Scopes}.
49 | *
50 | * @return The session's Scopes.
51 | */
52 | Scope[] getScopes();
53 |
54 | /**
55 | * Gets the session's token type.
56 | *
57 | * @return The session's token type.
58 | */
59 | String getTokenType();
60 |
61 | /**
62 | * Gets the session's expiration time.
63 | *
64 | * @return The session's expiration time.
65 | */
66 | OffsetDateTime getExpiration();
67 | }
68 |
--------------------------------------------------------------------------------
/commons/src/main/java/com/jagrosh/jdautilities/commons/JDAUtilitiesInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.commons;
17 |
18 | /**
19 | * Information regarding the library.
20 | * This is best coupled with usage of an {@link java.lang.annotation.Repeatable @Repeatable}
25 | * annotation and a similarly named holder annotation for multiple occurrences.
26 | * Previous to version 1.6 all Commands required the Command abstract class to be extended in source.
26 | * The primary issue that came with this was that Commands were restricted to that method of creation, offering
27 | * no support for popular means such as annotated commands.
28 | *
29 | * Since 1.6 the introduction of {@link com.jagrosh.jdautilities.command.CommandBuilder CommandBuilder}
30 | * has allowed the potential to create unique {@link com.jagrosh.jdautilities.command.Command Command}
31 | * objects after compilation.
32 | * This Object must be annotated with {@link
46 | * com.jagrosh.jdautilities.command.annotation.JDACommand.Module @JDACommand.Module}!
47 | *
48 | * @param o
49 | * The Object, annotated with {@code @JDACommand.Module}.
50 | *
51 | * @return A {@link java.util.List} of Commands generated from the provided Object
52 | */
53 | List Standard implementations should be able to simply provide a
27 | * type of {@link java.lang.Object Object} provided a non-null
28 | * {@link net.dv8tion.jda.api.entities.Guild Guild}. Further
29 | * customization of the implementation is allowed on the developer
30 | * end.
31 | *
32 | * @param Developers should implement this method to create or initialize resources when starting their bot.
66 | */
67 | default void init() {}
68 |
69 | /**
70 | * Called when JDA has fired a {@link net.dv8tion.jda.api.events.ShutdownEvent ShutdownEvent}.
71 | *
72 | * Developers should implement this method to free up or close resources when shutting their bot.
73 | */
74 | default void shutdown() {}
75 | }
76 |
--------------------------------------------------------------------------------
/command/src/main/java/com/jagrosh/jdautilities/command/GuildSettingsProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.command;
17 |
18 | import javax.annotation.Nullable;
19 | import java.util.Collection;
20 |
21 | /**
22 | * A basic frame that is optionally implementable by objects returned from
23 | * {@link GuildSettingsManager#getSettings(net.dv8tion.jda.api.entities.Guild)
24 | * GuildSettingsManager#getSettings(Guild)}.
25 | *
26 | * This interface allows the specification of any of the following functions:
27 | * An empty Collection or {@code null} may be returned to signify the Guild
55 | * doesn't have any guild specific prefixes, or that this feature is not supported
56 | * by this implementation.
57 | *
58 | * @return A Collection of String prefixes for the Guild represented by this
59 | * implementation, or {@code null} to signify it has none or that the
60 | * feature is not supported by the implementation.
61 | */
62 | @Nullable
63 | default Collection It is very important for implementations of SessionController to hold
38 | * a contract that Sessions created using {@link #createSession(SessionData)}
39 | * will be maintained and retrievable by external sources at any time.
40 | *
41 | * Note that Sessions that have elapsed their effective
42 | * {@link com.jagrosh.jdautilities.oauth2.session.SessionData#getExpiration() expiration}
43 | * are not necessary to maintain, unless they have been refreshed in which case they
44 | * should be updated to reflect this.
45 | *
46 | * @param identifier
47 | * The identifier to get a Session by.
48 | *
49 | * @return The Session mapped to the identifier provided.
50 | */
51 | S getSession(String identifier);
52 |
53 | /**
54 | * Creates a new {@link com.jagrosh.jdautilities.oauth2.session.Session Session} using
55 | * the specified {@link com.jagrosh.jdautilities.oauth2.session.SessionData SessionData}.
56 | *
57 | * Sessions should be kept mapped outside of just creation so that they can be
58 | * retrieved using {@link SessionController#getSession(String)} later for further
59 | * manipulation, as well as to keep updated if they are refreshed.
60 | *
61 | * @param data
62 | * The data to create a Session using.
63 | *
64 | * @return A new Session.
65 | */
66 | S createSession(SessionData data);
67 | }
68 |
--------------------------------------------------------------------------------
/doc/src/main/java/com/jagrosh/jdautilities/doc/standard/RequiredPermissions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.doc.standard;
17 |
18 | import com.jagrosh.jdautilities.doc.ConvertedBy;
19 | import com.jagrosh.jdautilities.doc.DocConverter;
20 | import net.dv8tion.jda.api.Permission;
21 |
22 | import java.lang.annotation.*;
23 |
24 | /**
25 | * A CommandDoc {@link java.lang.annotation.Annotation Annotation} that lists
26 | * required {@link net.dv8tion.jda.api.Permission Permission}s a bot must have
27 | * to use a command on a {@link net.dv8tion.jda.api.entities.Guild Guild}.
28 | *
29 | * @since 2.0
30 | * @author Kaidan Gustave
31 | */
32 | @ConvertedBy(RequiredPermissions.Converter.class)
33 | @Documented
34 | @Retention(RetentionPolicy.RUNTIME)
35 | @Target({ElementType.TYPE, ElementType.METHOD})
36 | public @interface RequiredPermissions
37 | {
38 | /**
39 | * An array of {@link net.dv8tion.jda.api.Permission Permission}s
40 | * a bot must have to run the command.
41 | *
42 | * @return The array of permissions
43 | */
44 | Permission[] value();
45 |
46 | /**
47 | * The {@link com.jagrosh.jdautilities.doc.DocConverter DocConverter} for the
48 | * {@link com.jagrosh.jdautilities.doc.standard.RequiredPermissions @RequiredPermissions}
49 | * annotation.
50 | */
51 | class Converter implements DocConverter These are the fundamental building blocks behind command doc annotations, and can
26 | * be applied using the {@link com.jagrosh.jdautilities.doc.ConvertedBy @ConvertedBy}
27 | * annotation:
28 | *
29 | * All of the contents are used heavily in the {@link com.jagrosh.jdautilities.command.impl.CommandClientImpl CommandClientImpl},
22 | * and are summarized as follows:
23 | * Note that this is effectively a wrapper for both the Guild info, as well
29 | * as the info on the user in the guild represented by the session that got this Guild.
30 | *
31 | * @author John Grosh (john.a.grosh@gmail.com)
32 | * @author Kaidan Gustave
33 | */
34 | public interface OAuth2Guild extends ISnowflake
35 | {
36 | /**
37 | * Gets the underlying {@link com.jagrosh.jdautilities.oauth2.OAuth2Client OAuth2Client}
38 | * that created this OAuth2Guild.
39 | *
40 | * @return The OAuth2Client that created this OAuth2Guild.
41 | */
42 | OAuth2Client getClient();
43 |
44 | /**
45 | * Gets the Guild's name.
46 | *
47 | * @return The Guild's name.
48 | */
49 | String getName();
50 |
51 | /**
52 | * Gets the Guild's icon ID, or {@code null} if the Guild does not have an icon.
53 | *
54 | * @return The Guild's icon ID.
55 | */
56 | String getIconId();
57 |
58 | /**
59 | * Gets the Guild's icon URL, or {@code null} if the Guild does not have an icon.
60 | *
61 | * @return The Guild's icon URL.
62 | */
63 | String getIconUrl();
64 |
65 | /**
66 | * Gets the Session User's raw permission value for the Guild.
67 | *
68 | * @return The Session User's raw permission value for the Guild.
69 | */
70 | int getPermissionsRaw();
71 |
72 | /**
73 | * Gets the Session User's {@link net.dv8tion.jda.api.Permission Permissions} for the Guild.
74 | *
75 | * @return The Session User's Permissions for the Guild.
76 | */
77 | EnumSet This class contains two static methods:
24 | * These are formatted ways to describe errors and provide the {@link com.jagrosh.jdautilities.doc.standard.Error#response()}
29 | * method for specifying the bot's response if the error occurs.
30 | *
31 | * Multiples of these can be applied using the
32 | * {@link com.jagrosh.jdautilities.doc.standard.Errors @Errors} annotation, or simply
33 | * multiples of these can be attached to a class or method.
34 | *
35 | * Below is a visual of what this should generally look like:
36 | * This annotation should be used for "primary" documented
29 | * information, and when applicable, developers who are using the
30 | * {@link com.jagrosh.jdautilities.doc.DocGenerator DocGenerator}
31 | * returned by {@link com.jagrosh.jdautilities.doc.DocGenerator#getDefaultGenerator()},
32 | * and who are not implementing their own CommandDoc systems, should
33 | * use this in place of creating a new annotation and converter if
34 | * possible.
35 | *
36 | * @since 2.0
37 | * @author Kaidan Gustave
38 | */
39 | @ConvertedBy(CommandInfo.Converter.class)
40 | @Documented
41 | @Retention(RetentionPolicy.RUNTIME)
42 | @Target({ElementType.TYPE, ElementType.METHOD})
43 | public @interface CommandInfo
44 | {
45 | /**
46 | * The name and aliases of a command.
47 | *
48 | * The first one should be the official name, and following
49 | * elements should be aliases (if any are allowed).
50 | *
51 | * @return The name and aliases
52 | */
53 | String[] name() default {};
54 |
55 | /**
56 | * A short format or explanation of a command's usage.
57 | *
58 | * @return The usage
59 | */
60 | String usage() default "";
61 |
62 | /**
63 | * A description of this command, what it does, and
64 | * (if needed) elaboration on the {@link com.jagrosh.jdautilities.doc.standard.CommandInfo#usage()}.
65 | *
66 | * @return The description of this command
67 | */
68 | String description() default "";
69 |
70 | /**
71 | * A series of prerequisites or requirements a user
72 | * must have to use this command.
73 | *
74 | * @return The requirements to use the command
75 | */
76 | String[] requirements() default {};
77 |
78 | /**
79 | * The {@link com.jagrosh.jdautilities.doc.DocConverter DocConverter} for
80 | * the {@link com.jagrosh.jdautilities.doc.standard.CommandInfo @CommandInfo}
81 | * annotation.
82 | */
83 | class Converter implements DocConverter As new elements are inserted into the cache, older ones may be removed as a result of the cache
27 | * being at the maximum capacity set at instantiation.
28 | *
29 | * @since 1.3
30 | * @author Michael Ritter
31 | */
32 | public class FixedSizeCache This entity runs on the basis of "first-in-first-out", meaning that elements inserted
43 | * into the newly constructed cache will remove the oldest ones if the maximum size is
44 | * already being occupied.
45 | *
46 | * @param size
47 | * The size of the FixedSizeCache to be created.
48 | */
49 | @SuppressWarnings("unchecked")
50 | public FixedSizeCache(int size)
51 | {
52 | this.map = new HashMap<>();
53 | if(size < 1)
54 | throw new IllegalArgumentException("Cache size must be at least 1!");
55 | this.keys = (K[]) new Object[size];
56 | }
57 |
58 | /**
59 | * Adds a key and pairs it with a value.
60 | *
61 | * If this {@link com.jagrosh.jdautilities.commons.utils.FixedSizeCache FixedSizeCache}
62 | * is already at maximum occupation, this will remove the oldest element.
63 | *
64 | * NOTE: Any inner workings of {@link java.util.HashMap#put(Object, Object)
65 | * HashMap#put(Object, Object)} still apply when using this method!
66 | * NOTE: Any inner workings of {@link java.util.HashMap#containsKey(Object)
91 | * HashMap#containsKey(Object)} still apply when using this method!
92 | * NOTE: Any inner workings of {@link java.util.HashMap#get(Object)
112 | * HashMap#get(Object)} still apply when using this method!
113 | * Note that a successfully completed command is one that has not encountered
45 | * an error or exception. Calls that do face errors should be handled by
46 | * {@link CommandListener#onCommandException(CommandEvent, Command, Throwable) CommandListener#onCommandException}
47 | *
48 | * @param event
49 | * The CommandEvent that triggered the Command
50 | * @param command
51 | * The Command that was triggered
52 | */
53 | default void onCompletedCommand(CommandEvent event, Command command) {}
54 |
55 | /**
56 | * Called when a {@link com.jagrosh.jdautilities.command.Command Command} is triggered
57 | * by a {@link com.jagrosh.jdautilities.command.CommandEvent CommandEvent} but is
58 | * terminated before completion.
59 | *
60 | * @param event
61 | * The CommandEvent that triggered the Command
62 | * @param command
63 | * The Command that was triggered
64 | */
65 | default void onTerminatedCommand(CommandEvent event, Command command) {}
66 |
67 | /**
68 | * Called when a {@link net.dv8tion.jda.api.events.message.MessageReceivedEvent MessageReceivedEvent}
69 | * is caught by the Client Listener's but doesn't correspond to a
70 | * {@link com.jagrosh.jdautilities.command.Command Command}.
71 | *
72 | * In other words, this catches all non-command MessageReceivedEvents allowing
73 | * you to handle them without implementation of another listener.
74 | *
75 | * @param event
76 | * A MessageReceivedEvent that wasn't used to call a Command
77 | */
78 | default void onNonCommandMessage(MessageReceivedEvent event) {}
79 |
80 | /**
81 | * Called when a {@link com.jagrosh.jdautilities.command.Command Command}
82 | * catches a {@link java.lang.Throwable Throwable} during execution.
83 | *
84 | * This doesn't account for exceptions thrown during other pre-checks,
85 | * and should not be treated as such!
86 | *
87 | * An example of this misconception is via a
88 | * {@link com.jagrosh.jdautilities.command.Command.Category Category} test:
89 | *
90 | * All OAuth2 sessions can act within' their available scope upon creation,
22 | * and as such, these are specified in when the session's are created.
23 | *
24 | * @author John Grosh (john.a.grosh@gmail.com)
25 | */
26 | public enum Scope
27 | {
28 | /**
29 | * For oauth2 bots, this puts the bot in the user's selected guild by default
30 | */
31 | BOT("bot"),
32 |
33 | /**
34 | * Allows /users/@me/connections to return linked third-party accounts
35 | */
36 | CONNECTIONS("connections"),
37 |
38 | /**
39 | * Enables /users/@me to return an email
40 | */
41 | EMAIL("email"),
42 |
43 | /**
44 | * Allows /users/@me without email
45 | */
46 | IDENTIFY("identify"),
47 |
48 | /**
49 | * Allows /users/@me/guilds to return basic information about all of a user's guilds
50 | */
51 | GUILDS("guilds"),
52 |
53 | /**
54 | * Allows /invites/{invite.id} to be used for joining users to a guild
55 | */
56 | GUILDS_JOIN("guilds.join"),
57 |
58 | /**
59 | * Allows your app to join users to a group dm
60 | */
61 | GDM_JOIN("gdm.join"),
62 |
63 | /**
64 | * For local rpc server api access, this allows you to read messages from all
65 | * client channels (otherwise restricted to channels/guilds your app creates)
66 | */
67 | MESSAGES_READ("messages.read"),
68 |
69 | /**
70 | * For local rpc server access, this allows you to control a user's local Discord client
71 | */
72 | RPC("rpc"),
73 |
74 | /**
75 | * For local rpc server api access, this allows you to access the API as the local user
76 | */
77 | RPC_API("rpc.api"),
78 |
79 | /**
80 | * For local rpc server api access, this allows you to receive notifications pushed out to the user
81 | */
82 | RPC_NOTIFICATIONS_READ("rpc.notifications.read"),
83 |
84 | /**
85 | * This generates a webhook that is returned in the oauth token response for authorization code grants
86 | */
87 | WEBHOOK_INCOMING("webhook.incoming"),
88 |
89 | /**
90 | * Unknown scope
91 | */
92 | UNKNOWN("");
93 |
94 | private final String text;
95 |
96 | Scope(String text)
97 | {
98 | this.text = text;
99 | }
100 |
101 | /**
102 | * The text key associated with this scope.
103 | *
104 | * @return The text key associated with this scope.
105 | */
106 | public String getText()
107 | {
108 | return text;
109 | }
110 |
111 | public static boolean contains(Scope[] scopes, Scope scope)
112 | {
113 | if(scopes == null || scopes.length == 0 || scope == null || scope == UNKNOWN)
114 | return false;
115 | for(Scope s : scopes)
116 | if(s == scope)
117 | return true;
118 | return false;
119 | }
120 |
121 | /**
122 | * Joins the specified scopes properly as they should
123 | * be represented as part of an authorization URL.
124 | *
125 | * @param scopes
126 | * The scopes to join.
127 | *
128 | * @return A String representing how the scopes should be
129 | * represented as part of an authorization URL.
130 | */
131 | public static String join(Scope... scopes)
132 | {
133 | return join(false, scopes);
134 | }
135 |
136 | /**
137 | * Joins the specified scopes properly as they should
138 | * be represented as part of an authorization URL.
139 | *
140 | * @param scopes
141 | * The scopes to join.
142 | * @param bySpace
143 | * If the scopes should be joined by " " or "%20" (default: "%20")
144 | *
145 | * @return A String representing how the scopes should be
146 | * represented as part of an authorization URL.
147 | */
148 | public static String join(boolean bySpace, Scope... scopes)
149 | {
150 | if(scopes.length == 0)
151 | return "";
152 | StringBuilder sb = new StringBuilder(scopes[0].getText());
153 | for(int i = 1; i < scopes.length; i++)
154 | {
155 | if (bySpace)
156 | {
157 | sb.append(" ");
158 | }
159 | else
160 | {
161 | sb.append("%20");
162 | }
163 | sb.append(scopes[i].getText());
164 | }
165 | return sb.toString();
166 | }
167 |
168 | /**
169 | * Gets a scope based on the specified text key.
170 | *
171 | * @param scope
172 | * A text key to get a scope by.
173 | *
174 | * @return The scope matching the provided text key
175 | * ({@link Scope#UNKNOWN UNKNOWN} by default)
176 | */
177 | public static Scope from(String scope)
178 | {
179 | for(Scope s : values())
180 | if(s.text.equalsIgnoreCase(scope))
181 | return s;
182 | return UNKNOWN;
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/requests/OAuth2Action.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.requests;
17 |
18 | import com.jagrosh.jdautilities.oauth2.entities.impl.OAuth2ClientImpl;
19 | import net.dv8tion.jda.internal.requests.Method;
20 | import net.dv8tion.jda.internal.utils.Checks;
21 | import okhttp3.Headers;
22 | import okhttp3.Request;
23 | import okhttp3.RequestBody;
24 | import okhttp3.Response;
25 |
26 | import javax.annotation.WillClose;
27 | import java.io.IOException;
28 | import java.util.function.Consumer;
29 |
30 | /**
31 | * An adaptable lookalike of JDA's {@link net.dv8tion.jda.api.requests.RestAction RestAction}.
32 | *
33 | * OAuth2Actions can either be completed asynchronously using {@link OAuth2Action#queue() queue},
34 | * or synchronously using {@link OAuth2Action#complete() complete}.
35 | *
36 | * Note that OAuth2Action does not extend JDA's RestAction.
37 | *
38 | * @author Kaidan Gustave
39 | */
40 | public abstract class OAuth2Action Bear in mind when using this, that this method blocks the thread it is called in.
145 | * @return the value constructed from the response
146 | * @throws java.io.IOException on unsuccessful execution
147 | */
148 | public T complete() throws IOException
149 | {
150 | return client.getRequester().submitSync(this);
151 | }
152 |
153 | /**
154 | * Gets the {@link com.jagrosh.jdautilities.oauth2.OAuth2Client client} responsible
155 | * for creating this OAuth2Action.
156 | *
157 | * @return The OAuth2Client responsible for creating this.
158 | */
159 | public OAuth2ClientImpl getClient()
160 | {
161 | return client;
162 | }
163 |
164 | protected abstract T handle(@WillClose Response response) throws IOException;
165 | }
166 |
--------------------------------------------------------------------------------
/examples/src/main/java/com/jagrosh/jdautilities/examples/command/AboutCommand.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.examples.command;
17 |
18 | import com.jagrosh.jdautilities.commons.JDAUtilitiesInfo;
19 | import com.jagrosh.jdautilities.command.Command;
20 | import com.jagrosh.jdautilities.command.CommandEvent;
21 | import com.jagrosh.jdautilities.doc.standard.CommandInfo;
22 | import com.jagrosh.jdautilities.examples.doc.Author;
23 | import net.dv8tion.jda.api.entities.ApplicationInfo;
24 | import net.dv8tion.jda.api.entities.ChannelType;
25 | import net.dv8tion.jda.api.EmbedBuilder;
26 | import net.dv8tion.jda.api.JDAInfo;
27 | import net.dv8tion.jda.api.Permission;
28 | import org.slf4j.Logger;
29 | import org.slf4j.LoggerFactory;
30 |
31 | import java.awt.*;
32 |
33 | /**
34 | *
35 | * @author John Grosh (jagrosh)
36 | */
37 | @CommandInfo(
38 | name = "About",
39 | description = "Gets information about the bot."
40 | )
41 | @Author("John Grosh (jagrosh)")
42 | public class AboutCommand extends Command {
43 | private boolean IS_AUTHOR = true;
44 | private String REPLACEMENT_ICON = "+";
45 | private final Color color;
46 | private final String description;
47 | private final Permission[] perms;
48 | private String oauthLink;
49 | private final String[] features;
50 |
51 | public AboutCommand(Color color, String description, String[] features, Permission... perms)
52 | {
53 | this.color = color;
54 | this.description = description;
55 | this.features = features;
56 | this.name = "about";
57 | this.help = "shows info about the bot";
58 | this.guildOnly = false;
59 | this.perms = perms;
60 | this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
61 | }
62 |
63 | public void setIsAuthor(boolean value)
64 | {
65 | this.IS_AUTHOR = value;
66 | }
67 |
68 | public void setReplacementCharacter(String value)
69 | {
70 | this.REPLACEMENT_ICON = value;
71 | }
72 |
73 | @Override
74 | protected void execute(CommandEvent event) {
75 | if (oauthLink == null) {
76 | try {
77 | ApplicationInfo info = event.getJDA().retrieveApplicationInfo().complete();
78 | oauthLink = info.isBotPublic() ? info.getInviteUrl(0L, perms) : "";
79 | } catch (Exception e) {
80 | Logger log = LoggerFactory.getLogger("OAuth2");
81 | log.error("Could not generate invite link ", e);
82 | oauthLink = "";
83 | }
84 | }
85 | EmbedBuilder builder = new EmbedBuilder();
86 | builder.setColor(event.isFromType(ChannelType.TEXT) ? event.getGuild().getSelfMember().getColor() : color);
87 | builder.setAuthor("All about " + event.getSelfUser().getName() + "!", null, event.getSelfUser().getAvatarUrl());
88 | boolean join = !(event.getClient().getServerInvite() == null || event.getClient().getServerInvite().isEmpty());
89 | boolean inv = !oauthLink.isEmpty();
90 | String invline = "\n" + (join ? "Join my server [`here`](" + event.getClient().getServerInvite() + ")" : (inv ? "Please " : ""))
91 | + (inv ? (join ? ", or " : "") + "[`invite`](" + oauthLink + ") me to your server" : "") + "!";
92 | String author = event.getJDA().getUserById(event.getClient().getOwnerId())==null ? "<@" + event.getClient().getOwnerId()+">"
93 | : event.getJDA().getUserById(event.getClient().getOwnerId()).getName();
94 | StringBuilder descr = new StringBuilder().append("Hello! I am **").append(event.getSelfUser().getName()).append("**, ")
95 | .append(description).append("\nI ").append(IS_AUTHOR ? "was written in Java" : "am owned").append(" by **")
96 | .append(author).append("** using " + JDAUtilitiesInfo.AUTHOR + "'s [Commands Extension](" + JDAUtilitiesInfo.GITHUB + ") (")
97 | .append(JDAUtilitiesInfo.VERSION).append(") and the [JDA library](https://github.com/DV8FromTheWorld/JDA) (")
98 | .append(JDAInfo.VERSION).append(")\nType `").append(event.getClient().getTextualPrefix()).append(event.getClient().getHelpWord())
99 | .append("` to see my commands!").append(join || inv ? invline : "").append("\n\nSome of my features include: ```css");
100 | for (String feature : features)
101 | descr.append("\n").append(event.getClient().getSuccess().startsWith("<") ? REPLACEMENT_ICON : event.getClient().getSuccess()).append(" ").append(feature);
102 | descr.append(" ```");
103 | builder.setDescription(descr);
104 | if (event.getJDA().getShardInfo() == null)
105 | {
106 | builder.addField("Stats", event.getJDA().getGuilds().size() + " servers\n1 shard", true);
107 | builder.addField("Users", event.getJDA().getUsers().size() + " unique\n" + event.getJDA().getGuilds().stream().mapToInt(g -> g.getMembers().size()).sum() + " total", true);
108 | builder.addField("Channels", event.getJDA().getTextChannels().size() + " Text\n" + event.getJDA().getVoiceChannels().size() + " Voice", true);
109 | }
110 | else
111 | {
112 | builder.addField("Stats", (event.getClient()).getTotalGuilds() + " Servers\nShard " + (event.getJDA().getShardInfo().getShardId() + 1)
113 | + "/" + event.getJDA().getShardInfo().getShardTotal(), true);
114 | builder.addField("This shard", event.getJDA().getUsers().size() + " Users\n" + event.getJDA().getGuilds().size() + " Servers", true);
115 | builder.addField("", event.getJDA().getTextChannels().size() + " Text Channels\n" + event.getJDA().getVoiceChannels().size() + " Voice Channels", true);
116 | }
117 | builder.setFooter("Last restart", null);
118 | builder.setTimestamp(event.getClient().getStartTime());
119 | event.reply(builder.build());
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/entities/OAuth2User.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.entities;
17 |
18 | import com.jagrosh.jdautilities.oauth2.OAuth2Client;
19 | import com.jagrosh.jdautilities.oauth2.session.Session;
20 | import net.dv8tion.jda.api.sharding.ShardManager;
21 | import net.dv8tion.jda.api.JDA;
22 | import net.dv8tion.jda.api.entities.IMentionable;
23 | import net.dv8tion.jda.api.entities.ISnowflake;
24 | import net.dv8tion.jda.api.entities.User;
25 |
26 | /**
27 | * OAuth2 representation of a Discord User.
28 | * Note that if this user is acquired without the '{@link com.jagrosh.jdautilities.oauth2.Scope#EMAIL email}'
77 | * OAuth {@link com.jagrosh.jdautilities.oauth2.Scope Scope}, this will throw a
78 | * {@link com.jagrosh.jdautilities.oauth2.exceptions.MissingScopeException MissingScopeException}.
79 | *
80 | * @return The user's email.
81 | *
82 | * @throws com.jagrosh.jdautilities.oauth2.exceptions.MissingScopeException
83 | * If the corresponding {@link OAuth2User#getSession() session} does not have the
84 | * proper 'email' OAuth2 scope
85 | */
86 | String getEmail();
87 |
88 | /**
89 | * Returns {@code true} if the user's Discord account has been verified via email.
90 | *
91 | * This is required to send messages in guilds where certain moderation levels are used.
92 | *
93 | * @return {@code true} if the user has verified their account, {@code false} otherwise.
94 | */
95 | boolean isVerified();
96 |
97 | /**
98 | * Returns {@code true} if this user has multi-factor authentication enabled.
99 | *
100 | * Some guilds require mfa for administrative actions.
101 | *
102 | * @return {@code true} if the user has mfa enabled, {@code false} otherwise.
103 | */
104 | boolean isMfaEnabled();
105 |
106 | /**
107 | * Gets the user's discriminator.
108 | *
109 | * @return The user's discriminator.
110 | */
111 | String getDiscriminator();
112 |
113 | /**
114 | * Gets the user's avatar ID, or {@code null} if they have not set one.
115 | *
116 | * @return The user's avatar ID, or {@code null} if they have not set one.
117 | */
118 | String getAvatarId();
119 |
120 | /**
121 | * Gets the user's avatar URL, or {@code null} if they have not set one.
122 | *
123 | * @return The user's avatar URL, or {@code null} if they have not set one.
124 | */
125 | String getAvatarUrl();
126 |
127 | /**
128 | * Gets the user's avatar URL.
129 | *
130 | * @return The user's avatar URL.
131 | */
132 | String getDefaultAvatarId();
133 |
134 | /**
135 | * Gets the user's default avatar ID.
136 | *
137 | * @return The user's default avatar ID.
138 | */
139 | String getDefaultAvatarUrl();
140 |
141 | /**
142 | * Gets the user's avatar URL, or their {@link #getDefaultAvatarUrl() default avatar URL}
143 | * if they do not have a custom avatar set on their account.
144 | *
145 | * @return The user's effective avatar URL.
146 | */
147 | String getEffectiveAvatarUrl();
148 |
149 | /**
150 | * Gets whether or not this user is a bot.
151 | *
152 | * While, at the time of writing this documentation, bots cannot
153 | * authenticate applications, there may be a time in the future
154 | * where they have such an ability.
155 | *
156 | * @return {@code false}
157 | *
158 | * @deprecated
159 | * Due to the nature of OAuth2 at this moment, bots are not
160 | * allowed to use the various urls provided.
161 | * Note that there is no guarantee that this will not return {@code null}
184 | * as the instance of JDA may not have access to the User.
185 | *
186 | * For sharded bots, use {@link OAuth2User#getJDAUser(ShardManager)}.
187 | *
188 | * @param jda
189 | * The instance of JDA to get from.
190 | *
191 | * @return A JDA User, possibly {@code null}.
192 | */
193 | User getJDAUser(JDA jda);
194 |
195 | /**
196 | * Gets the corresponding {@link net.dv8tion.jda.api.entities.User JDA User}
197 | * from the provided {@link net.dv8tion.jda.api.sharding.ShardManager ShardManager}.
198 | *
199 | * Note that there is no guarantee that this will not return {@code null}
200 | * as the ShardManager may not have access to the User.
201 | *
202 | * For un-sharded bots, use {@link OAuth2User#getJDAUser(JDA)}.
203 | *
204 | * @param shardManager
205 | * The ShardManager to get from.
206 | *
207 | * @return A JDA User, possibly {@code null}.
208 | */
209 | User getJDAUser(ShardManager shardManager);
210 | }
211 |
--------------------------------------------------------------------------------
/command/src/main/java/com/jagrosh/jdautilities/command/impl/AnnotatedModuleCompilerImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.command.impl;
17 |
18 | import com.jagrosh.jdautilities.command.AnnotatedModuleCompiler;
19 | import com.jagrosh.jdautilities.command.Command;
20 | import com.jagrosh.jdautilities.command.CommandBuilder;
21 | import com.jagrosh.jdautilities.command.CommandEvent;
22 | import com.jagrosh.jdautilities.command.annotation.JDACommand;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | import java.lang.reflect.*;
27 | import java.util.ArrayList;
28 | import java.util.List;
29 | import java.util.function.Predicate;
30 |
31 | /**
32 | * Default implementation for {@link com.jagrosh.jdautilities.command.AnnotatedModuleCompiler
33 | * AnnotatedModuleCompiler}.
34 | *
35 | * @since 1.8
36 | * @author Kaidan Gustave
37 | */
38 | public class AnnotatedModuleCompilerImpl implements AnnotatedModuleCompiler
39 | {
40 | private static final Logger LOG = LoggerFactory.getLogger(AnnotatedModuleCompiler.class);
41 |
42 | @Override
43 | public List OAuth2Client's are made using a {@link com.jagrosh.jdautilities.oauth2.OAuth2Client.Builder OAuth2Client.Builder},
36 | * and sessions can be appended using {@link OAuth2Client#startSession(String, String, String, Scope...)}.
37 | *
38 | * @author John Grosh (john.a.grosh@gmail.com)
39 | * @author Kaidan Gustave
40 | */
41 | public interface OAuth2Client
42 | {
43 | /**
44 | * The REST version targeted by JDA-Utilities OAuth2.
45 | */
46 | int DISCORD_REST_VERSION = 8;
47 |
48 | /**
49 | * Generates a formatted authorization URL from the provided redirect URI fragment
50 | * and {@link com.jagrosh.jdautilities.oauth2.Scope Scopes}.
51 | *
52 | * @param redirectUri
53 | * The redirect URI.
54 | * @param scopes
55 | * The provided scopes.
56 | *
57 | * @return The generated authorization URL.
58 | */
59 | String generateAuthorizationURL(String redirectUri, Scope... scopes);
60 |
61 | /**
62 | * Starts a {@link com.jagrosh.jdautilities.oauth2.session.Session Session} with the provided code,
63 | * state, and identifier. The state provided should be unique and provided through an
64 | * implementation of {@link com.jagrosh.jdautilities.oauth2.state.StateController StateController}.
65 | *
66 | * If the state has already been consumed by the StateController using
67 | * {@link com.jagrosh.jdautilities.oauth2.state.StateController#consumeState(String) StateController#consumeState},
68 | * then it should return {@code null} when provided the same state, so that this may throw a
69 | * {@link InvalidStateException InvalidStateException} to signify it has
70 | * been consumed.
71 | *
72 | * @param code
73 | * The code for the Session to start.
74 | * @param state
75 | * The state for the Session to start.
76 | * @param identifier
77 | * The identifier for the Session to start.
78 | * @param scopes
79 | * The provided scopes.
80 | *
81 | * @return A {@link com.jagrosh.jdautilities.oauth2.requests.OAuth2Action OAuth2Action} for the Session to start.
82 | *
83 | * @throws InvalidStateException
84 | * If the state, when consumed by this client's StateController, results in a {@code null} redirect URI.
85 | */
86 | @CheckReturnValue
87 | OAuth2Action All Sessions should handle an individual Discord User, and as such this method retrieves
94 | * data on that User when the session is provided.
95 | *
96 | * @param session
97 | * The Session to get a OAuth2User for.
98 | *
99 | * @return A {@link com.jagrosh.jdautilities.oauth2.requests.OAuth2Action OAuth2Action} for
100 | * the OAuth2User to be retrieved.
101 | */
102 | @CheckReturnValue
103 | OAuth2Action All Sessions should handle an individual Discord User, and as such this method retrieves
110 | * data on all the various Discord Guilds that user is a part of when the session is provided.
111 | *
112 | * Note that this can only be performed for Sessions who have the necessary
113 | * {@link com.jagrosh.jdautilities.oauth2.Scope#GUILDS 'guilds'} scope.
114 | * At minimum, the developer must provide a
162 | * valid Client ID, as well as a valid secret.
163 | */
164 | class Builder
165 | {
166 | private long clientId = -1;
167 | private String clientSecret;
168 | private SessionController sessionController;
169 | private StateController stateController;
170 | private OkHttpClient client;
171 |
172 | /**
173 | * Finalizes and builds an {@link com.jagrosh.jdautilities.oauth2.OAuth2Client OAuth2Client}
174 | * instance using this builder.
175 | *
176 | * @return The OAuth2Client instance build.
177 | *
178 | * @throws java.lang.IllegalArgumentException
179 | * If either:
180 | * The primary issue that command systems face when trying to implement "annotated command"
31 | * systems is that reflection is a powerful but also costly tool and requires much more overhead
32 | * than most other types systems.
33 | *
34 | * To circumvent this, classes annotated with this are put through an {@link
35 | * com.jagrosh.jdautilities.command.AnnotatedModuleCompiler AnnotatedModuleCompiler}.
36 | * where they will be converted to Commands using {@link com.jagrosh.jdautilities.command.CommandBuilder
37 | * CommandBuilder}.
38 | *
39 | * Classes that wish to be contain methods to be used as commands must be annotated with
40 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand.Module @Module}.
41 | * The first index is the name, and following indices are aliases.
71 | *
72 | * @return An array of strings, the first one being the name
73 | * of the command, and following ones being aliases.
74 | */
75 | String[] name() default {"null"};
76 |
77 | /**
78 | * The help string for a command.
79 | *
80 | * @return The help string for a command.
81 | */
82 | String help() default "no help available";
83 |
84 | /**
85 | * Whether or not the command is only usable in a guild.
86 | * This holds both metadata for both the
119 | * {@link com.jagrosh.jdautilities.command.Command#cooldown Command#cooldown}
120 | * and {@link com.jagrosh.jdautilities.command.Command#cooldownScope
121 | * Command#cooldownScope}.
122 | *
123 | * @return The {@code @Cooldown} for the command.
124 | */
125 | Cooldown cooldown() default @Cooldown(0);
126 |
127 | /**
128 | * The {@link net.dv8tion.jda.api.Permission Permissions} the bot must have
129 | * on a guild to use this command.
130 | *
131 | * @return The required permissions the bot must have to use this command.
132 | */
133 | Permission[] botPermissions() default {};
134 |
135 | /**
136 | * The {@link net.dv8tion.jda.api.Permission Permissions} the user must have
137 | * on a guild to use this command.
138 | *
139 | * @return The required permissions a user must have to use this command.
140 | */
141 | Permission[] userPermissions() default {};
142 |
143 | /**
144 | * Whether or not this command uses topic tags.
145 | * For more information on topic tags, see
148 | * {@link com.jagrosh.jdautilities.command.Command#usesTopicTags
149 | * Command#usesTopicTags}
150 | *
151 | * @return {@code true} if this command uses topic tags, {@code false} otherwise.
152 | */
153 | boolean useTopicTags() default true;
154 |
155 | /**
156 | * The names of any methods representing child commands for this command.
157 | *
158 | * @return The names of any methods representing child commands.
159 | */
160 | String[] children() default {};
161 |
162 | /**
163 | * Whether or not this command should remain hidden in the help builder.
164 | *
165 | * @return {@code true} if this command should remain hidden, {@code false} otherwise.
166 | */
167 | boolean isHidden() default false;
168 |
169 | /**
170 | * The {@link JDACommand.Category JDACommand.Category} for this command.
171 | * Method names provided to this annotation must have one or two parameters.
184 | * Either a single parameter {@link com.jagrosh.jdautilities.command.CommandEvent
185 | * CommandEvent}, or a double parameter {@code CommandEvent} and {@code Command}.
186 | * This is not the same thing as the name of the commands! These are
201 | * the names of the methods representing execution of the commands!
202 | *
203 | * @return An array of method names used when creating commands.
204 | */
205 | String[] value();
206 | }
207 |
208 | /**
209 | * A value wrapper for what would be {@link com.jagrosh.jdautilities.command.Command#cooldown
210 | * Command#cooldown} and {@link com.jagrosh.jdautilities.command.Command#cooldownScope
211 | * Command#cooldownScope}.
212 | *
213 | * The default {@link com.jagrosh.jdautilities.command.Command.CooldownScope CooldownScope}
214 | * is {@link com.jagrosh.jdautilities.command.Command.CooldownScope#USER CooldownScope.USER}.
215 | *
216 | * @see JDACommand#cooldown()
217 | */
218 | @Target(ElementType.TYPE)
219 | @Retention(RetentionPolicy.RUNTIME)
220 | @interface Cooldown
221 | {
222 | /**
223 | * The number of seconds the annotated Command will be on cooldown.
224 | *
225 | * @return The number of seconds the annotated Command will be on cooldown.
226 | */
227 | int value();
228 |
229 | /**
230 | * The {@link com.jagrosh.jdautilities.command.Command.CooldownScope CooldownScope}
231 | * for the annotated Command.
232 | *
233 | * By default this is {@link com.jagrosh.jdautilities.command.Command.CooldownScope#USER
234 | * CooldownScope.USER}.
235 | *
236 | * @return The CooldownScope for this annotated Command.
237 | */
238 | Command.CooldownScope scope() default Command.CooldownScope.USER;
239 | }
240 |
241 | /**
242 | * A helper annotation to assist in location of Category instance.
243 | *
244 | * This will target a static field in the specified class
245 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand.Category#location() location} using reflections, with a
246 | * matching {@link com.jagrosh.jdautilities.command.annotation.JDACommand.Category#name() name}.
247 | *
248 | * It is important to remember the target must be a static field
249 | * and any other attempted inputs will result in errors from the
250 | * {@link com.jagrosh.jdautilities.command.AnnotatedModuleCompiler compiler}.
251 | *
252 | * @see com.jagrosh.jdautilities.command.annotation.JDACommand#category()
253 | */
254 | @Target(ElementType.TYPE)
255 | @Retention(RetentionPolicy.RUNTIME)
256 | @interface Category
257 | {
258 | /**
259 | * The name of the static field in the {@link com.jagrosh.jdautilities.command.annotation.JDACommand.Category#location()
260 | * target class} that will be the category for the annotated command.
261 | *
262 | * @return The name of the static field in the target class.
263 | */
264 | String name();
265 |
266 | /**
267 | * The target class where the static field is located.
268 | *
269 | * @return The target class where the static field is located.
270 | */
271 | Class> location();
272 | }
273 |
274 | }
275 |
--------------------------------------------------------------------------------
13 | Issues that do not complete the checklist may be closed without any help.
14 |
15 | - [ ] I have checked for similar issues on the [issue tracker][issues].
16 | - [ ] I have updated to the [latest version][download] of JDA-Utilities.
17 | - [ ] I have checked the branches or the maintainers' PRs for upcoming features/bug fixes.
18 |
19 | > The issue tracker is reserved for issues, errors, and feature requests related
20 | > to JDA-Utilities, and not questions and other requests for help.
21 | >
22 | > - For examples, check out the [examples module][examples-module] or the list
23 | > of [JDA-Utilities projects][jda-u-projects].
24 | > - For questions join the [official JDA discord server][guild] and ask them
25 | > in our `#jda-utilities` channel.
26 | > - For general programming questions, visit [StackOverflow][stack overflow].
27 |
28 | #### Issue Information
29 | Check all that apply:
30 |
31 | - [ ] This is a bug report about an error, issue, or bug in JDA-Utilities.
32 | - [ ] I have been able to consistently reproduce this bug.
33 | - [ ] This is a feature request for the JDA-Utilities library.
34 |
35 | > This issue tracker **does not** assist or handle issues with the JDA library.
36 | > For JDA related issues, visit the [JDA issue tracker][jda-issues]
37 | > and open an issue there.
38 |
39 | #### Description
40 |
41 | Describe your issue here.
42 | Please provide any stack-traces, code, or pictures that will help describe the issue you are encountering.
43 |
--------------------------------------------------------------------------------
/menu/src/main/java/com/jagrosh/jdautilities/menu/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * Menus package.
19 | * Contains the {@link com.jagrosh.jdautilities.menu.Menu Menu} class and all
20 | * standard implementations of it:
21 | *
22 | *
37 | *
38 | * All menus also come with an implementation of a {@link com.jagrosh.jdautilities.menu.Menu.Builder Menu.Builder}
39 | * as a static inner class of the corresponding Menu implementation, which are the main entryway to create said
40 | * implementations for usage.
41 | *
42 | *
A menu where users select a choice via "reaction-buttons".
A menu with 1 - 10 ordered items, each with their own reaction to choose them with.
A menu that paginates a number of items across a number of pages and uses reactions to traverse between them.
A menu that orders choices and uses a indicator and reactions to choose one of the choices.
A menu similar to the Paginator that displays a picture on each page.
Visit the JDA-Utilities GitHub Repository
21 | * to submit issue reports or feature requests, or join the
22 | * Official JDA Discord Guild if you need any assistance with the library!
23 | *
24 | * @author John Grosh (john.a.grosh@gmail.com)
25 | */
26 | public final class JDAUtilitiesInfo
27 | {
28 | public static final String VERSION_MAJOR = "@VERSION_MAJOR@";
29 | public static final String VERSION_MINOR = "@VERSION_MINOR@";
30 | public static final String VERSION_REVISION = "@VERSION_REVISION@";
31 | public static final String VERSION = VERSION_MAJOR.startsWith("@")? "DEV" : VERSION_MAJOR + "." + VERSION_MINOR + "." + VERSION_REVISION;
32 | public static final String GITHUB = "https://github.com/JDA-Applications/JDA-Utilities";
33 | public static final String AUTHOR = "JDA-Applications";
34 |
35 | // Removed in favor of a token replacement.
36 | /*
37 | // Version init block
38 | static
39 | {
40 | Package pkg = JDAUtilitiesInfo.class.getPackage();
41 |
42 | String version = pkg.getImplementationVersion();
43 | VERSION = version == null? "DEV" : version;
44 |
45 | String[] parts = VERSION.split("\\.", 2);
46 | VERSION_MAJOR = version == null? "2" : parts[0]; // This should only be updated every version major!
47 | VERSION_MINOR = version == null? "X" : parts[1];
48 | }
49 | */
50 | }
51 |
--------------------------------------------------------------------------------
/doc/src/main/java/com/jagrosh/jdautilities/doc/DocMultiple.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.doc;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * A helper {@link java.lang.annotation.Annotation Annotation}, useful for
22 | * formatting multiple occurrences of the same CommandDoc annotation.
23 | *
24 | *
{@link com.jagrosh.jdautilities.doc.standard.Error @Error} and {@link
27 | * com.jagrosh.jdautilities.doc.standard.Errors @Errors} are an example of such practice.
28 | *
29 | * @see com.jagrosh.jdautilities.doc.standard.Error
30 | * @see com.jagrosh.jdautilities.doc.standard.Errors
31 | *
32 | * @since 2.0
33 | * @author Kaidan Gustave
34 | */
35 | @Documented
36 | @Retention(RetentionPolicy.RUNTIME)
37 | @Target(ElementType.ANNOTATION_TYPE)
38 | public @interface DocMultiple
39 | {
40 | /**
41 | * Text that occurs before all occurrences of the annotation
42 | * this is applied to.
43 | *
Default this is an empty String.
44 | *
45 | * @return The preface text
46 | */
47 | String preface() default "";
48 |
49 | /**
50 | * A prefix annotation appended to the front of each occurrence.
51 | *
Default this is an empty string.
52 | *
53 | * @return The prefix String.
54 | */
55 | String prefixEach() default "";
56 |
57 | /**
58 | * A separator String applied in-between occurrences.
59 | *
Default this is an empty string.
60 | *
61 | * @return The separator String.
62 | */
63 | String separateBy() default "";
64 | }
65 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS="-Xmx64m"
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/command/src/main/java/com/jagrosh/jdautilities/command/AnnotatedModuleCompiler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.command;
17 |
18 | import com.jagrosh.jdautilities.command.annotation.JDACommand;
19 | import java.util.List;
20 |
21 | /**
22 | * A "compiler" for {@link java.lang.Object Object}s that uses {@link java.lang.annotation.Annotation Annotation}s
23 | * as helpers for creating {@link com.jagrosh.jdautilities.command.Command Command}s.
24 | *
25 | *
The primary duty of this class is to provide a "in runtime" converter for generics that are annotated with
33 | * the {@link JDACommand.Module JDACommand.Module}
34 | *
35 | * @since 1.7
36 | * @author Kaidan Gustave
37 | */
38 | public interface AnnotatedModuleCompiler
39 | {
40 | /**
41 | * Compiles one or more {@link com.jagrosh.jdautilities.command.Command Command}s
42 | * using method annotations as for properties from the specified {@link java.lang.Object
43 | * Object}.
44 | *
45 | *
If in the future it is decided to add a method
44 | * to this interface, the method will have a default
45 | * implementation that doesn't require developer additions.
46 | */
47 | public interface GuildSettingsManager
28 | *
30 | *
31 | * Note that all of these functions are OPTIONAL to implement, and instructions
32 | * are available in method documentation on how to implement properly.
33 | *
Additionally, as stated before, the interface itself does not need to be
34 | * implemented for an object to be returned handled by a GuildSettingsManager.
35 | *
36 | * @since 2.0
37 | * @author Kaidan Gustave
38 | *
39 | * @implNote
40 | * Unless in the event of a major breaking change to
41 | * JDA, there is no chance of implementations of this
42 | * interface being required to implement additional
43 | * methods.
44 | *
If in the future it is decided to add a method
45 | * to this interface, the method will have a default
46 | * implementation that doesn't require developer additions.
47 | */
48 | public interface GuildSettingsProvider
49 | {
50 | /**
51 | * Gets a {@link java.util.Collection Collection} of String prefixes available
52 | * for the Guild represented by this implementation.
53 | *
54 | *
26 | * The type of the Session for this to handle.
27 | *
28 | * @author John Grosh (john.a.grosh@gmail.com)
29 | * @author Kaidan Gustave
30 | */
31 | public interface SessionController
32 | {
33 | /**
34 | * Gets a {@link com.jagrosh.jdautilities.oauth2.session.Session Session} that
35 | * was previously created using the provided identifier.
36 | *
37 | *
30 | * {@literal @ConvertedBy(MyCommandDocAnn.Converter.class)}
31 | * {@literal @Retention(RetentionPolicy.RUNTIME)}
32 | * {@literal @Target(ElementType.ANNOTATION_TYPE)}
33 | * public @interface MyCommandDocAnn
34 | * {
35 | * String value();
36 | *
37 | * class Converter implements DocConverter{@literal
46 | *
47 | * It is also notably recommended you follow the standards for DocConverters listed below:
48 | *
49 | *
57 | *
58 | * @see ConvertedBy
59 | *
60 | * @since 2.0
61 | * @author Kaidan Gustave
62 | */
63 | @FunctionalInterface
64 | public interface DocConverter
Should never throw and/or encounter uncaught exceptions.
70 | *
71 | * @param annotation
72 | * The annotation to process.
73 | *
74 | * @return A String processed from the Annotation provided.
75 | */
76 | String read(T annotation);
77 | }
78 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/requests/OAuth2URL.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.requests;
17 |
18 | import com.jagrosh.jdautilities.oauth2.OAuth2Client;
19 |
20 | /**
21 | * Simple formattable constants for various URLs used in the JDA-Utilities OAuth2.
22 | *
23 | * @author Kaidan Gustave
24 | */
25 | public enum OAuth2URL
26 | {
27 | AUTHORIZE("/oauth2/authorize",
28 | "client_id=%d",
29 | "redirect_uri=%s",
30 | "response_type=code",
31 | "scope=%s",
32 | "state=%s"),
33 | TOKEN("/oauth2/token",
34 | "client_id=%d",
35 | "redirect_uri=%s",
36 | "grant_type=authorization_code",
37 | "code=%s",
38 | "client_secret=%s",
39 | "scope=%s"),
40 | CURRENT_USER("/users/@me"),
41 | CURRENT_USER_GUILDS("/users/@me/guilds");
42 |
43 | public static final String BASE_API_URL = String.format("https://discord.com/api/v%d", OAuth2Client.DISCORD_REST_VERSION);
44 |
45 | private final String route;
46 | private final String formattableRoute;
47 | private final boolean hasQueryParams;
48 | private final String queryParams;
49 |
50 | OAuth2URL(String route, String... queryParams)
51 | {
52 | this.route = route;
53 | this.hasQueryParams = queryParams.length > 0;
54 |
55 | if(hasQueryParams)
56 | {
57 | StringBuilder b = new StringBuilder();
58 |
59 | for(int i = 0; i < queryParams.length; i++)
60 | {
61 | b.append(i == 0? '?' : '&');
62 | b.append(queryParams[i]);
63 | }
64 |
65 | this.formattableRoute = route + b.toString();
66 | this.queryParams = b.toString();
67 | }
68 | else
69 | {
70 | this.formattableRoute = route;
71 | this.queryParams = "";
72 | }
73 | }
74 |
75 | public String getRoute()
76 | {
77 | return route;
78 | }
79 |
80 | public boolean hasQueryParams()
81 | {
82 | return hasQueryParams;
83 | }
84 |
85 | public String compileQueryParams(Object... values) {
86 | return String.format(queryParams, values).replaceFirst("\\?", "");
87 | }
88 |
89 | public String getRouteWithBaseUrl()
90 | {
91 | return BASE_API_URL + route;
92 | }
93 |
94 | public String compile(Object... values)
95 | {
96 | return BASE_API_URL + (hasQueryParams? String.format(formattableRoute, values) : formattableRoute);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/command/src/main/java/com/jagrosh/jdautilities/command/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * Items in this package pertain to the {@link com.jagrosh.jdautilities.command.CommandClient CommandClient} and
19 | * {@link com.jagrosh.jdautilities.command.Command Commands}.
20 | *
21 | *
24 | *
56 | */
57 | package com.jagrosh.jdautilities.command;
58 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/entities/impl/OAuth2GuildImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.entities.impl;
17 |
18 | import com.jagrosh.jdautilities.oauth2.OAuth2Client;
19 | import com.jagrosh.jdautilities.oauth2.entities.OAuth2Guild;
20 | import net.dv8tion.jda.api.Permission;
21 |
22 | import java.util.EnumSet;
23 |
24 | /**
25 | *
26 | * @author John Grosh (john.a.grosh@gmail.com)
27 | */
28 | public class OAuth2GuildImpl implements OAuth2Guild
29 | {
30 | private final OAuth2Client client;
31 | private final long id;
32 | private final String name, icon;
33 | private final boolean owner;
34 | private final int permissions;
35 |
36 | public OAuth2GuildImpl(OAuth2Client client, long id, String name, String icon, boolean owner, int permissions)
37 | {
38 | this.client = client;
39 | this.id = id;
40 | this.name = name;
41 | this.icon = icon;
42 | this.owner = owner;
43 | this.permissions = permissions;
44 | }
45 |
46 | @Override
47 | public OAuth2Client getClient()
48 | {
49 | return client;
50 | }
51 |
52 | @Override
53 | public long getIdLong()
54 | {
55 | return id;
56 | }
57 |
58 | @Override
59 | public String getName()
60 | {
61 | return name;
62 | }
63 |
64 | @Override
65 | public String getIconId()
66 | {
67 | return icon;
68 | }
69 |
70 | @Override
71 | public String getIconUrl()
72 | {
73 | return icon == null ? null : "https://cdn.discordapp.com/icons/" + id + "/" + icon + ".png";
74 | }
75 |
76 | @Override
77 | public int getPermissionsRaw()
78 | {
79 | return permissions;
80 | }
81 |
82 | @Override
83 | public EnumSet
An interface to create Commands from annotated objects (More info on annotated commands can be found in the
26 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand JDACommand} documentation).
An chain builder for Commands.
An abstract class that can be inherited by classes to create Commands compatible with the
33 | * {@code CommandClientImpl}.
An interface used for getting info set when building a {@code CommandClientImpl}.
A builder system used to create a {@code CommandClientImpl} across several optional chained methods.
A wrapper for a {@link net.dv8tion.jda.api.events.message.MessageReceivedEvent MessageReceivedEvent},
43 | * {@code CommandClient}, and String arguments. The main basis for carrying information to be used in Commands.
An interface to be provided to a {@code CommandClientImpl} that can provide Command operations depending
47 | * on the outcome of the call.
An abstract object used to store and handle {@code GuildSettingsProvider} implementations.
An implementable interface used to supply default methods for handling guild specific settings
54 | * via a {@code GuildSettingsManager}.
25 | *
31 | *
32 | * @since 1.2
33 | * @author Kaidan Gustave
34 | */
35 | public final class SafeIdUtil
36 | {
37 | /**
38 | * Safely convert the provided String ID to a {@code long} usable with
39 | * {@link net.dv8tion.jda.api.utils.MiscUtil#parseSnowflake(String) MiscUtil.parseSnowflake(String)}.
40 | *
41 | * @param id
42 | * The String ID to be converted
43 | *
44 | * @return If the String can be converted into a non-negative {@code long}, then it will return the conversion.
45 | *
However, if one of the following criteria is met, then this method will return {@code 0L}:
46 | *
47 | *
52 | */
53 | public static long safeConvert(String id)
54 | {
55 | try {
56 | long l = Long.parseLong(id.trim());
57 | if(l<0)
58 | return 0L;
59 | return l;
60 | } catch (NumberFormatException e) {
61 | return 0L;
62 | }
63 | }
64 |
65 | /**
66 | * Checks if the provided String ID is usable with {@link net.dv8tion.jda.api.utils.MiscUtil#parseSnowflake(String) MiscUtil.parseSnowflake(String)}.
67 | *
68 | * @param id
69 | * The String ID to be converted
70 | *
71 | * @return {@code true} if both of the following criteria are not met:
72 | *
73 | *
78 | */
79 | public static boolean checkId(String id)
80 | {
81 | try {
82 | long l = Long.parseLong(id.trim());
83 | return l >= 0;
84 | } catch (NumberFormatException e) {
85 | return false;
86 | }
87 | }
88 |
89 | // Prevent instantiation
90 | private SafeIdUtil(){}
91 | }
92 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/session/SessionData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.session;
17 |
18 | import com.jagrosh.jdautilities.oauth2.Scope;
19 |
20 | import java.time.OffsetDateTime;
21 | import java.time.format.DateTimeFormatter;
22 |
23 | /**
24 | * Contains various data necessary for creating a {@link com.jagrosh.jdautilities.oauth2.session.Session Session}
25 | * using a {@link com.jagrosh.jdautilities.oauth2.session.SessionController SessionController}.
26 | *
27 | * @author Kaidan Gustave
28 | */
29 | public class SessionData
30 | {
31 | private final String identifier, accessToken, refreshToken, tokenType;
32 | private final OffsetDateTime expiration;
33 | private final Scope[] scopes;
34 |
35 | public SessionData(String identifier, String accessToken, String refreshToken, String tokenType, OffsetDateTime expiration, Scope[] scopes)
36 | {
37 | this.identifier = identifier;
38 | this.accessToken = accessToken;
39 | this.refreshToken = refreshToken;
40 | this.tokenType = tokenType;
41 | this.expiration = expiration;
42 | this.scopes = scopes;
43 | }
44 |
45 | /**
46 | * Gets the session identifier.
47 | *
48 | * @return The session identifier.
49 | */
50 | public String getIdentifier()
51 | {
52 | return identifier;
53 | }
54 |
55 | /**
56 | * Gets the session access token.
57 | *
58 | * @return The session access token.
59 | */
60 | public String getAccessToken()
61 | {
62 | return accessToken;
63 | }
64 |
65 | /**
66 | * Gets the session refresh token.
67 | *
68 | * @return The session refresh token.
69 | */
70 | public String getRefreshToken()
71 | {
72 | return refreshToken;
73 | }
74 |
75 | /**
76 | * Gets the session token type.
77 | *
78 | * @return The session token type.
79 | */
80 | public String getTokenType()
81 | {
82 | return tokenType;
83 | }
84 |
85 | /**
86 | * Gets the session expiration time.
87 | *
88 | * @return The session expiration time.
89 | */
90 | public OffsetDateTime getExpiration()
91 | {
92 | return expiration;
93 | }
94 |
95 | /**
96 | * Gets the session {@link com.jagrosh.jdautilities.oauth2.Scope Scopes}.
97 | *
98 | * @return The session Scopes.
99 | */
100 | public Scope[] getScopes()
101 | {
102 | return scopes;
103 | }
104 |
105 | @Override
106 | public boolean equals(Object obj)
107 | {
108 | if(!(obj instanceof SessionData))
109 | return false;
110 |
111 | SessionData data = ((SessionData) obj);
112 |
113 | return getIdentifier().equals(data.getIdentifier()) && getTokenType().equals(data.getTokenType());
114 | }
115 |
116 | @Override
117 | public String toString()
118 | {
119 | return String.format("SessionData(identifier: %s, access-token: %s, refresh-token: %s, type: %s, expires: %s)",
120 | getIdentifier(), getAccessToken(), getRefreshToken(), getTokenType(),
121 | getExpiration().format(DateTimeFormatter.RFC_1123_DATE_TIME));
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/requests/OAuth2Requester.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.requests;
17 |
18 | import com.jagrosh.jdautilities.commons.JDAUtilitiesInfo;
19 | import net.dv8tion.jda.internal.utils.JDALogger;
20 | import okhttp3.*;
21 | import org.slf4j.Logger;
22 |
23 | import java.io.IOException;
24 | import java.util.function.Consumer;
25 |
26 | /**
27 | * @author Kaidan Gustave
28 | */
29 | public class OAuth2Requester
30 | {
31 | protected static final Logger LOGGER = JDALogger.getLog(OAuth2Requester.class);
32 | protected static final String USER_AGENT = "JDA-Utils Oauth2("+JDAUtilitiesInfo.GITHUB+" | "+JDAUtilitiesInfo.VERSION+")";
33 | protected static final RequestBody EMPTY_BODY = RequestBody.create(null, new byte[0]);
34 |
35 | private final OkHttpClient httpClient;
36 |
37 | public OAuth2Requester(OkHttpClient httpClient)
38 | {
39 | this.httpClient = httpClient;
40 | }
41 |
42 |
37 | * Possible Errors:
38 | * • "I encountered an issue while processing this command!" - Houston had a problem!
39 | * • "You used this command too fast" - b1nzy's fault!
40 | * • "An unexpected error occurred!" - Let's just blame Onitor!
41 | *
42 | *
43 | * @see com.jagrosh.jdautilities.doc.standard.Errors
44 | *
45 | * @since 2.0
46 | * @author Kaidan Gustave
47 | */
48 | @ConvertedBy(Error.Converter.class)
49 | @DocMultiple(
50 | preface = "**Possible Errors:**\n\n",
51 | prefixEach = "+ ",
52 | separateBy = "\n\n")
53 | @Documented
54 | @Repeatable(Errors.class)
55 | @Retention(RetentionPolicy.RUNTIME)
56 | @Target({ElementType.TYPE, ElementType.METHOD})
57 | public @interface Error
58 | {
59 | /**
60 | * A brief description of what caused the error.
61 | *
62 | * @return A description of what caused the error.
63 | */
64 | String value();
65 |
66 | /**
67 | * A response message that would normally be sent if this
68 | * error occurs, as a means of users identifying the error
69 | * without an idea of what exactly went wrong.
70 | *
71 | * @return A response message.
72 | */
73 | String response() default "";
74 |
75 | /**
76 | * A prefix appended to the front of the produced String during
77 | * conversion.
78 | *
Only really useful or needed when a Command has multiple
79 | * {@link com.jagrosh.jdautilities.doc.standard.Error @Error}
80 | * annotations, for the purpose of listing.
81 | *
82 | * @return A prefix for the conversion, useful when multiple @Errors
83 | * are specified.
84 | */
85 | String prefix() default "";
86 |
87 | /**
88 | * The {@link com.jagrosh.jdautilities.doc.DocConverter DocConverter}
89 | * for the {@link com.jagrosh.jdautilities.doc.standard.Error @Error}
90 | * annotation.
91 | */
92 | class Converter implements DocConverter
105 | [**JMusicBot**](https://github.com/jagrosh/MusicBot) - This music bot uses the Command Client for its base, and several menus, including the OrderedMenu for search results and the Paginator for the current queue
106 | [**GiveawayBot**](https://github.com/jagrosh/GiveawayBot) - GiveawayBot is a basic bot for hosting quick giveaways!
107 |
--------------------------------------------------------------------------------
/examples/src/main/java/com/jagrosh/jdautilities/examples/command/GuildlistCommand.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.examples.command;
17 |
18 | import java.awt.Color;
19 | import java.util.concurrent.TimeUnit;
20 | import com.jagrosh.jdautilities.command.Command;
21 | import com.jagrosh.jdautilities.command.CommandEvent;
22 | import com.jagrosh.jdautilities.doc.standard.CommandInfo;
23 | import com.jagrosh.jdautilities.doc.standard.Error;
24 | import com.jagrosh.jdautilities.doc.standard.RequiredPermissions;
25 | import com.jagrosh.jdautilities.examples.doc.Author;
26 | import com.jagrosh.jdautilities.menu.Paginator;
27 | import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
28 | import net.dv8tion.jda.api.Permission;
29 | import net.dv8tion.jda.api.entities.ChannelType;
30 | import net.dv8tion.jda.api.exceptions.PermissionException;
31 |
32 | /**
33 | *
34 | * @author John Grosh (jagrosh)
35 | */
36 | @CommandInfo(
37 | name = "Guildlist",
38 | description = "Gets a paginated list of the guilds the bot is on.",
39 | requirements = {
40 | "The bot has all necessary permissions.",
41 | "The user is the bot's owner."
42 | }
43 | )
44 | @Error(
45 | value = "If arguments are provided, but they are not an integer.",
46 | response = "[PageNumber] is not a valid integer!"
47 | )
48 | @RequiredPermissions({Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_ADD_REACTION})
49 | @Author("John Grosh (jagrosh)")
50 | public class GuildlistCommand extends Command {
51 |
52 | private final Paginator.Builder pbuilder;
53 | public GuildlistCommand(EventWaiter waiter)
54 | {
55 | this.name = "guildlist";
56 | this.help = "shows the list of guilds the bot is on";
57 | this.arguments = "[pagenum]";
58 | this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_ADD_REACTION};
59 | this.guildOnly = false;
60 | this.ownerCommand = true;
61 | pbuilder = new Paginator.Builder().setColumns(1)
62 | .setItemsPerPage(10)
63 | .showPageNumbers(true)
64 | .waitOnSinglePage(false)
65 | .useNumberedItems(false)
66 | .setFinalAction(m -> {
67 | try {
68 | m.clearReactions().queue();
69 | } catch(PermissionException ex) {
70 | m.delete().queue();
71 | }
72 | })
73 | .setEventWaiter(waiter)
74 | .setTimeout(1, TimeUnit.MINUTES);
75 | }
76 |
77 | @Override
78 | protected void execute(CommandEvent event) {
79 | int page = 1;
80 | if(!event.getArgs().isEmpty())
81 | {
82 | try
83 | {
84 | page = Integer.parseInt(event.getArgs());
85 | }
86 | catch(NumberFormatException e)
87 | {
88 | event.reply(event.getClient().getError()+" `"+event.getArgs()+"` is not a valid integer!");
89 | return;
90 | }
91 | }
92 | pbuilder.clearItems();
93 | event.getJDA().getGuilds().stream()
94 | .map(g -> "**"+g.getName()+"** (ID:"+g.getId()+") ~ "+g.getMembers().size()+" Members")
95 | .forEach(pbuilder::addItems);
96 | Paginator p = pbuilder.setColor(event.isFromType(ChannelType.TEXT) ? event.getSelfMember().getColor() : Color.black)
97 | .setText(event.getClient().getSuccess()+" Guilds that **"+event.getSelfUser().getName()+"** is connected to"
98 | +(event.getJDA().getShardInfo()==null ? ":" : "(Shard ID "+event.getJDA().getShardInfo().getShardId()+"):"))
99 | .setUsers(event.getAuthor())
100 | .build();
101 | p.paginate(event.getChannel(), page);
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/doc/src/main/java/com/jagrosh/jdautilities/doc/standard/CommandInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.doc.standard;
17 |
18 | import com.jagrosh.jdautilities.doc.ConvertedBy;
19 | import com.jagrosh.jdautilities.doc.DocConverter;
20 |
21 | import java.lang.annotation.*;
22 |
23 | /**
24 | * A CommandDoc {@link java.lang.annotation.Annotation Annotation}
25 | * that contains basic information on command usage, declaration,
26 | * and requirements.
27 | *
28 | *
It is recommended anyone using this consult the documentation for HashMap.
67 | *
68 | * @param key
69 | * The key to pair with the value
70 | * @param value
71 | * The value to pair with the key
72 | *
73 | * @see java.util.HashMap#put(Object, Object) HashMap#put(Object, Object)
74 | */
75 | public void add(K key, V value)
76 | {
77 | if(keys[currIndex] != null)
78 | {
79 | map.remove(keys[currIndex]);
80 | }
81 | map.put(key, value);
82 | keys[currIndex] = key;
83 | currIndex = (currIndex + 1) % keys.length;
84 | }
85 |
86 | /**
87 | * Checks if this {@link com.jagrosh.jdautilities.commons.utils.FixedSizeCache FixedSizeCache}
88 | * contains a key.
89 | *
90 | *
It is recommended anyone using this consult the documentation for HashMap.
93 | *
94 | * @param key
95 | * The key to check for
96 | *
97 | * @return {@code true} if the FixedSizeCache contains a key, else {@code false}
98 | *
99 | * @see java.util.HashMap#containsKey(Object) HashMap#containsKey(Object)
100 | */
101 | public boolean contains(K key)
102 | {
103 | return map.containsKey(key);
104 | }
105 |
106 | /**
107 | * Retrieves a value from this {@link FixedSizeCache
108 | * FixedSizeCache} corresponding to the specified key, or {@code null} if there is no
109 | * corresponding value to be retrieved.
110 | *
111 | *
It is recommended anyone using this consult the documentation for HashMap.
114 | *
115 | * @param key
116 | * The key to retrieve a value for
117 | *
118 | * @return A value corresponding to the provided key, or {@code null} if there was no
119 | * value to get.
120 | *
121 | * @see java.util.HashMap#get(Object) HashMap#get(Object)
122 | */
123 | public V get(K key)
124 | {
125 | return map.get(key);
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/examples/src/main/java/com/jagrosh/jdautilities/examples/command/RoleinfoCommand.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.examples.command;
17 |
18 | import com.jagrosh.jdautilities.command.Command;
19 | import com.jagrosh.jdautilities.command.CommandEvent;
20 | import com.jagrosh.jdautilities.commons.utils.FinderUtil;
21 | import java.awt.Color;
22 | import java.time.format.DateTimeFormatter;
23 | import java.util.List;
24 | import net.dv8tion.jda.api.EmbedBuilder;
25 | import net.dv8tion.jda.api.MessageBuilder;
26 | import net.dv8tion.jda.api.Permission;
27 | import net.dv8tion.jda.api.entities.Member;
28 | import net.dv8tion.jda.api.entities.Role;
29 |
30 | /**
31 | *
32 | * @author John Grosh (jagrosh)
33 | */
34 | public class RoleinfoCommand extends Command
35 | {
36 | private final static String LINESTART = "\u25AB"; // ▫
37 | private final static String ROLE_EMOJI = "\uD83C\uDFAD"; // 🎭
38 |
39 | public RoleinfoCommand()
40 | {
41 | this.name = "roleinfo";
42 | this.aliases = new String[]{"rinfo","rankinfo"};
43 | this.help = "shows info about a role";
44 | this.arguments = "
106 | *
107 | * The {@link java.lang.NullPointerException NullPointerException} thrown will not be caught by this method!
108 | *
109 | * @param event
110 | * The CommandEvent that triggered the Command
111 | * @param command
112 | * The Command that was triggered
113 | * @param throwable
114 | * The Throwable thrown during Command execution
115 | */
116 | default void onCommandException(CommandEvent event, Command command, Throwable throwable) {
117 | // Default rethrow as a runtime exception.
118 | throw throwable instanceof RuntimeException? (RuntimeException)throwable : new RuntimeException(throwable);
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/entities/impl/OAuth2UserImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2.entities.impl;
17 |
18 | import com.jagrosh.jdautilities.oauth2.OAuth2Client;
19 | import com.jagrosh.jdautilities.oauth2.Scope;
20 | import com.jagrosh.jdautilities.oauth2.entities.OAuth2User;
21 | import com.jagrosh.jdautilities.oauth2.exceptions.MissingScopeException;
22 | import com.jagrosh.jdautilities.oauth2.session.Session;
23 | import net.dv8tion.jda.api.sharding.ShardManager;
24 | import net.dv8tion.jda.api.JDA;
25 | import net.dv8tion.jda.api.entities.User;
26 |
27 | /**
28 | *
29 | * @author John Grosh (john.a.grosh@gmail.com)
30 | */
31 | public class OAuth2UserImpl implements OAuth2User
32 | {
33 | private final OAuth2Client client;
34 | private final Session session;
35 | private final long id;
36 | private final String name, discriminator, avatar, email;
37 | private final boolean verified, mfaEnabled;
38 |
39 | public OAuth2UserImpl(OAuth2Client client, Session session, long id, String name, String discriminator,
40 | String avatar, String email, boolean verified, boolean mfaEnabled)
41 | {
42 | this.client = client;
43 | this.session = session;
44 | this.id = id;
45 | this.name = name;
46 | this.discriminator = discriminator;
47 | this.avatar = avatar;
48 | this.email = email;
49 | this.verified = verified;
50 | this.mfaEnabled = mfaEnabled;
51 | }
52 |
53 | @Override
54 | public OAuth2Client getClient()
55 | {
56 | return client;
57 | }
58 |
59 | @Override
60 | public Session getSession()
61 | {
62 | return session;
63 | }
64 |
65 | @Override
66 | public String getId()
67 | {
68 | return Long.toUnsignedString(id);
69 | }
70 |
71 | @Override
72 | public long getIdLong()
73 | {
74 | return id;
75 | }
76 |
77 | @Override
78 | public String getName()
79 | {
80 | return name;
81 | }
82 |
83 | @Override
84 | public String getEmail()
85 | {
86 | if(Scope.contains(getSession().getScopes(), Scope.EMAIL))
87 | throw new MissingScopeException("get email for user", Scope.EMAIL);
88 | return email;
89 | }
90 |
91 | @Override
92 | public boolean isVerified()
93 | {
94 | return verified;
95 | }
96 |
97 | @Override
98 | public boolean isMfaEnabled()
99 | {
100 | return mfaEnabled;
101 | }
102 |
103 | @Override
104 | public String getDiscriminator()
105 | {
106 | return discriminator;
107 | }
108 |
109 | @Override
110 | public String getAvatarId()
111 | {
112 | return avatar;
113 | }
114 |
115 | @Override
116 | public String getAvatarUrl()
117 | {
118 | return getAvatarId() == null ? null : "https://cdn.discordapp.com/avatars/" + getId() + "/" + getAvatarId()
119 | + (getAvatarId().startsWith("a_") ? ".gif" : ".png");
120 | }
121 |
122 | @Override
123 | public String getDefaultAvatarId()
124 | {
125 | return DEFAULT_AVATARS[Integer.parseInt(getDiscriminator()) % DEFAULT_AVATARS.length];
126 | }
127 |
128 | @Override
129 | public String getDefaultAvatarUrl()
130 | {
131 | return "https://discord.com/assets/" + getDefaultAvatarId() + ".png";
132 | }
133 |
134 | @Override
135 | public String getEffectiveAvatarUrl()
136 | {
137 | return getAvatarUrl() == null ? getDefaultAvatarUrl() : getAvatarUrl();
138 | }
139 |
140 | @Override
141 | public String getAsMention()
142 | {
143 | return "<@" + id + '>';
144 | }
145 |
146 | @Override
147 | public User getJDAUser(JDA jda)
148 | {
149 | return jda.getUserById(id);
150 | }
151 |
152 | @Override
153 | public User getJDAUser(ShardManager shardManager)
154 | {
155 | return shardManager.getUserById(id);
156 | }
157 |
158 | @Override
159 | public boolean equals(Object o)
160 | {
161 | if (!(o instanceof OAuth2UserImpl))
162 | return false;
163 | OAuth2UserImpl oUser = (OAuth2UserImpl) o;
164 | return this == oUser || this.id == oUser.id;
165 | }
166 |
167 | @Override
168 | public int hashCode()
169 | {
170 | return Long.hashCode(id);
171 | }
172 |
173 | @Override
174 | public String toString()
175 | {
176 | return "U:" + getName() + '(' + id + ')';
177 | }
178 |
179 | private static final String[] DEFAULT_AVATARS = new String[] {
180 | "6debd47ed13483642cf09e832ed0bc1b",
181 | "322c936a8c8be1b803cd94861bdfa868",
182 | "dd4dbc0016779df1378e7812eabaa04d",
183 | "0e291f67c9274a1abdddeb3fd919cbaa",
184 | "1cbd08c76f8af6dddce02c5138971129"
185 | };
186 | }
187 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS='"-Xmx64m"'
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/Scope.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.oauth2;
17 |
18 | /**
19 | * Constants used to specify the scope of OAuth2 sessions.
20 | *
21 | * public class BadCommand extends Command {
91 | *
92 | * public BadCommand() {
93 | * this.name = "bad";
94 | * this.category = new Category("bad category", event {@literal ->} {
95 | * // This will throw a NullPointerException if it's not from a Guild!
96 | * return event.getGuild().getIdLong() == 12345678910111213;
97 | * });
98 | * }
99 | *
100 | * {@literal @Override}
101 | * protected void execute(CommandEvent) {
102 | * event.reply("This is a bad command!");
103 | * }
104 | *
105 | * }
More specifically, this is the User that the session is currently managing when retrieved using
29 | * {@link com.jagrosh.jdautilities.oauth2.OAuth2Client#getUser(Session) OAuth2Client#getUser}.
30 | *
31 | * @author John Grosh (john.a.grosh@gmail.com)
32 | * @author Kaidan Gustave
33 | */
34 | public interface OAuth2User extends ISnowflake, IMentionable
35 | {
36 | /**
37 | * Gets the underlying {@link com.jagrosh.jdautilities.oauth2.OAuth2Client OAuth2Client}
38 | * that created this OAuth2User.
39 | *
40 | * @return The OAuth2Client that created this OAuth2User.
41 | */
42 | OAuth2Client getClient();
43 |
44 | /**
45 | * Gets the originating {@link com.jagrosh.jdautilities.oauth2.session.Session}
46 | * that is responsible for this OAuth2User.
47 | *
48 | * @return The Session responsible for this OAuth2User.
49 | */
50 | Session getSession();
51 |
52 | /**
53 | * Gets the user's Snowflake ID as a String.
54 | *
55 | * @return The user's Snowflake ID as a String.
56 | */
57 | String getId();
58 |
59 | /**
60 | * Gets the user's Snowflake ID as a {@code long}.
61 | *
62 | * @return The user's Snowflake ID as a {@code long}.
63 | */
64 | long getIdLong();
65 |
66 | /**
67 | * Gets the user's account name.
68 | *
69 | * @return The user's account name.
70 | */
71 | String getName();
72 |
73 | /**
74 | * Gets the user's email address that is associated with their Discord account.
75 | *
76 | *
This method is scheduled for removal upon merging it
162 | * with master in JDA-Utilities 2.2
163 | */
164 | @Deprecated
165 | default boolean isBot()
166 | {
167 | // Note: the code here has not changed from it's implementation.
168 | return false;
169 | }
170 |
171 | /**
172 | * Gets the user as a discord formatted mention:
173 | *
{@code <@SNOWFLAKE_ID> }
174 | *
175 | * @return A discord formatted mention of this user.
176 | */
177 | String getAsMention();
178 |
179 | /**
180 | * Gets the corresponding {@link net.dv8tion.jda.api.entities.User JDA User}
181 | * from the provided instance of {@link net.dv8tion.jda.api.JDA JDA}.
182 | *
183 | * > getGuilds(Session session)
166 | {
167 | Checks.notNull(session, "session");
168 | if(!Scope.contains(session.getScopes(), Scope.GUILDS))
169 | throw new MissingScopeException("get guilds for a Session", Scope.GUILDS);
170 | return new OAuth2Action
>(this, Method.GET, OAuth2URL.CURRENT_USER_GUILDS.compile()) {
171 | @Override
172 | protected Headers getHeaders()
173 | {
174 | return Headers.of("Authorization", generateAuthorizationHeader(session));
175 | }
176 |
177 | @Override
178 | protected List
Trying to call this using a Session without the scope will cause a
115 | * {@link com.jagrosh.jdautilities.oauth2.exceptions.MissingScopeException MissingScopeException}
116 | * to be thrown.
117 | *
118 | * @param session
119 | * The Session to get OAuth2Guilds for.
120 | *
121 | * @return A {@link com.jagrosh.jdautilities.oauth2.requests.OAuth2Action OAuth2Action} for
122 | * the OAuth2Guilds to be retrieved.
123 | *
124 | * @throws com.jagrosh.jdautilities.oauth2.exceptions.MissingScopeException
125 | * If the provided Session does not have the 'guilds' scope.
126 | */
127 | @CheckReturnValue
128 | OAuth2Action> getGuilds(Session session);
129 |
130 | /**
131 | * Gets the client ID for this OAuth2Client.
132 | *
133 | * @return The client ID.
134 | */
135 | long getId();
136 |
137 | /**
138 | * Gets the client's secret.
139 | *
140 | * @return The client's secret.
141 | */
142 | String getSecret();
143 |
144 | /**
145 | * Gets the client's {@link com.jagrosh.jdautilities.oauth2.state.StateController StateController}.
146 | *
147 | * @return The client's StateController.
148 | */
149 | StateController getStateController();
150 |
151 | /**
152 | * Gets the client's {@link com.jagrosh.jdautilities.oauth2.session.SessionController SessionController}.
153 | *
154 | * @return The client's SessionController.
155 | */
156 | SessionController getSessionController();
157 |
158 | /**
159 | * Builder for creating OAuth2Client instances.
160 | *
161 | *
181 | *
184 | */
185 | public OAuth2Client build()
186 | {
187 | Checks.check(clientId >= 0, "Client ID is invalid!");
188 | Checks.notEmpty(clientSecret, "Client Secret");
189 | return new OAuth2ClientImpl(clientId, clientSecret, sessionController, stateController, client);
190 | }
191 |
192 | /**
193 | * Sets the OAuth2Client's ID.
194 | *
195 | * @param clientId
196 | * The OAuth2Client's ID.
197 | *
198 | * @return This builder.
199 | */
200 | public Builder setClientId(long clientId)
201 | {
202 | this.clientId = clientId;
203 | return this;
204 | }
205 |
206 | /**
207 | * Sets the OAuth2Client's secret.
208 | *
209 | * @param clientSecret
210 | * The OAuth2Client's secret.
211 | *
212 | * @return This builder.
213 | */
214 | public Builder setClientSecret(String clientSecret)
215 | {
216 | this.clientSecret = clientSecret;
217 | return this;
218 | }
219 |
220 | /**
221 | * Sets the OAuth2Client's {@link com.jagrosh.jdautilities.oauth2.session.SessionController SessionController}.
222 | *
223 | * @param sessionController
224 | * The OAuth2Client's SessionController.
225 | *
226 | * @return This builder.
227 | */
228 | public Builder setSessionController(SessionController sessionController)
229 | {
230 | this.sessionController = sessionController;
231 | return this;
232 | }
233 |
234 | /**
235 | * Sets the OAuth2Client's {@link com.jagrosh.jdautilities.oauth2.state.StateController StateController}.
236 | *
237 | * @param stateController
238 | * The OAuth2Client's StateController.
239 | *
240 | * @return This builder.
241 | */
242 | public Builder setStateController(StateController stateController)
243 | {
244 | this.stateController = stateController;
245 | return this;
246 | }
247 |
248 | /**
249 | * Sets the client's internal {@link okhttp3.OkHttpClient OkHttpClient} used for
250 | * all requests and interactions with Discord.
251 | *
252 | * @param client
253 | * The OAuth2Client's OkHttpClient.
254 | *
255 | * @return This builder.
256 | */
257 | public Builder setOkHttpClient(OkHttpClient client)
258 | {
259 | this.client = client;
260 | return this;
261 | }
262 | }
263 | }
264 |
--------------------------------------------------------------------------------
/command/src/main/java/com/jagrosh/jdautilities/command/annotation/JDACommand.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jagrosh.jdautilities.command.annotation;
17 |
18 | import com.jagrosh.jdautilities.command.Command;
19 | import net.dv8tion.jda.api.Permission;
20 |
21 | import java.lang.annotation.*;
22 |
23 | /**
24 | * An Annotation applicable to {@link java.lang.reflect.Method Method}s that will act as
25 | * {@link com.jagrosh.jdautilities.command.Command Command}s when added to a Client
26 | * using {@link com.jagrosh.jdautilities.command.CommandClientBuilder#addAnnotatedModule(Object)
27 | * CommandClientBuilder#addAnnotatedModule()} serving as metadata "constructors" for what
28 | * would be a class extending Command of the same functionality and settings.
29 | *
30 | *
Following that, any methods of said class annotated with this annotation (whose names
42 | * are also given as parameters of the {@code @Module} annotation) will be registered to the
43 | * module and "compiled" through the AnnotatedModuleCompiler provided in CommandClientBuilder.
44 | *
45 | *
57 | *
58 | * @see com.jagrosh.jdautilities.command.annotation.JDACommand.Module
59 | *
60 | * @since 1.7
61 | * @author Kaidan Gustave
62 | */
63 | @Retention(RetentionPolicy.RUNTIME)
64 | @Target(ElementType.METHOD)
65 | public @interface JDACommand
66 | {
67 | /**
68 | * The name and aliases of the command.
69 | *
70 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand.Module @JDACommand.Module}({@link com.jagrosh.jdautilities.command.annotation.JDACommand.Module#value() value} = "example")
46 | * public class AnnotatedModuleCmd {
47 | *
48 | * {@literal @JDACommand(}
49 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand#name() name} = {"example", "test", "demo"},
50 | * {@link com.jagrosh.jdautilities.command.annotation.JDACommand#help() help} = "gives an example of what commands do"
51 | * )
52 | * public void example(CommandEvent) {
53 | * event.reply("Hey look! This would be the bot's reply if this was a command!");
54 | * }
55 | *
56 | * }
Default {@code true}.
87 | *
88 | * @return {@code true} if the command can only be used in a guild,
89 | * {@code false} otherwise.
90 | */
91 | boolean guildOnly() default true;
92 |
93 | /**
94 | * The name of a role required to use this command.
95 | *
96 | * @return The name of a role required to use this command.
97 | */
98 | String requiredRole() default "";
99 |
100 | /**
101 | * Whether or not the command is owner only.
102 | *
Default {@code true}.
103 | *
104 | * @return {@code true} if the command is owner only, {@code false} otherwise.
105 | */
106 | boolean ownerCommand() default false;
107 |
108 | /**
109 | * The arguments string for the command.
110 | *
111 | * @return The arguments string for the command.
112 | */
113 | String arguments() default "";
114 |
115 | /**
116 | * The {@link JDACommand.Cooldown JDACommand.Cooldown} for the command.
117 | *
118 | *
Default {@code true}.
146 | *
147 | *
This holds data to properly locate a static field representing
172 | * this command's {@link com.jagrosh.jdautilities.command.Command.Category
173 | * Category}.
174 | *
175 | * @return The {@code @Category} for this command.
176 | */
177 | Category category() default @Category(name = "null", location = Category.class);
178 |
179 | /**
180 | * A helper annotation to assist in location of methods that will generate
181 | * into {@link com.jagrosh.jdautilities.command.Command Command}s.
182 | *
183 | *
The arrangement of the double parameters is not important, so methods
187 | * may do it as {@code (CommandEvent, Command)} or {@code (Command, CommandEvent)}.
188 | *
189 | * @see JDACommand
190 | */
191 | @Target(ElementType.TYPE)
192 | @Retention(RetentionPolicy.RUNTIME)
193 | @interface Module
194 | {
195 | /**
196 | * The names of any methods that will be targeted when compiling this object
197 | * using the {@link com.jagrosh.jdautilities.command.AnnotatedModuleCompiler
198 | * AnnotatedModuleCompiler}.
199 | *
200 | *