不和谐 具有用于编写自定义机器人的出色API,并且非常活跃 机器人社区。今天我们’我将看看如何开始制作自己的东西。
您将需要一些编程知识才能编写机器人程序,因此它不是’虽然适合所有人,但幸运的是,有一些流行语言模块可以很容易地做到。我们’将使用最受欢迎的一种 discord.js.
有关: How to Create, Set Up, 和 Manage 您r 不和谐 Server
入门
前往不和谐’s 机器人门户,然后创建一个新的应用程序。
您’我想记下客户端ID和秘密(当然,您应该保守秘密)。但是,这不是’t the bot, just the “Application.” 您’我必须将机器人添加到“Bot” tab.
Make a note of this token as well, 和 keep it a secret. Do not, under any circumstances, commit this key to Github. 您r bot will be hacked almost immediately.
安装Node.js并获取编码
要在网页外运行Javascript代码,您需要 节点。下载它,安装它,并确保它可以在终端上运行(或命令提示符,因为所有这些都应在Windows系统上运行)。默认命令是“node.”
我们还建议您安装Nodemon工具。它’一个监视您的机器人的命令行应用程序’s code 和 restarts automatically on changes. 您 can install it by running the following command:
npm i -g nodemon
您’ll need a text editor. 您 could just use notepad, but we recommend either 原子 要么 VSC.
这里’s our “Hello World”:
const 不和谐 = require('discord.js'); const client = new 不和谐.Client(); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('message', msg => { if (msg.content === 'ping') { msg.reply('pong'); } }); client.login('token');
此代码取自 discord.js 例。让’s break it down.
- 前两行用于配置客户端。第一行将模块导入到名为的对象中“Discord,”第二行初始化客户端对象。
- The
client.on('ready')
block will fire when the bot starts up. 这里, it’刚刚配置为将其名称记录到终端。 - The
client.on('message')
block will fire everytime a new message is posted to any channel. Of course, you’我需要检查邮件内容,然后’s what theif
block does. If the message just says “ping,”然后它将回复“Pong!” - 最后一行使用Bot门户中的令牌登录。显然,此屏幕截图中的令牌是伪造的。唐’永远不要将令牌发布到互联网上。
Copy this code, paste in your token at the bottom, 和 save it as index.js
in a dedicated folder.
How to Run the 机器人
转到您的终端,然后运行以下命令:
nodemon --inspect index.js
This starts up the script, 和 also fires up the Chrome debugger, which you can access by typing chrome://inspect/
into Chrome’s Omnibar,然后打开“Node专用的devtools。”
现在,它应该说“Logged in as <bot-name>,” but here I’ve添加了一行,它将记录接收到控制台的所有消息对象:
那么,什么构成了这个消息对象呢?实际上有很多东西:
最值得注意的是,您具有作者信息和频道信息,可以使用msg.author和msg.channel访问这些信息。我建议使用这种方法将对象记录到Chrome 节点 devtools,然后四处看看以了解它的工作原理。您可能会发现一些有趣的东西。例如,在这里,机器人将其回复记录到控制台,因此机器人’s replies trigger client.on('message')
. So, I made a spambot:
注意:请注意这一点,因为您没有’真的想处理递归。
How to Add the 机器人 to 您r Server
This part is harder than it should be. 您 have to take this URL:
//discordapp.com/oauth2/authorize?client_id=CLIENTID&scope=bot
并用您的机器人替换CLIENTID’的客户ID,可在 申请页面. Once this is done though, you can give the link to your friends to have them add the bot to their 服务器s as well.
好吧,那我还能做什么?
除了基本设置外,其他任何事情都完全由您决定。但是,这不会’如果我们停下来打个招呼,那么本教程就不算什么了,所以让’我去过一些 文件资料,因此您对什么内容有了更好的了解’可能的。我建议您尽可能地通读’有充分的记录。
I would recommend adding console.log(client)
to the start of your code, 和 taking a look at the client object in the console:
From here, you can learn a lot. Since you can add a bot to multiple 服务器s at once, 服务器s are part of the 公会
map object. In that object are the individual 公会 (which is the API’s name for “server”),并且这些行会对象具有包含所有信息和消息列表的频道列表。该API非常深入,可能需要一段时间才能学习,但是至少’易于设置并开始学习。