0
0
Lập trình
Sơn Tùng Lê
Sơn Tùng Lê103931498422911686980

Hướng Dẫn Tạo Bot Chat Discord Mới Với ES6, Discord.js, Bun và Tích Hợp ChatGPT

Đăng vào 1 tháng trước

• 4 phút đọc

Hướng Dẫn Tạo Bot Chat Discord Hiện Đại

Bài viết này sẽ hướng dẫn bạn cách tạo một chatbot trên Discord hiện đại bằng cách sử dụng ES6, thư viện Discord.js, Bun và tích hợp khả năng của ChatGPT để tạo ra các phản hồi thông minh.

Bước 1: Thiết Lập Dự Án

Đầu tiên, hãy bắt đầu với việc thiết lập cấu trúc thư mục cho dự án của bạn. Dưới đây là cấu trúc cơ bản:

Copy
project-root/
├── src/
│   ├── commands/
│   │   ├── ping.js
│   │   └── ask.js
│   ├── utils/
│   │   └── openai.js
│   ├── config.js
│   └── index.js
├── package.json
├── docker-compose.yaml
└── Dockerfile

Tạo Ứng Dụng Discord

Trước tiên, bạn cần tạo một ứng dụng Discord mới trên Discord Developer Portal. Sau đó, hãy thiết lập bot của bạn và kích hoạt các intent cần thiết trong phần cài đặt.

Bước 2: Triển Khai Bot Với ES6 Modules

Chúng ta sẽ sử dụng các module ES6 để triển khai bot. Dưới đây là nội dung của các file mà bạn cần tạo:

1. src/config.js

javascript Copy
export const DISCORD_BOT_TOKEN = process.env.DISCORD_BOT_TOKEN;
export const CLIENT_ID = process.env.CLIENT_ID;
export const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

2. src/utils/openai.js

javascript Copy
import { Configuration, OpenAI } from "openai";
import { OPENAI_API_KEY } from '../config.js';

const configuration = new Configuration({
  apiKey: OPENAI_API_KEY,
});

export const openai = new OpenAI(configuration);

export async function askChatGPT(question) {
  try {
    const response = await openai.createCompletion({
      model: "text-davinci-002",
      prompt: question,
      max_tokens: 150
    });
    return response.data.choices[0].text.trim();
  } catch (error) {
    console.error('Error asking ChatGPT:', error);
    throw error;
  }
}

3. src/commands/ping.js

javascript Copy
export const data = {
  name: 'ping',
  description: 'Replies with Pong!'
};

export async function execute(interaction) {
  await interaction.reply('Pong!');
}

4. src/commands/ask.js

javascript Copy
import { askChatGPT } from '../utils/openai.js';

export const data = {
  name: 'ask',
  description: 'Ask ChatGPT a question',
  options: [{
    name: 'question',
    type: 3,
    description: 'Your question',
    required: true
  }]
};

export async function execute(interaction) {
  const question = interaction.options.getString('question');
  await interaction.deferReply();
  try {
    const answer = await askChatGPT(question);
    await interaction.editReply(`Q: ${question}\nA: ${answer}`);
  } catch (error) {
    console.error(error);
    await interaction.editReply('Xin lỗi, đã xảy ra lỗi khi xử lý yêu cầu của bạn.');
  }
}

5. src/index.js

javascript Copy
import { Client, GatewayIntentBits, REST, Routes } from 'discord.js';
import { DISCORD_BOT_TOKEN, CLIENT_ID } from './config.js';
import * as pingCommand from './commands/ping.js';
import * as askCommand from './commands/ask.js';

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

const commands = [
  pingCommand.data,
  askCommand.data
];

const rest = new REST({ version: '10' }).setToken(DISCORD_BOT_TOKEN);

async function main() {
  try {
    console.log('Đang làm mới các lệnh ứng dụng (/)...');
    await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
    console.log('Đã làm mới thành công các lệnh ứng dụng (/)');

    client.on('ready', () => {
      console.log(`Đăng nhập thành công với ${client.user.tag}!`);
    });

    client.on('interactionCreate', async interaction => {
      if (!interaction.isChatInputCommand()) return;

      if (interaction.commandName === 'ping') {
        await pingCommand.execute(interaction);
      } else if (interaction.commandName === 'ask') {
        await askCommand.execute(interaction);
      }
    });

    await client.login(DISCORD_BOT_TOKEN);
  } catch (error) {
    console.error(error);
  }
}

main();

Bước 3: Cập Nhật package.json

Để sử dụng ES6 modules, bạn cần cập nhật file package.json:

json Copy
{
  "type": "module",
  "dependencies": {
    "discord.js": "^14.0.0",
    "openai": "^3.0.0"
  }
}

Bước 4: Tạo File docker-compose.yaml

Tạo file docker-compose.yaml với nội dung sau:

yaml Copy
version: '3'
services:
  bot:
    build: .
    environment:
      - DISCORD_BOT_TOKEN=<YOUR_BOT_TOKEN>
      - CLIENT_ID=<YOUR_CLIENT_ID>
      - OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>

Bước 5: Tạo File Dockerfile

Tạo file Dockerfile để cấu hình container cho bot:

Copy
FROM node:latest

WORKDIR /app

COPY package.json .

RUN npm install

COPY . .

CMD ["node", "src/index.js"]

Khởi Động Bot

Chạy lệnh docker compose up để khởi động bot. Sau đó, thêm bot của bạn vào server Discord và thử nghiệm với các lệnh /ask hoặc /ping để tương tác với bot.

Kết Luận

Cấu trúc dự án mà chúng ta đã thiết lập giúp dễ dàng quản lý, mở rộng và bảo trì mã nguồn. Bot hiện tại hỗ trợ lệnh slash cho cả chức năng ping và hỏi ChatGPT. Bạn có thể dễ dàng thêm nhiều lệnh khác bằng cách tạo file mới trong thư mục commands và import chúng trong file index.js.

Nếu bạn muốn tiết kiệm thời gian và bắt đầu nhanh hơn, hãy tham khảo repository mẫu này: https://github.com/mrgoonie/bun-discord-bot. Đây là một nền tảng tuyệt vời để phát triển Discord bot với Bun.

Chúc bạn lập trình vui vẻ và thành công khi xây dựng chatbot Discord của riêng mình!
source: viblo

Gợi ý câu hỏi phỏng vấn
Không có dữ liệu

Không có dữ liệu

Bài viết được đề xuất
Bài viết cùng tác giả

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào