discord china_Javacord的Discord机器人:如何进行首次机器人

本文翻译自Medium平台,介绍了如何利用Javacord库为Discord创建首个机器人,涵盖了设置过程和基本操作。
摘要由CSDN通过智能技术生成

discord china

In my last article, Creating a Discord Developer Application, I talked about the Discord Developer Portal, how to create a Developer Application, and I gave you a few ideas on what you can do with your bot. In this article, I’ll finally be answering some questions you might have about this whole series. Before I answer any of those questions, though, allow me to provide a quick disclaimer.

在上一篇文章“ 创建Discord开发人员应用程序”中 ,我讨论了Discord开发人员门户网站,如何创建开发人员应用程序,并为您提供了一些有关如何使用机器人进行操作的想法。 在本文中,我将最终回答有关整个系列的一些问题。 但是,在我回答任何一个问题之前,请允许我提供快速的免责声明。

Disclaimer Time!

免责声明时间!

This article assumes you understand the basics of the Java programming language to a functional level. This includes but is not limited to an understanding of methods, object creation, and lambdas. If you are not familiar with these concepts, save this article on the side and come back to it when you are. For total beginners, I would recommend w3schools as an excellent place to learn the basics of Java and other languages.

本文假定您在功能上了解Java编程语言的基础。 这包括但不限于对方法,对象创建和lambda的理解。 如果您不熟悉这些概念,请将本文保留在一边,然后在您回来时再来看看。 对于初学者来说,我建议将w3schools作为学习Java和其他语言基础的理想场所。

On another important note: This is not an official Javacord article or series, and I am not a Javacord team member. I am simply spreading the word and proper usage of the library I like to use for my Discord bots. This article does, however, include information provided directly from the Javacord team to ensure I am giving you the most correct and clean code as possible.

另一个重要说明: 这不是Javacord的官方文章或系列,我也不是Javacord团队成员。 我只是在传播我喜欢用于Discord机器人的库的字眼和正确用法。 但是,本文的确包含了直接从Javacord团队提供的信息,以确保我能为您提供最正确,最干净的代码。

Now, it’s time to answer that first big question.

现在,该回答第一个大问题了。

What is Javacord?

什么是Javacord?

Javacord is an amazing library that allows you to communicate with the Discord API from your Java code in a greatly simplified manner. You can create objects and call methods that your bot will use to send messages, manipulate roles on a user, and so much more. The Javacord website has everything clearly laid out in terms of proper documentation and example code so that even the total beginner can create a basic Discord bot. I’ll be referencing some of their examples, wiki pages, and JavaDocs in this article and any future articles about bots for you to read up more on how the library works.

Javacord是一个了不起的库,它允许您以极大的简化方式通过Java代码与Discord API进行通信。 您可以创建对象和调用方法,您的机器人将使用这些对象和方法来发送消息,操纵用户的角色等等。 Javacord网站以正确的文档和示例代码清楚地列出了所有内容,因此即使是初学者也可以创建基本的Discord机器人。 在本文以及以后有关机器人的任何文章中,我将引用他们的一些示例,Wiki页面和JavaDocs,以供您阅读有关该库如何工作的更多信息。

I would highly recommend you join the official Javacord Discord server before you start working with this library. There is an absolutely wonderful community surrounding it (and I’m happy to say I’m a part of it) that is always willing to help you with an issue if you’re willing to learn. Here you can speak with me, the creators, the contributors, and plenty of other bot developers just like you. Come join in on the discussion!

强烈建议您在开始使用此库之前加入正式的Javacord Discord服务器 。 周围有一个绝对美好的社区(我很高兴地说我是其中的一部分),如果您愿意学习,它总是愿意为您解决问题。 在这里,您可以与我,创作者,贡献者以及许多其他像您一样的机器人开发者交谈。 快来参加讨论!

So I need Javacord for my bot, how do I get it?

所以我的机器人需要Javacord,我怎么得到它?

The Javacord wiki’s welcome page tells you exactly what to do to put Javacord in your bot project whether you’re using Gradle or Maven. In our case of using Gradle, it’s a very simple couple of steps:

