初めに
Discordをターミナルから送受信したい、と思ったので、Discord Botを作った。
Botの作り方
1. 登録
- Discord Developer Portalにアクセス
- New Application → 名前をつけて作成
- “Bot” タブから Bot を作成
- Token をコピーしておく
Token は公開しないように
2. Node.js で作成
mkdir discord-cli-bot
cd discord-cli-bot
npm init -y
npm install discord.js
3..env/config.jsonを作成
{
"clientId": "OAuth2にあるClient IDをコピペ",
"token": "botのtokenをコピペ",
"guildId": "botを追加したサーバーのIDをコピペ"
}
4. コード
index.jsにいかを貼り付け。
const { token } = require('./.env/config.json');
require("dotenv").config();
const { Client, GatewayIntentBits } = require("discord.js");
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
let lastMessage = null;
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on("messageCreate", msg => {
const name = msg.author.username;
console.log(`\x1b[32m${name}\x1b[0m: ${msg.content}`);
lastMessage = msg;
});
rl.on("line", input => {
if (input.trim() === "exit") {
console.log("Shutting down bot...");
client.destroy();
process.exit(0);
}
if (lastMessage) {
lastMessage.channel.send(input);
}
});
client.login(token);
このプログラムだと、今日のログを表示、その後入力を受け取るようになる。
使ってみる
Developer Portal →OAuth2 → URL Generator
Scopes
- bot
Permissions(最低限)
- Send Messages
- Read Message History
生成された URL をブラウザで開き、
追加したいサーバーを選んで承認
実行
node index.js
これで、基礎的な部分は完了
ターミナル上で送受信できるようになった。
終わりに
意外と便利
今後機能も追加したい。
~Thank you for reading~