LoginSignup
1
2

More than 1 year has passed since last update.

discord.js v14を使用した簡単な応答botの作り方

Last updated at Posted at 2022-08-18

discord.js v14を使用した簡単な応答botの作り方

はじめに

どうもはじめまして、だらけ(darakeee)です。
今回はdiscord.js v14を使用して簡易的な返答Botを作っていこうと思います。

こちらは、JavaScript と discord.js を利用した Discord Bot 開発のチュートリアル記事を想定して書いております。

もし説明が間違っていたり、分かりづらかったら教えてください。

DeveloperPortalで必要な操作は別の記事を書いたので、こちらをご覧ください。

動作環境

  • npm 8.14.0
  • node.js 18.4.0
  • discord.js 14.1.2
  • dotenv 16.0.1

※discord.jsは。node.js「16.9.0」以前は対応していないので注意。

ファイル構成

discordBot/
 ├ node_module/
 ├ src/
 │  └ index.js
 ├ .env
 ├ package-lock.json
 └ package.json

手順&各種コマンド

  1. package.jsonの作成

    npm init
    
  2. discord.js、dotenvのインストール

    npm install discord.js dotenv
    
    • discord.js→今回使うnode.jsのモジュール。
    • dotenv→.envファイルを読み込めるようになるモジュール。
      .envに記述されたキーをprocess.env経由で参照できます。
  3. srcフォルダ、index.js、.envの作成
    上のファイル構成通りに作成してください。
    コードは下のものをお使いください。

  4. 完成!

  5. botを起動

    node src/index.js
    

※node [起動したいjsの場所]で起動できます。

コード(サンプル)

index.js

src/index.js
//dotenvの適用
require('dotenv').config();
//.envからtokenの呼び出し
const {token} = process.env;

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
	intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages]
});

//起動確認
client.once('ready', () => {
    console.log(`${client.user.tag} Ready`);
});

//返答
client.on('messageCreate', message => {
    if (message.author.bot) {
        return;
    }

    if (message.content == 'hi') {
        message.channel.send('hi!');
    }
});

//Discordへの接続
client.login(token);

※「hi」とチャットに書くと、「hi!」と返ってくるようになってます。

.env

.env
token=ここに自分のトークンをペースト

※「ここに自分のトークンをペースト」を消して、トークンをペースト。

あとがき

ここまで見てくださり、ありがとうございます。
今回はdiscord.js v14でのBotの作り方をまとめてみました。
基礎的な部分しか今回は記載していないため、もし興味を持たれた方はぜひ公式サイトをチェックしてみてください!

1
2
1

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
1
2