Javacord Wiki的欢迎页面告诉您无论使用Gradle还是Maven,将Javacord放入机器人项目的确切方法。 在我们使用Gradle的情况下,这是非常简单的几个步骤:

  1. Open the build.gradle file in your IntelliJ bot project

    在您的IntelliJ bot项目中打开build.gradle文件

  2. Delete the testCompile line in the dependencies block (this line is for doing tests on your code, which I may cover in a later article)

    删除依赖关系块中的testCompile行(此行用于对您的代码进行测试,我可能会在以后的文章中介绍)

  3. Where you deleted the previous line, add the following: implementation ‘org.javacord:javacord:3.0.6’

    在删除上一行的地方,添加以下内容: 实现'org.javacord:javacord:3.0.6'

Make sure to click the Load Gradle Changes button at the top right after you add this line. This allows Gradle to import Javacord into your project for you to create your bot.

添加此行后,请确保单击右上方的“ Load Gradle Changes”按钮。 这允许Gradle将Javacord导入到您的项目中,以供您创建机器人。

Congratulations! After a few moments of importing, you will officially have access to countless tools to use to write your bot with. Now, we’re going to use them for a very simple bot that we’ll expand on later in this article.

恭喜你! 片刻导入后,您将可以正式使用无数工具来编写机器人。 现在,我们将把它们用于一个非常简单的机器人,我们将在本文后面进行扩展。

How do I make my bot do something?

如何使我的机器人做某事?

Back on Javacord’s home page, there is an excellent example labeled “Logging in” we are going to use to verify that your bot is up and running. This is always a good test to run right after you do all of this setup, so we’re going to do it here as well. When you are done following the example, your main file should look something like the picture below (remember to replace yourtokenhere with the bot’s token we got in the last article).

回到Javacord的主页上 ,有一个很好的示例,名为“登录”,我们将使用它来验证您的机器人已启动并正在运行。 完成所有设置后,这始终是一个很好的测试,因此我们也将在这里进行。 完成该示例后,您的主文件应类似于下图(请记住,将上一文章中的bot令牌替换为yourtokenhere )。

import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;public class Bot { public static void main(String[] args) {
DiscordApi api = new DiscordApiBuilder().setToken("yourtokenhere").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()); }
}

From here, you can run your bot by pressing Shift+F10; if you’ve followed all of these steps correctly, you should see the print statement with the bot’s invite link appear in the console at the bottom of the screen. Use this to invite your bot to your server so you can test out how it works!

在这里,您可以按Shift + F10来运行您的机器人; 如果正确执行了所有这些步骤,则应该在屏幕底部的控制台中看到带有bot邀请链接的打印语句。 使用它邀请您的机器人到您的服务器,以便您可以测试它的工作方式!

What did I just write?

我刚刚写了什么?

At the beginning of getting into this library, some things may be a little confusing, so I’ll break down what’s going on inside of the main method here:

在进入这个库的开始,有些事情可能会有些混乱,所以我将在这里分解主要方法中的内容:

  • First: we’re creating a DiscordApi instance. Simply put, this is what allows us to interact with the Discord API. We create an instance of the DiscordApiBuilder class, pass it the token to login with, and then tell it to log in to the bot’s account. join() is a method of the CompletableFuture that login() returns; it blocks the current thread and returns the completed DiscordApi instance to the api variable.

    首先:我们正在创建DiscordApi实例。 简而言之,这就是使我们能够与Discord API进行交互的原因。 我们创建DiscordApiBuilder类的实例,将令牌传递给它进行登录,然后告诉它登录到机器人的帐户。 join()login()返回的CompletableFuture的方法; 它会阻塞当前线程,并将完整的DiscordApi实例返回给api变量。

  • Second: we add what’s called a “listener”. A listener does exactly what it sounds like; it waits and listens for a certain thing to happen, and in the following code block, it reacts accordingly. In our case, we’re listening for any message that the bot can read. Every time that happens, it’s called an event and the bot can access information about it using the event parameter. You can use whatever name for the event you’d like, but you want it to still be representative of the event you’re passing in to the lambda (in this case, a MessageCreateEvent).

    第二:我们添加所谓的“侦听器”。 聆听者完全按照听上去的做。 它等待并侦听某件事的发生,然后在下面的代码块中做出相应的React。 就我们而言,我们正在侦听该机器人可以读取的任何消息。 每次发生时,它都称为事件,并且机器人可以使用event参数访问有关该事件的信息。 您可以为事件使用任何名称,但是您希望它仍然代表您要传递给lambda的事件(在本例中为MessageCreateEvent )。

  • Third: every time the bot gets a message, it checks to see if the message content of the event matches “!ping”. The equalsIgnoreCase() method does this comparison and, as the name entails, ignores upper or lower case letters, and returns a true or false value based on the match.

    第三:每当机器人收到消息时,它都会检查事件的消息内容是否匹配“!ping”。 equalsIgnoreCase()方法进行此比较,并且顾名思义,将忽略大写或小写字母,并根据匹配结果返回true或false值。

  • Fourth: if the message content matches, we get the text channel that the event happened in, and to it, we send the message “Pong!”.

    第四:如果消息内容匹配,我们将获得事件发生的文本通道,并向其发送消息“ Pong!”。
  • Lastly: The final line in the main method is simply a print statement that calls the createBotInvite() method of the API instance. This prints out the URL that you can use to invite the bot to your server.

    最后:main方法的最后一行只是一条打印语句,该语句调用API实例的createBotInvite()方法。 这会打印出可用于邀请漫游器加入服务器的URL。

