3
1

More than 3 years have passed since last update.

discord.jsでDiscord Botを作ってみた

Last updated at Posted at 2019-12-04

概要

discord.jsでbotを作ったので、それを書き留めときます。
インストールは、Ubuntu mateを想定したものを紹介致します。
他のOSを使っている方に関しては、調べてください

Node.js&npmのインストール方法

コマンドラインを開き下のコマンドを実行します。

sudo apt install -y nodejs npm

Windowsの場合
Node.jsの公式サイトへ行きインストーラをダウンロードします。

discord.jsのインストール方法

こちらもコマンドラインを開き下のコマンドを実行します。

Ubuntu
sudo npm i discord.js
Windows
npm i discord.js

実際に書いていく

まずは、discord.jsを読み込むコードを書きます。

index.js
 const discord = require("discord.js");
 const client = new discord.Client;

簡単な返事機能のコードを書きます。
ユーザーがこんにちはと送信した場合に、メンション付きで返事をします。
messageイベントにはmessageプロパティが含まれているので、
messageの内容、つまりmessage.contentがこんにちはだった場合の処理を書いてあげれば、返事をしてくれます。

index.js
//続き
client.on("message", message => {
  if (message.author.bot || !message.guild) return
  if (message.content === "こんにちは"){
    message.reply('さん、こんにちはー');
  }
});
client.login("Botのトークン")

if (message.author.bot || !message.guild) returnでBot自身のメッセージとDMといったGuild以外からのメッセージに反応しないようにしています。

Botのトークンのところには、Discord Developer Portal
にある、自分のBotの右にあるBotへ行きtokenの下にあるcopyを押して、index.jsのBotのトークンのところへ貼り付けます。

実際にBotを起動してみる

Botを起動させるためにはコマンドラインで下のコマンドを実行します。

node index.js

ちゃんとBotがONLINEになっていれば成功です。
色々な種類のコードを書いていく予定ですので、よろしくお願いします。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1