Last active
September 10, 2023 12:29
-
-
Save Waipy252/ceb3d4f7bbbb88332cdeff34261a0415 to your computer and use it in GitHub Desktop.
ChatGPTを使ったDiscordボット
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const OpenAI = require('openai') | |
const API_KEY = 'YOUR_OPENAPI_TOKEN' | |
const openai = new OpenAI({ | |
apiKey: API_KEY | |
}); | |
const getChatResponse = async (text) => { | |
const chatCompletion = await openai.chat.completions.create({ | |
model: "gpt-3.5-turbo", | |
messages: [{"role": "user", "content": text}], | |
}); | |
return chatCompletion.choices[0].message; | |
} | |
module.exports = getChatResponse; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Client, GatewayIntentBits } = require('discord.js'); | |
const getChatResponse = require('./api.js'); | |
// ボットのトークン | |
const token = 'YOUR_DISCORD_BOT_TOKEN'; | |
// ボットを作成 | |
const client = new Client({ | |
intents: [ | |
GatewayIntentBits.Guilds, | |
GatewayIntentBits.GuildMessages, | |
] | |
}); | |
// ボットが準備完了時に実行されるイベント | |
client.once('ready', () => { | |
console.log(`Logged in as ${client.user.tag}`); | |
}); | |
// メッセージを受信した際に実行されるイベント | |
client.on('messageCreate', async (message) => { | |
// ボット自身のメッセージには反応しないようにする | |
if (message.author.bot) return; | |
// メッセージのコンテンツを取得 | |
const content = message.content; | |
console.log(content) | |
// 特定のキーワードに反応する例 | |
if(content.includes('/url')){ | |
const trimContent = content.replace(/.* \/url/g, ''); | |
const instruction = '以下の記事タイトルからURLを作成してください 例)ITパスポート取得への道 URL: /guide-for-it-passport ---' + trimContent | |
console.log(instruction) | |
message.reply(await getChatResponse(instruction)); | |
} | |
}); | |
// ボットをログイン | |
client.login(token); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment