1
0

More than 1 year has passed since last update.

[追記式]Discord.js v13のメモ

Posted at

自分がDiscord.jsを用いた際のメモをただただ残していく

元々はDiscord.py(discord.pyへようこそ)を用いてBOTを組んでいましたが,開発が終了していたり,自分が欲しい機能(ex. Slash Commands)かなかったりと色々あるのでDiscord.jsに移行することを決めました.

余談

今までPythonばかり触れておりnode.js?を触れるのは初めてなのでわからないことばかりです.なので,備忘録的な感じでここに追記しながら書き収めていきたいと思います.記述していくものはコード中心なのでBOTの設定等は省略します.

注意

あくまでも僕自身のやり方なので必ずしも正しい書き方とは限りません.有識者の方いらっしゃいましたらアドバイス等よろしくお願いします!

備忘録

2021/11/10: この記事の始まり

基本的なファイル構成

├── main
    ├── config.json
    ├── deploy-commands.js
    └── index.js

config.json: TOKENなど外部に見せたくないファイルを書いていくファイル
deploy-commands.js
index.js: メインに書いていくファイル

※ Githubを用いる際などはconfig.json.gitignoreに記述する.

config.json

config.json
{
    "clientId": "BOTのクライアントID",
    "guildId": "DiscordサーバーのID",
    "token": "トークン"
}

deploy-commands.js

このファイルでは/(Slash Commands)を登録しています.

deploy-commands.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');

const commands = [
    new SlashCommandBuilder().setName('good').setDescription('Replies with morning!'),
]
    .map(command => command.toJSON());

const rest = new REST({ version: '9' }).setToken(token);

rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
    .then(() => console.log('Successfully registered application commands.'))
    .catch(console.error);

index.js

このファイルではdeploy-commands.jsで登録したSlash Commandsを実行した時の挙動を記述したり,その他の挙動を記述していきます.

index.js
const { Client, Intents, Message, VoiceChannel } = require('discord.js');
const { token } = require('./config.json');

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

client.once('ready', () => {
    console.log('Ready!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'good') {
        await interaction.reply('> morning!');
    }
});

client.login(token);

メッセージが送信されたchannel idを取得して変数定義する

index.js
const ch_id =interaction.channelId;

最後に

タイトルにある通りこの記事は追記式で書いています.

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