GithubHelp home page GithubHelp logo

javacord / javacord-bot Goto Github PK

View Code? Open in Web Editor NEW
6.0 5.0 4.0 1.22 MB

This is the bot used on the Javacord server.

License: Apache License 2.0

Dockerfile 0.24% Java 98.47% Kotlin 1.29%
javacord discord bot discord-bot javacord-api java hacktoberfest

javacord-bot's Introduction

Javacord Latest version Latest JavaDocs Javacord Wiki Javacord Discord server

An easy to use multithreaded library for creating Discord bots in Java.

Javacord is a modern library that focuses on simplicity and speed ๐Ÿš€. By reducing itself to standard Java classes and features like Optionals and CompletableFutures, it is extremely easy to use for every Java developer, as it does not require you to learn any new frameworks or complex abstractions. It has rich documentation and an awesome community on Discord that loves to help with any specific problems and questions.

Starting in early 2023, support for Java 8 will be discontinued and Java 11 will be the new minimum requirement for using Javacord. If you are not yet running Java 11+, we strongly recommend that you upgrade before the end of 2022.

๐ŸŽ‰ Basic Usage

The following example logs the bot in and replies to every "!ping" message with "Pong!". Note that message content is a privileged Intent and needs to specifically be enabled.

public class MyFirstBot {

    public static void main(String[] args) {
        // Insert your bot's token here
        String token = "your token";

        DiscordApi api = new DiscordApiBuilder().setToken(token).addIntent(Intent.MESSAGE_CONTENT).login().join();

        // Add a listener which answers with "Pong!" if someone writes "!ping"
        api.addMessageCreateListener(event -> {
            if (event.getMessageContent().equalsIgnoreCase("!ping")) {
                event.getChannel().sendMessage("Pong!");
            }
        });

        // Print the invite url of your bot
        System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
    }

}

More sophisticated examples can be found at the end of the README. You can also check out the example bot for a fully functional bot.

/ Slash commands

First, you need to create the ping pong slash command. Run this code one single time to create the command:

public class MyFirstBot {

    public static void main(String[] args) {
        // Insert your bot's token here
        String token = "your token";

        DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();

        SlashCommand.with("ping", "A simple ping pong command!").createGlobal(api).join();
    }
}

Discord now knows about your command and will offer it in your text channels if you type /.

Next, let's see how we can let the bot send answers to this simple slash command:

public class MyFirstBot {

    public static void main(String[] args) {
        // Insert your bot's token here
        String token = "your token";

        DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();

        api.addSlashCommandCreateListener(event -> {
            SlashCommandInteraction slashCommandInteraction = event.getSlashCommandInteraction();
            if (slashCommandInteraction.getCommandName().equals("ping")) {
                slashCommandInteraction.createImmediateResponder()
                    .setContent("Pong!")
                    .setFlags(MessageFlag.EPHEMERAL) // Only visible for the user which invoked the command
                    .respond();
            }
        });
    }
}

A more detailed version of how to use slash commands can be found in the wiki

๐Ÿ“ฆ Download / Installation

The recommended way to get Javacord is to use a build manager, like Gradle or Maven.
If you are not familiar with build managers, you can follow this setup guide or download Javacord directly from GitHub.

Javacord Dependency

Gradle

repositories { mavenCentral() }
dependencies { implementation 'org.javacord:javacord:3.8.0' }

Maven

<dependency>
    <groupId>org.javacord</groupId>
    <artifactId>javacord</artifactId>
    <version>3.8.0</version>
    <type>pom</type>
</dependency>

Sbt

libraryDependencies ++= Seq("org.javacord" % "javacord" % "3.8.0")

Optional Logger Dependency

Any Log4j-2-compatible logging framework can be used to provide a more sophisticated logging experience with being able to configure log format, log targets (console, file, database, Discord direct message, ...), log levels per class, and much more.

For example, Log4j Core in Gradle

dependencies { runtimeOnly 'org.apache.logging.log4j:log4j-core:2.19.0' }

Take a look at the logger configuration wiki article for further information.

๐Ÿ”ง IDE Setup

