discord.js로 Hello World Discord 봇 만들기

6658 단어 typescriptdiscord
며칠 전 학교 동문들과 소통하기 위해 Discord 서버를 새로 만들었습니다.

Discord 서버에서 무언가를 하려면 봇을 만들어야 할 수도 있기 때문에 방금 discord.js를 테스트했습니다.

이 글에서는 내가 게시hello하고 봇이 채널에 답장world하는 Hello World 봇을 만드는 방법을 보여 드리겠습니다.

Discord 개발자 포털



https://discord.com/developers/docs/intro

discord.js



https://discord.js.org/#/

1단계 봇 설정



discord.py에는 이 단계에 대한 좋은 페이지가 있습니다.
https://discordpy.readthedocs.io/en/stable/discord.html

2단계 프로젝트 생성


discord.js에는 노드 16.6.0 이상이 필요합니다.



$ yarn init -y
# if you use npm
$ npm init -y

패키지 설치
js를 사용하려면 yarn add -D/npm install -D 건너 뛰십시오.
또한 dotenv는 선택 사항입니다. discord.js를 빠르게 테스트하려면 dotenv를 설치할 필요가 없으며 하드코딩해야 합니다Token.

$ yarn add discord.js dotenv
$ yarn add -D typescript ts-node
# for npm
$ npm install discord.js dotenv
$ npm install -D typescript ts-node


3단계 Hello World 봇 작성



js를 사용하는 경우 require 대신 import를 사용해야 합니다.
.env
TOKEN=xxxxxxx your token xxxxxxxxx



import DiscordJS, { Intents } from "discord.js";
import dotenv from "dotenv";
dotenv.config();

const client = new DiscordJS.Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});

console.log("Starting...");

client.on("ready", () => {
  console.log(`the bot is online!`);
});

client.on("messageCreate", (message) => {
  console.log("messageCreate");
  // get author info
  const authorId = message.author.id;
  const authorName = message.author.username;
  console.log(`author: ${authorName}`);
  if (message.content === "hello") {
    message.reply({content: "world"});
  }
});

client.login(process.env.TOKEN);


4단계 봇 시도



봇을 실행

$ ts-node index.ts
# if you use js
$ node index.js


채널에 무언가를 게시하십시오. hello를 게시하면 봇이 world 라고 답장합니다. 동시에 터미널에서 계정 이름과 계정 ID를 볼 수 있습니다.

좋은 웹페이지 즐겨찾기