Use Cases

Discord Bot dengan Claude Code

Pelajari tentang discord bot menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

Discord Botpengembangan dengan Claude Code: efisiensi

Discord Bot コミュニティ運営、ゲームservermanajemen、notifikasidistribusi dll.幅広い用途 pemanfaatanされてい.discord.jslibrary 使えばTypeScript 快適 pengembangan きます 、インタラクションpemrosesanやパーミッションmanajemen 多く implementasi diperlukan.Claude Code pemanfaatan 、高機能なDiscord Bot efisien pembangunanし.

Setup Proyek

> Discord Bot proyek buatkan.
> discord.js v14、TypeScript、commandhandler構成 dengan 。
npm init -y
npm install discord.js
npm install -D typescript @types/node tsx
// src/index.ts
import { Client, GatewayIntentBits, Collection, Events } from 'discord.js';
import { registerCommands } from './commands';

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

client.commands = new Collection();

client.once(Events.ClientReady, (c) => {
  console.log(`Logged in as ${c.user.tag}`);
});

// commandhandler
client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;

  const command = client.commands.get(interaction.commandName);
  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    const reply = {
      content: 'command 実行中 error 発生しま。',
      ephemeral: true,
    };
    if (interaction.replied || interaction.deferred) {
      await interaction.followUp(reply);
    } else {
      await interaction.reply(reply);
    }
  }
});

registerCommands(client);
client.login(process.env.DISCORD_TOKEN);

Implementasi Slash Command

> /poll command dengan 投票機能 implementasikan.
> tombol dengan 投票 dengan きるよう.
// src/commands/poll.ts
import {
  SlashCommandBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  EmbedBuilder,
  ChatInputCommandInteraction,
  ButtonInteraction,
} from 'discord.js';

const polls = new Map<string, { question: string; votes: Map<string, Set<string>> }>();

export const data = new SlashCommandBuilder()
  .setName('poll')
  .setDescription('投票 pembuatanします')
  .addStringOption((opt) =>
    opt.setName('question').setDescription('質問').setRequired(true)
  )
  .addStringOption((opt) =>
    opt.setName('option1').setDescription('選択肢1').setRequired(true)
  )
  .addStringOption((opt) =>
    opt.setName('option2').setDescription('選択肢2').setRequired(true)
  )
  .addStringOption((opt) =>
    opt.setName('option3').setDescription('選択肢3').setRequired(false)
  );

export async function execute(interaction: ChatInputCommandInteraction) {
  const question = interaction.options.getString('question', true);
  const options = [
    interaction.options.getString('option1', true),
    interaction.options.getString('option2', true),
    interaction.options.getString('option3'),
  ].filter(Boolean) as string[];

  const pollId = `poll-${Date.now()}`;
  const votes = new Map<string, Set<string>>();
  options.forEach((opt) => votes.set(opt, new Set()));
  polls.set(pollId, { question, votes });

  const embed = new EmbedBuilder()
    .setTitle('📊 ' + question)
    .setColor(0x6366f1)
    .setDescription(
      options.map((opt) => `**${opt}**: 0票`).join('\n')
    )
    .setFooter({ text: `Poll ID: ${pollId}` });

  const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
    ...options.map((opt, i) =>
      new ButtonBuilder()
        .setCustomId(`${pollId}:${opt}`)
        .setLabel(opt)
        .setStyle(ButtonStyle.Primary)
    )
  );

  await interaction.reply({ embeds: [embed], components: [row] });
}

// tombolhandler
export async function handlePollButton(interaction: ButtonInteraction) {
  const [pollId, option] = interaction.customId.split(':');
  const poll = polls.get(pollId);
  if (!poll) return;

  const userId = interaction.user.id;

  // 既存 投票 penghapusan
  for (const voters of poll.votes.values()) {
    voters.delete(userId);
  }

  // 新しい投票 penambahan
  poll.votes.get(option)?.add(userId);

  const description = Array.from(poll.votes.entries())
    .map(([opt, voters]) => {
      const count = voters.size;
      const bar = '█'.repeat(count) || '░';
      return `**${opt}**: ${count}票 ${bar}`;
    })
    .join('\n');

  const embed = new EmbedBuilder()
    .setTitle('📊 ' + poll.question)
    .setColor(0x6366f1)
    .setDescription(description)
    .setFooter({ text: `Poll ID: ${pollId}` });

  await interaction.update({ embeds: [embed] });
}

Embedpesan

> server情報 tampilanするcommand buatkan.
> リッチなEmbed形式 dengan tampilanして。
// src/commands/serverinfo.ts
import {
  SlashCommandBuilder,
  EmbedBuilder,
  ChatInputCommandInteraction,
} from 'discord.js';

export const data = new SlashCommandBuilder()
  .setName('serverinfo')
  .setDescription('server情報 tampilanします');

export async function execute(interaction: ChatInputCommandInteraction) {
  const guild = interaction.guild;
  if (!guild) return;

  const embed = new EmbedBuilder()
    .setTitle(guild.name)
    .setThumbnail(guild.iconURL() || '')
    .setColor(0x6366f1)
    .addFields(
      { name: 'メンバー数', value: `${guild.memberCount}人`, inline: true },
      { name: 'チャンネル数', value: `${guild.channels.cache.size}`, inline: true },
      { name: 'ロール数', value: `${guild.roles.cache.size}`, inline: true },
      { name: 'pembuatan日', value: guild.createdAt.toLocaleDateString('ja-JP'), inline: true },
      { name: 'ブースト', value: `Lv.${guild.premiumTier} (${guild.premiumSubscriptionCount}回)`, inline: true },
    )
    .setTimestamp();

  await interaction.reply({ embeds: [embed] });
}

registrasi command

// src/commands/index.ts
import { REST, Routes, Client } from 'discord.js';
import * as poll from './poll';
import * as serverinfo from './serverinfo';

const commands = [poll, serverinfo];

export function registerCommands(client: Client) {
  for (const command of commands) {
    client.commands.set(command.data.name, command);
  }
}

// スラッシュcommand Discord registrasi
export async function deployCommands() {
  const rest = new REST().setToken(process.env.DISCORD_TOKEN!);
  const body = commands.map((c) => c.data.toJSON());

  await rest.put(
    Routes.applicationCommands(process.env.DISCORD_CLIENT_ID!),
    { body }
  );
  console.log('Commands deployed');
}

Ringkasan

discord.js dan Claude Code 組み合わせれば、インタラクティブなDiscord Bot efisien pembangunan bisa dilakukan.チャットボットpengembanganpanduanAPIpengembangan dasar juga bisa dijadikan referensi.

Untuk discord.jsの詳細, lihat discord.js公式ガイド.

#Claude Code #Discord Bot #discord.js #chatbot #コミュニティ
Gratis

PDF Gratis: Cheatsheet Claude Code dalam 5 Menit

Cukup masukkan emailmu dan kami akan langsung mengirim cheatsheet PDF A4 satu halaman.

Kami menjaga data pribadimu dengan aman dan tidak pernah mengirim spam.

Masa

Tentang Penulis

Masa

Engineer yang aktif menggunakan Claude Code. Mengelola claudecode-lab.com, media teknologi 10 bahasa dengan lebih dari 2.000 halaman.