Once your bot is in your server, testing the code you just wrote is very simple. In any channel the bot has access to, send a !ping message and you should get the programmed response back almost immediately.

一旦您的机器人进入服务器,对您刚刚编写的代码进行测试就非常简单。 机器人可以访问的任何通道都发送!ping消息,您应该几乎立即返回编程的响应。

Image for post
Testing the ping command (supplied by author)
测试ping命令(由作者提供)

Congratulations x2! You technically have a functional Discord bot. It doesn’t do anything too helpful at the moment, though, so let’s fix that!

恭喜x2! 从技术上讲,您具有功能齐全的Discord机器人。 不过,目前它并没有太大帮助,所以让我们修复它!

I want my bot to do something useful!

我希望我的机器人做一些有用的事情!

I may show more example projects in time, but for the sake of this article, let’s work on a very simple task to give your bot: welcome new users to your Discord server!

我可能会及时显示更多示例项目,但是为了本文的方便,让我们着手做一个非常简单的任务来给您的机器人:欢迎新用户使用Discord服务器!

The main driver behind this task is a different kind of listener, called a ServerMemberJoinListener. As the name entails, this waits and listens for a member to join any server the bot is in. We want to welcome new users to the server, so we want to use this listener to act when somebody joins.

该任务背后的主要驱动程序是另一种侦听器,称为ServerMemberJoinListener 。 顾名思义,它等待并侦听成员加入该机器人所在的任何服务器。我们希望欢迎新用户加入该服务器,因此我们希望使用此侦听器在有人加入时采取行动。

As you can see in my code below, I’ve introduced something called an Optional. Javacord’s wiki has a great explanation of how to use this Java class, and I would highly recommend checking out the page to understand what I’m doing with channel.ifPresent().

正如您在下面的代码中看到的那样,我引入了一个称为Optional的东西。 Javacord的Wiki对如何使用此Java类进行了很好的解释 ,我强烈建议您检出页面以了解我对channel.ifPresent()的操作

import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
import org.javacord.api.entity.channel.TextChannel;import java.util.Optional;public class Bot { public static void main(String[] args) {
DiscordApi api = new DiscordApiBuilder().setToken("yourtokenhere").login().join()); // Welcome new users to your server
api.addServerMemberJoinListener(event -> {
Optional<Textchannel> channel = api.getTextChannelById(yourchannelidL);
channel.ifPresent(textChannel -> textChannel.sendMessage("Welcome to the server, " + event.getUser().getMentionTag() + "!"));
}); // Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite()); }
}

Like I did earlier, let me give you a quick rundown on what the code is doing:

