Claude Code के साथ Discord Bot
Claude Code का उपयोग करके discord bot सीखें। Practical tips और code examples शामिल हैं।
Discord Botdevelopmentको Claude Code से Efficient बनाएं
Discord Botはコミュニティ運営、ゲームservermanagement、通知配信 आदि幅広い用途でutilizationされてい है।discord.jslibraryを使えばTypeScriptで快適にdevelopmentできますが、インタラクションprocessingやパーミッションmanagementには多くのimplementationがज़रूरी है।Claude Code का उपयोग करके、高featuresなDiscord Botをefficientlybuild करें।
Projectのsetup
> Discord BotのProjectをबनाओ。
> discord.js v14、TypeScript、commandhandler構成で。
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);
スラッシュcommandのimplementation
> /poll commandで投票featuresをimplement करो。
> buttonで投票できる तरहして。
// 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('投票 createします')
.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] });
}
// buttonhandler
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;
// 既存の投票 delete
for (const voters of poll.votes.values()) {
voters.delete(userId);
}
// नया投票をadd
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] });
}
Embedmessage
> server情報 displayするcommandを作って。
> リッチなEmbed形式でdisplayして。
// src/commands/serverinfo.ts
import {
SlashCommandBuilder,
EmbedBuilder,
ChatInputCommandInteraction,
} from 'discord.js';
export const data = new SlashCommandBuilder()
.setName('serverinfo')
.setDescription('server情報 displayします');
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: 'channel数', value: `${guild.channels.cache.size}`, inline: true },
{ name: 'ロール数', value: `${guild.roles.cache.size}`, inline: true },
{ name: 'create日', value: guild.createdAt.toLocaleDateString('ja-JP'), inline: true },
{ name: 'ブースト', value: `Lv.${guild.premiumTier} (${guild.premiumSubscriptionCount}回)`, inline: true },
)
.setTimestamp();
await interaction.reply({ embeds: [embed] });
}
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に登録
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');
}
まとめ
discord.jsとClaude Codeを組み合わせれば、インタラクティブなDiscord Botをefficientlybuild किया जा सकता है。チャットボットdevelopmentガイドやAPIdevelopmentの基本भी reference के लिए देखें。
discord.jsके details के लिएdiscord.js公式ガイドをदेखें。
मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट
बस अपना ईमेल दर्ज करें और हम तुरंत A4 एक-पृष्ठ चीटशीट PDF भेज देंगे।
हम आपकी व्यक्तिगत जानकारी की सुरक्षा करते हैं और स्पैम नहीं भेजते।
लेखक के बारे में
Masa
Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।
संबंधित लेख
हर दिन बहुभाषी Claude Code लेख प्रकाशित करने से पहले 7 जांचें
एक व्यावहारिक चेकलिस्ट ताकि आप हर दिन बहुभाषी Claude Code लेख प्रकाशित करते समय कोई भाषा न छोड़ें, CTA न तोड़ें और पुराना पेज लाइव न रहने दें।
Codex Automations क्या है? AI से content ops, analysis और deploy करवाने का तरीका
Codex Automations से analytics, article planning, CTA सुधार, deploy और monetization workflow चलाने की practical guide.
Claude Code × GCP Cloud Functions संपूर्ण गाइड | सर्वरलेस फंक्शन तेज़ी से विकसित करें
Claude Code से GCP Cloud Functions को ऑप्टिमाइज़ करें। HTTP/Pub/Sub/Firestore ट्रिगर, लोकल टेस्टिंग और डिप्लॉयमेंट ऑटोमेशन — Masa के व्यावहारिक अनुभव से रियल कोड उदाहरणों के साथ।