4
1

More than 3 years have passed since last update.

Discord.jsを拡張しよう!

Last updated at Posted at 2019-09-22

Discord.js (v12)Structuresクラスの紹介をしたいと思います。

注意

これから紹介する機能は、v13.0.0で削除されました。

  • Discord.jsのバージョンは11.5.1ではなく12.0.0-dev
  • 開発途中のバージョンで更新が活発(大きな変更には注意しよう)
  • Node.jsのバージョンは10.0.0以上であること(安定版は6.0.0以上)

インストール

npm
npm install discordjs/discord.js

どうやって拡張するの?

ドキュメントの例を見ればすぐに分かると思います。

const { Structures } = require('discord.js');

Structures.extend('Guild', Guild => {
  class CoolGuild extends Guild {
    constructor(client, data) {
      super(client, data);
      this.cool = true;
    }
  }

  return CoolGuild;
});

これはGuildオブジェクトにcoolというメンバ変数を追加しています。よって

bot.js
const { Structures, Client } = require('discord.js');

Structures.extend('Guild', Guild => {
  class CoolGuild extends Guild {
    constructor(client, data) {
      super(client, data);
      this.cool = true;
    }
  }

  return CoolGuild;
});

const client = new Client();

client.on('message', (message) => {
  if (message.guild.cool) console.log('このサーバーはクール!')
})

こんなことができるようになる。

拡張するときの注意

Clientのインスタンスを作る前に拡張しなければならない

ドキュメントにも書いてありますが、Clientのインスタンスを作る前に拡張しなければなりません。

参考

あとがき

サンプルコードが雑すぎて凄さが伝わらないような気もするけど()
ちなみに他のオブジェクトも拡張できるよ!これを使っているフレームワークのklasaとか結構参考になると思う。

TypeScript使ってる場合は型定義を書く必要がある。

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