If you have never used Gradle or Maven before, you should take a look at one of the setup tutorials:

๐Ÿค Support

Javacord's Discord community is an excellent resource if you have questions about the library.

๐Ÿ“’ Documentation

  • The Javacord wiki is a great place to get started.
  • Additional documentation can be found in the JavaDoc.

๐Ÿ’ก How to Create a Bot User and Get Its Token

๐Ÿ“‹ Version Numbers

The version number has a 3-digit format: major.minor.trivial

  • major: Increased extremely rarely to mark a major release (usually a rewrite affecting very huge parts of the library).
  • minor: Any backward incompatible change to the api.
  • trivial: A backward compatible change to the api. This is usually an important bugfix (or a bunch of smaller ones) or a backwards compatible feature addition.

๐Ÿ”จ Deprecation Policy

A method or class that is marked as deprecated can be removed with the next minor release (but it will usually stay for several minor releases). A minor release might remove a class or method without having it deprecated, but we will do our best to deprecate it before removing it. We are unable to guarantee this though, because we might have to remove / replace something due to changes made by Discord, which we are unable to control. Usually you can expect a deprecated method or class to stay for at least 6 months before it finally gets removed, but this is not guaranteed.

โœจ Contributing

Contributions of any kind are welcome. You can start contributing to this library by creating issues, submitting pull requests or improving the Javacord Wiki.

If you want to submit pull requests you can find a list of good first issues here. You are not restricted to only these issues, so you can start with any other issue that you would like to do. Be sure to read the Contributing Guidelines before you start.

The awesome people that contributed to Javacord in the past can be found โœจhereโœจ

๐Ÿฅ‡ Large Bots Using Javacord

Javacord is used by many large bots. Here are just a few of them:

If you own a large bot that uses Javacord, feel free to add it to the list in a pull request!

๐Ÿ™Œ More Examples

Using the MessageBuilder ๐Ÿ› 

The following example uses the built-in MessageBuilder. It is very useful to construct complex messages with images, code-blocks, embeds, or attachments.

new MessageBuilder()
  .append("Look at these ")
  .append("awesome", MessageDecoration.BOLD, MessageDecoration.UNDERLINE)
  .append(" animal pictures! ๐Ÿ˜ƒ")
  .appendCode("java", "System.out.println(\"Sweet!\");")
  .addAttachment(new File("C:/Users/JohnDoe/Pictures/kitten.jpg"))
  .addAttachment(new File("C:/Users/JohnDoe/Pictures/puppy.jpg"))
  .setEmbed(new EmbedBuilder()
        .setTitle("WOW")
        .setDescription("Really cool pictures!")
        .setColor(Color.ORANGE))
  .send(channel);

Listeners in Their Own Class ๐Ÿ—ƒ

All the examples use inline listeners for simplicity. For better readability it is also possible to have listeners in their own class:

public class MyListener implements MessageCreateListener {

    @Override
    public void onMessageCreate(MessageCreateEvent event) {
        Message message = event.getMessage();
        if (message.getContent().equalsIgnoreCase("!ping")) {
            event.getChannel().sendMessage("Pong!");
        }
    }

}
api.addListener(new MyListener());

Libraries compatible with Javacord ๐Ÿ“š

This is a not exhaustive list of libraries that are compatible with Javacord. If you want to add your own library to this list, feel free to open a pull request! They are sorted alphabetically that means that the order does not reflect the usage or quality of the library.

Attach Listeners to Objects ๐Ÿ“Œ

You can even attach listeners to objects. Let's say you have a very sensitive bot. As soon as someone reacts with a ๐Ÿ‘Ž within the first 30 minutes of message creation, it deletes its own message.