就像我之前所做的那样,让我简要介绍一下代码的作用:

  • First: add a ServerMemberJoinListener to wait and listen to a Discord user joining the server the bot is on. This is the event trigger we’ll be using to mention the user in a moment.

    首先:添加ServerMemberJoinListener来等待并收听Discord用户加入该机器人所在的服务器。 这是事件触发器,我们稍后将使用它来提及用户。

  • Second: request an Optional object with the type parameter TextChannel, use the API instance to get a text channel by its ID (check out this post by Discord support on how to get a channel’s ID), and assign that value to the Optional. Because we’re just feeding in a string of numbers, this channel may or may not exist, and that’s why we’re using an Optional. (Note: the L at the end of the numbers indicate a long, a Java datatype. When hard-coding IDs, it is best practice to use this datatype as opposed to a String, as the natural form of IDs is long.)

    第二:使用类型参数TextChannel请求一个Optional对象,使用API​​实例通过其ID获取文本通道(Discord支持人员请查看此文章 ,了解如何获取通道的ID),然后将该值分配给Optional 。 因为我们只是输入一串数字,所以此通道可能存在也可能不存在,这就是为什么我们使用Optional的原因。 (注意:数字末尾的L表示long ,它是Java数据类型。当对ID进行硬编码时,由于ID的自然形式很 ,因此最好的做法是使用此数据类型而不是String 。)

  • Third: handle the Optional appropriately. Call the ifPresent() method of the Optional to check if the channel exists and if the bot can see it; if it does and if it can, use the lambda’s textChannel parameter to send the programmed message. Get the user who joined (the User is stored in the event variable, so we use event.getUser() to retrieve them) and get their mention tag to use in the message. The mention tag is, in the test below, where the user’s name is preceded by an @. Using the mention tag “pings” the user and lets them know someone is trying to get their attention; in our case, that’s our bot!

    第三:适当处理Optional 。 调用可选ifPresent()方法来检查信道存在, 并且如果机器人能看到它; 如果可以,请使用lambda的textChannel参数发送已编程的消息。 获取加入的用户 (该用户存储在事件变量中,因此我们使用event.getUser()来检索他们)并获取其提及标记以在消息中使用。 在下面的测试中,提及标记在用户名前面带有@。 使用提及标签“ ping”用户,并让他们知道有人正试图引起他们的注意; 就我们而言,这就是我们的机器人!

Image for post
Testing the bot’s welcome message (supplied by author)
测试机器人的欢迎消息(由作者提供)

Congratulations x3! After you write all of this code and restart your bot, any user should be given a warm welcome in whatever channel you specified. It’s not the most spectacular first project, but it’s a very good introduction to the basics of the Javacord library and Discord bot development. It does have a practical application, as some server owners want to automate welcoming new users. If you want to pretty up the bot’s welcome message, I’d suggest checking out Javacord’s Embed FAQ and learning about embeds to make things look just a little neater.

恭喜x3! 编写完所有代码并重新启动bot之后,无论您使用哪种渠道,都应向任何用户表示热烈欢迎。 这不是最壮观的第一个项目,但是它很好地介绍了Javacord库和Discord bot开发的基础知识。 它确实具有实际的应用程序,因为某些服务器所有者希望自动化欢迎新用户。 如果您想修饰一下机器人的欢迎信息,我建议您查看Javacord的Embed FAQ并学习关于embed的知识,以使事情看起来更加整洁。

That does it for your introduction to Discord Bots with Javacord! I’d like to thank the Javacord team for personally providing the proper information to me so I could make this article accurate and as high-quality as it can be. I’ll be happy to respond to any questions, comments, or suggestions you may have about this article or future ones. Make sure to subscribe to The Playground Digest newsletter to get the first word on new articles playing with Java, and make sure to give me a follow to see more like this in the future. If you know anybody who isn’t quite sure how to make a basic Discord bot in Java, share this article with them to give them a great place to start!

这就是您使用Javacord向Discord Bots进行介绍的过程! 我要感谢Javacord团队亲自为我提供了适当的信息,以便使本文尽可能准确,高质量。 我很乐意回答您对本文或以后的任何问题,评论或建议。 确保订阅The Playground Digest新闻通讯,以获得有关使用Java的新文章的第一句话,并确保给我一定的关注,以供日后使用。 如果您认识不十分了解如何用Java制作基本Discord机器人的人,请与他们分享本文,为他们提供一个理想的起点!

Want to see all of these concepts in action? Check out my Fiverr®️ Gig®️ to see how I can make a custom Discord bot for your server using everything I discussed in this article, and whatever else you want your bot to do!

希望看到所有这些概念在起作用吗? 看看我的Fiverr®️Gig®️ ,看看如何使用本文中讨论的所有方法以及您希望机器人执行的其他操作为您的服务器制作自定义Discord机器人!

翻译自: https://medium.com/java-playground/discord-bots-with-javacord-how-to-make-your-first-bot-f199bd1f11db

discord china

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值