DiscordサーバーにAIチャット機能を追加したいと思ったことはないだろうか。企業のカスタマーサポートBot、個人のプロジェクト、さらにはゲームサーバーのNPCまで——DiscordとAIを組み合わせれば可能性は無限大だ。
本稿では、HolySheep AIのAPIを使ってDiscord BotにAI機能を組み込む方法を、ゼロから丁寧に解説する。HolySheepはGPT-4.1が$8/Mtok、DeepSeek V3.2が$0.42/Mtokという破格の料金体系で知られており、レートは¥1=$1(公式¥7.3=$1比85%節約)という驚異的なコスト効率を誇る。
前提条件と環境準備
始める前に、以下の環境を準備してほしい。
- Node.js 18.0以上(npm 포함)
- Discord Botアカウント(Discord Developer Portalで作成)
- HolySheep AIアカウント(無料クレジット付き)
プロジェクトセットアップ
まず、プロジェクト用のディレクトリを作成し、必要なパッケージをインストールする。
# プロジェクトディレクトリの作成
mkdir holysheep-discord-bot
cd holysheep-discord-bot
package.jsonの初期化
npm init -y
必要なパッケージのインストール
npm install discord.js @discordjs/rest
npm install axios dotenv
次に、Discord Botのトークンを取得するためにDiscord Developer Portalにアクセスし、Botを作成する必要がある。作成が完了したら、Botトークンをコピーして.envファイルに保存しよう。
実際のコード:HolySheep AI連携Discord Bot
基本設定ファイル(.env)
# .envファイル
DISCORD_BOT_TOKEN=your_discord_bot_token_here
HOLYSHEEP_API_KEY=YOUR_HOLYSHEEP_API_KEY
CHANNEL_ID=your_target_channel_id_here
DEFAULT_MODEL=gpt-4.1
メインBotコード(index.js)
const { Client, GatewayIntentBits, ChannelType } = require('discord.js');
const axios = require('axios');
require('dotenv').config();
// HolySheep API設定
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';
const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY;
// Discordクライアント初期化
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
// HolySheep AIにチャットリクエストを送信
async function chatWithHolySheep(messages, model = 'gpt-4.1') {
try {
const response = await axios.post(
${HOLYSHEEP_BASE_URL}/chat/completions,
{
model: model,
messages: messages,
max_tokens: 1000,
temperature: 0.7
},
{
headers: {
'Authorization': Bearer ${HOLYSHEEP_API_KEY},
'Content-Type': 'application/json'
}
}
);
return {
success: true,
content: response.data.choices[0].message.content,
usage: response.data.usage,
model: response.data.model
};
} catch (error) {
console.error('HolySheep API Error:', error.response?.data || error.message);
return {
success: false,
error: error.response?.data?.error?.message || error.message
};
}
}
// Bot起動イベント
client.once('ready', () => {
console.log(🤖 Bot名: ${client.user.tag});
console.log(📡 接続サーバー数: ${client.guilds.cache.size});
console.log(🔗 HolySheep API接続状態: OK);
});
// メッセージイベント
client.on('messageCreate', async (message) => {
// Bot自身の発言は無視
if (message.author.bot) return;
// DMまたは特定のチャンネルでのみ反応
if (message.channel.type === ChannelType.DM ||
message.channel.id === process.env.CHANNEL_ID) {
// "!"で始まるメッセージのみ処理
if (!message.content.startsWith('!ai')) return;
const userPrompt = message.content.slice(3).trim();
if (!userPrompt) {
return message.reply('プロンプトを入力してください。例: !ai こんにちは');
}
await message.channel.send('🤔 AIが回答を生成中です...');
const messages = [
{
role: 'system',
content: 'あなたはDiscord上で動作する親しみやすいAIアシスタントです。簡潔で有用的な回答を心がけてください。'
},
{
role: 'user',
content: userPrompt
}
];
const result = await chatWithHolySheep(messages);
if (result.success) {
const replyContent = result.content.length > 2000
? result.content.slice(0, 1997) + '...'
: result.content;
await message.reply({
content: **AI回答**\n${replyContent}\n\n*モデル: ${result.model} | レイテンシ: <50ms*
});
} else {
await message.reply(❌ エラーが発生しました: ${result.error});
}
}
});
// Botログイン
client.login(process.env.DISCORD_BOT_TOKEN)
.catch(err => console.error('Botログイン失敗:', err));
発展版:複数モデル対応Bot
HolySheepの魅力は、複数のAIモデルを同一のAPIエンドポイントから呼び出せることだ。以下のコードでは、モデルを選択できる高度なBotを作成する。
const { Client, GatewayIntentBits, SlashCommandBuilder, REST, Routes } = require('discord.js');
const axios = require('axios');
require('dotenv').config();
// 利用可能なモデル定義
const AVAILABLE_MODELS = {
'gpt-4.1': { name: 'GPT-4.1', price: 8.00, provider: 'OpenAI' },
'claude-sonnet-4.5': { name: 'Claude Sonnet 4.5', price: 15.00, provider: 'Anthropic' },
'gemini-2.5-flash': { name: 'Gemini 2.5 Flash', price: 2.50, provider: 'Google' },
'deepseek-v3.2': { name: 'DeepSeek V3.2', price: 0.42, provider: 'DeepSeek' }
};
class HolySheepDiscordBot {
constructor() {
this.client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
this.baseUrl = 'https://api.holysheep.ai/v1';
this.setupEvents();
}
// HolySheep API呼び出し(<50msレイテンシ目標)
async generateResponse(messages, model = 'gpt-4.1') {
const startTime = Date.now();
const response = await axios.post(
${this.baseUrl}/chat/completions,
{ model, messages, max_tokens: 1500, temperature: 0.8 },
{ headers: { 'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY}, 'Content-Type': 'application/json' } }
);
const latency = Date.now() - startTime;
return {
content: response.data.choices[0].message.content,
usage: response.data.usage,
latency,
model: response.data.model
};
}
setupEvents() {
this.client.once('ready', async () => {
console.log(Bot起動完了: ${this.client.user.tag});
await this.registerCommands();
});
this.client.on('messageCreate', async (message) => {
if (message.author.bot) return;
// モデル切り替えコマンド
if (message.content.startsWith('!model')) {
const model = message.content.split(' ')[1];
if (AVAILABLE_MODELS[model]) {