api.addMessageCreateListener(event -> {
    if (event.getMessageContent().equalsIgnoreCase("!ping")) {
        event.getChannel().sendMessage("Pong!").thenAccept(message -> {
            // Attach a listener directly to the message
            message.addReactionAddListener(reactionEvent -> {
                if (reactionEvent.getEmoji().equalsEmoji("๐Ÿ‘Ž")) {
                    reactionEvent.deleteMessage();
                }
            }).removeAfter(30, TimeUnit.MINUTES);
        });
    }
}

The result then looks like this:

Creating a Temporary Voice Channel ๐Ÿ’ฃ๐ŸŽง

This example creates a temporary voice channel that gets deleted when the last user leaves it or if nobody joins it within the first 30 seconds after creation.

Server server = ...;
ServerVoiceChannel channel = new ServerVoiceChannelBuilder(server)
        .setName("tmp-channel")
        .setUserlimit(10)
        .create()
        .join();

// Delete the channel if the last user leaves
channel.addServerVoiceChannelMemberLeaveListener(event -> {
    if (event.getChannel().getConnectedUserIds().isEmpty()) {
        event.getChannel().delete();
    }
});

// Delete the channel if no user joined in the first 30 seconds 
api.getThreadPool().getScheduler().schedule(() -> {
    if (channel.getConnectedUserIds().isEmpty()) {
        channel.delete();
    }
}, 30, TimeUnit.SECONDS);

Note: You should also make sure to remove the channels on bot shutdown (or startup)

๐Ÿ“ƒ License

Javacord is distributed under the Apache license version 2.0.

javacord-bot's People

Contributors

bastian avatar burdoto avatar comroid-commit avatar joshix-1 avatar saladoc avatar vampire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

javacord-bot's Issues

HTML to Markdown conversion

For previews, like in the Wiki Command, it would be nice to correctly approximate the formatting of the previewed web page. For that we'll need to take the HTML content and properly replicate the formatting in markdown to the best of our ability.

The following formatting elements will be required:

  • <strong> to **
  • <em> to *
  • Headings (likely just treated as bold)
  • Weblinks
  • <code> both inline and in block form

Basic info commands

!teamcity - links to the TeamCity server.

!readme - links to Javacord's Readme page.

Implement a !timeout command

Create a command !timeout <user> <time> that temporarily mutes a user.

A muted user can not post messages or reactions and is unable to join voice channels. If they were in a voice channel when being muted, they are also moved to the server's AFK channel if possible.

The command is available to the Maintainer group (id 151325992038825984) in an unlimited form and to the contributor group (id: 399530229732868096) in a form that is limited as follows

  • can be used a maximum of X times over a 24 hour period by the same person
  • will mute the target for a maximum duration of Y

After the time elapses a muted person is automatically unmuted. Subsequent calls for the same target will overwrite their timeout duration. A duration of zero or smaller acts as an unmute.

All mute / unmute operations are to be logged to a channel specified by ID.

Option to limit bot to specific channel

I would like to add the bot to the DiscordApi server, but the commands of the bot should be limited to the java_javacord channel (id 381889796785831936) without requiring any special permission configuration (as I only have permissions to edit the permissions of the java_javacord channel).

I see two options:

  • Hardcode the id of the channel
  • Make it configurable via a command

We also have to consider commands like !timeout that should be limited to the Javacord server.

Improve Search commands

The /wiki and /docs commands both perform searches.

We should investigate if and how the search can be improved for users.

Possible techniques to explore:

  • Auto-Completion for known Keywords / Classes
  • Fuzzy Searches
  • ...

Detect latest javacord version.

  • Introduce a !latest command providing the latest javacord version
  • Rewrite the !maven and !gradle commands to include the latest version instead of the one used by the bot.

Automatically detect latest Javacord version

The maven and gradle commands should not be limited to the version the bot is currently running on. They should fetch and display the latest release version, no matter which version of javacord powers the bot.

Attempt to automatically rebase pull requests

Add a !rebase <pr> command available only to the Maintainer group (id: 151325992038825984).

If <pr> identifies a pull request to Javacord (or another project by the Javacord Organization), the bot attempts to rebase the pull request. This will be most likely done via a bash script that the bot will be able to run.

The bot is to report whether the rebase was successful or failed.

Standardize Error Handling

Right now both the !docs and !wiki commands may encounter errors during their execution. Since that may happen as well with future additions, we should find a standardized way of dealing with exceptions during program executions in order to stay consistent.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.