ในบทความนี้ผมจะแบ่งปันประสบการณ์ตรงในการสร้าง Discord Bot ที่ใช้ AI สำหรับการสนทนาหลายรอบ (Multi-Turn) และการเรียกใช้ฟังก์ชัน (Tool Calling) ตั้งแต่เริ่มต้นจนใช้งานจริง พร้อมแนะนำวิธีประหยัดค่าใช้จ่ายได้มากถึง 85% ผ่าน สมัครที่นี่
ทำไมต้องสร้าง Discord Bot ด้วย AI?
จากประสบการณ์ของผม การนำ AI มาใช้กับ Discord ช่วยให้:
- ตอบคำถามลูกน้องในคอมมูนิตี้แบบอัตโนมัติ 24/7
- สร้างระบบ Chatbot ที่จำบทสนทนาก่อนหน้าได้ (Multi-Turn)
- เรียกใช้คำสั่งภายนอกได้ เช่น ค้นหาข้อมูล ดึงราคาหุ้น หรือตรวจสอบสถานะเซิร์ฟเวอร์
เปรียบเทียบค่าใช้จ่าย AI API 2026
ก่อนเริ่มต้น มาดูค่าใช้จ่ายของแต่ละเจ้ากัน:
| โมเดล | Output (USD/MTok) | 10M tokens/เดือน |
|---|---|---|
| GPT-4.1 | $8.00 | $80 |
| Claude Sonnet 4.5 | $15.00 | $150 |
| Gemini 2.5 Flash | $2.50 | $25 |
| DeepSeek V3.2 | $0.42 | $4.20 |
สรุป: หากใช้ DeepSeek V3.2 ผ่าน HolySheep จะประหยัดได้ถึง 95% เมื่อเทียบกับ Claude และมีความเร็วตอบสนองต่ำกว่า 50ms
เริ่มต้นสร้างโปรเจกต์
ติดตั้ง Dependencies
npm install discord.js openai dotenv
สำหรับ Python:
pip install discord.py openai python-dotenv
โค้ด Python: Discord Bot + Multi-Turn Conversation
import discord
import openai
import os
from dotenv import load_dotenv
load_dotenv()
ตั้งค่า HolySheep API
openai.api_key = os.getenv("YOUR_HOLYSHEEP_API_KEY")
openai.api_base = "https://api.holysheep.ai/v1"
สร้าง Discord Client
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
เก็บประวัติการสนทนาต่อผู้ใช้
conversation_histories = {}
@client.event
async def on_ready():
print(f"Bot พร้อมใช้งาน: {client.user}")
@client.event
async def on_message(message):
if message.author == client.user:
return
# ตรวจสอบ prefix ของบอท
if not message.content.startswith("!ai "):
return
user_id = str(message.author.id)
user_input = message.content[4:] # ตัด prefix
# สร้าง history สำหรับผู้ใช้ใหม่
if user_id not in conversation_histories:
conversation_histories[user_id] = []
# เพิ่มข้อความผู้ใช้เข้า history
conversation_histories[user_id].append({
"role": "user",
"content": user_input
})
async with message.channel.typing():
try:
response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=conversation_histories[user_id],
max_tokens=1000,
temperature=0.7
)
bot_reply = response.choices[0].message["content"]
# เพิ่ม response เข้า history เพื่อจดจำบทสนทนา
conversation_histories[user_id].append({
"role": "assistant",
"content": bot_reply
})
await message.reply(bot_reply)
except Exception as e:
await message.reply(f"เกิดข้อผิดพลาด: {str(e)}")
client.run(os.getenv("DISCORD_BOT_TOKEN"))
โค้ด Python: Tool Calling สำหรับค้นหาข้อมูล
import openai
import json
import random
from datetime import datetime
ตั้งค่า HolySheep API
openai.api_key = "YOUR_HOLYSHEEP_API_KEY"
openai.api_base = "https://api.holysheep.ai/v1"
กำหนด tools ที่บอทสามารถเรียกใช้ได้
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "ดึงข้อมูลอากาศของเมืองที่ระบุ",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "ชื่อเมืองที่ต้องการดูอากาศ"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "get_server_status",
"description": "ตรวจสอบสถานะเซิร์ฟเวอร์",
"parameters": {
"type": "object",
"properties": {
"server_id": {
"type": "string",
"description": "ID ของเซิร์ฟเวอร์ที่ต้องการตรวจสอบ"
}
},
"required": ["server_id"]
}
}
}
]
def get_weather(city):
"""ฟังก์ชันจำลองดึงข้อมูลอากาศ"""
conditions = ["แดดจัด", "มีเมฆ", "ฝนตก", "พายุ", "หิมะตก"]
return {
"city": city,
"temperature": random.randint(15, 35),
"condition": random.choice(conditions),
"humidity": random.randint(40, 90),
"timestamp": datetime.now().isoformat()
}
def get_server_status(server_id):
"""ฟังก์ชันจำลองตรวจสอบสถานะเซิร์ฟเวอร์"""
statuses = ["online", "offline", "maintenance"]
return {
"server_id": server_id,
"status": random.choice(statuses),
"players_online": random.randint(0, 100),
"uptime_percentage": random.uniform(95, 99.9)
}
def execute_tool(tool_name, arguments):
"""เรียกใช้ฟังก์ชันตามชื่อที่กำหนด"""
if tool_name == "get_weather":
return get_weather(**arguments)
elif tool_name == "get_server_status":
return get_server_status(**arguments)
return None
def chat_with_tools(user_message, conversation_history):
"""ส่งข้อความพร้อม tools ไปยัง AI"""
messages = conversation_history + [{"role": "user", "content": user_message}]
response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
# ตรวจสอบว่า AI ต้องการเรียกใช้ tool หรือไม่
if response_message.get("tool_calls"):
tool_results = []
for tool_call in response_message["tool_calls"]:
tool_name = tool_call["function"]["name"]
arguments = json.loads(tool_call["function"]["arguments"])
print(f"AI เรียกใช้ tool: {tool_name} พร้อม arguments: {arguments}")
result = execute_tool(tool_name, arguments)
tool_results.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": json.dumps(result)
})
# ส่งผลลัพธ์กลับไปให้ AI ประมวลผล
messages.append(response_message)
messages.extend(tool_results)
final_response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=messages
)
return final_response.choices[0].message["content"]
return response_message["content"]
ทดสอบการทำงาน
if __name__ == "__main__":
history = []
# ทดสอบการถามเรื่องอากาศ
response1 = chat_with_tools("อากาศที่กรุงเทพเป็นอย่างไร?", history)
print(f"User: อากาศที่กรุงเทพเป็นอย่างไร?")
print(f"Bot: {response1}\n")
เชื่อมต่อ Tool Calling กับ Discord Bot
import discord
import openai
import json
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("YOUR_HOLYSHEEP_API_KEY")
openai.api_base = "https://api.holysheep.ai/v1"
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
เก็บประวัติการสนทนาต่อผู้ใช้
user_conversations = {}
tools = [
{
"type": "function",
"function": {
"name": "search_wikipedia",
"description": "ค้นหาข้อมูลจาก Wikipedia",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "คำค้นหา"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "คำนวณทางคณิตศาสตร์",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "นิพจน์ทางคณิตศาสตร์ เช่น 2+2*3"}
},
"required": ["expression"]
}
}
}
]
def search_wikipedia(query):
# จำลองการค้นหา Wikipedia
return {
"query": query,
"result": f"ข้อมูลเกี่ยวกับ {query} จาก Wikipedia...",
"url": f"https://th.wikipedia.org/wiki/{query}"
}
def calculate(expression):
try:
result = eval(expression)
return {"expression": expression, "result": result}
except:
return {"error": "ไม่สามารถคำนวณได้"}
def execute_function(name, args):
if name == "search_wikipedia":
return search_wikipedia(args["query"])
elif name == "calculate":
return calculate(args["expression"])
return None
@client.event
async def on_ready():
print(f"Bot พร้อม: {client.user}")
@client.event
async def on_message(message):
if message.author == client.user or not message.content.startswith("!ask "):
return
user_id = str(message.author.id)
question = message.content[5:]
if user_id not in user_conversations:
user_conversations[user_id] = []
async with message.channel.typing():
try:
# เตรียม messages
messages = user_conversations[user_id] + [{"role": "user", "content": question}]
# เรียก API พร้อม tools
response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
# หาก AI ต้องการเรียกใช้ tool
if response_message.get("tool_calls"):
tool_results = []
for tool_call in response_message["tool_calls"]:
func_name = tool_call["function"]["name"]
func_args = json.loads(tool_call["function"]["arguments"])
result = execute_function(func_name, func_args)
tool_results.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": json.dumps(result)
})
# ส่งผลลัพธ์กลับให้ AI ประมวลผล
messages.append(response_message)
messages.extend(tool_results)
final_response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=messages
)
answer = final_response.choices[0].message["content"]
else:
answer = response_message["content"]
# บันทึกประวัติ
user_conversations[user_id].append({"role": "user", "content": question})
user_conversations[user_id].append({"role": "assistant", "content": answer})
# จำกัดประวัติไว้ 10 ข้อความล่าสุด
if len(user_conversations[user_id]) > 20:
user_conversations[user_id] = user_conversations[user_id][-20:]
await message.reply(answer)
except Exception as e:
await message.reply(f"❌ เกิดข้อผิดพลาด: {str(e)}")
client.run(os.getenv("DISCORD_BOT_TOKEN"))
ข้อผิดพลาดที่พบบ่อยและวิธีแก้ไข
กรณีที่ 1: Error 401 Unauthorized
# ❌ ผิด - ใช้ API URL ของ OpenAI โดยตรง
openai.api_base = "https://api.openai.com/v1"
✅ ถูก - ใช้ HolySheep API Gateway
openai.api_base = "https://api.holysheep.ai/v1"
openai.api_key = "YOUR_HOLYSHEEP_API_KEY"
สาเหตุ: API Key ไม่ถูกต้องหรือใช้ URL ผิด
วิธีแก้: ตรวจสอบว่าใช้ https://api.holysheep.ai/v1 และ API Key ที่ได้จากการสมัคร
กรณีที่ 2: Rate Limit Error 429
import time
from functools import wraps
def rate_limit(max_calls=60, period=60):
"""Decorator สำหรับจำกัดจำนวนคำขอ"""
calls = []
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
now = time.time()
calls[:] = [t for t in calls if now - t < period]
if len(calls) >= max_calls:
wait_time = period - (now - calls[0])
await asyncio.sleep(wait_time)
calls.pop(0)
calls.append(time.time())
return await func(*args, **kwargs)
return wrapper
return decorator
@rate_limit(max_calls=30, period=60)
async def call_ai_api(messages):
response = openai.ChatCompletion.create(
model="gpt-4.1",
messages=messages
)
return response
สาเหตุ: ส่งคำขอมากเกินจำนวนที่กำหนดต่อนาที
วิธีแก้: ใช้ rate limiting หรืออัพเกรดเป็นแพลนที่มีโควต้าสูงขึ้น
กรณีที่ 3: Context Overflow หรือ Token Limit
import tiktoken
def count_tokens(text, model="gpt-4"):
"""นับ
แหล่งข้อมูลที่เกี่ยวข้อง