1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ターミナルからDiscord

Last updated at Posted at 2025-12-08

初めに

Discordをターミナルから送受信したい、と思ったので、Discord Botを作った。

Botの作り方

1. 登録

  1. Discord Developer Portalにアクセス
  2. New Application → 名前をつけて作成
  3. “Bot” タブから Bot を作成
  4. 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 PortalOAuth2URL Generator

Scopes

  • bot

Permissions(最低限)

  • Send Messages
  • Read Message History
    生成された URL をブラウザで開き、
    追加したいサーバーを選んで承認

実行

node index.js

これで、基礎的な部分は完了
ターミナル上で送受信できるようになった。

終わりに

意外と便利
今後機能も追加したい。
~Thank you for reading~

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?