Ollama와 AI Discord 봇 만들기
Source: Dev.to
개요
이 튜토리얼에서는 처음부터 AI 기반 Discord 봇을 만드는 방법을 배웁니다. 튜토리얼을 마치면 봇이 다음을 할 수 있게 됩니다:
- AI를 사용해 메시지에 응답하기
- 사용자와 대화하기
사전 경험은 필요 없으며, 파이썬에 대한 기본 지식만 있으면 도움이 됩니다.
배울 내용
- Discord 봇 애플리케이션 만드는 방법
- Ollama(완전 로컬) 설치 및 사용 방법
- 파이썬 코드로 두 시스템을 연결하는 방법
- 봇을 실제 사람처럼 말하게 만드는 방법
- 봇을 24시간 운영하는 방법
준비물
- Python 3.8+ – 프로그래밍 언어
- Discord 계정 – 봇을 만들기 위해 필요
- Ollama – 무료 로컬 AI
- 텍스트 편집기 / IDE – 원하는 도구
Part 1: Discord 봇 설정하기
- Discord 개발자 페이지로 이동합니다.
- New Application을 클릭하고 이름을 입력한 뒤 생성합니다.
- Bot 탭으로 이동해 다음 특권 게이트웨이 인텐트를 활성화합니다:
- Presence Intent
- Server Members Intent
- Message Content Intent
- Reset Token을 클릭하고 토큰을 복사한 뒤 안전하게 보관합니다.
- 봇을 서버에 초대합니다:
- OAuth2 → URL Generator 로 이동
- Scopes:
bot,applications.commands - Permissions:
- Send Messages
- Send Messages in Threads
- Read Message History
- View Channels
- Use Slash Commands
- Add Reactions
- 생성된 URL을 복사하고 서버를 선택한 뒤 봇을 승인합니다.
봇은 실행하기 전까지 서버에서 오프라인 상태로 표시됩니다.
Part 2: Ollama 설치하기
Ollama는 AI 모델을 로컬에서 실행해 무료, 개인, 빠른 추론을 제공합니다.
macOS
brew install ollama
Linux
curl -fsSL https://ollama.ai/install.sh | sh
Windows
Download the installer from .
Ollama 시작하기:
ollama serve
이 터미널을 열어 둡니다; 봇은 여기와 통신합니다.
모델 다운로드
ollama pull llama3.1
llama3.1 모델은 무료이며 오픈소스이고, 대화에 적합합니다.
설치 확인
ollama run llama3.1
프롬프트가 나타나면 입력하고 응답을 확인할 수 있습니다.
Part 3: 파이썬 의존성 설치하기
가상 환경을 만들고 활성화합니다:
python3 -m venv env
source env/bin/activate # Windows에서는 `env\Scripts\activate` 사용
필요한 패키지를 설치합니다:
pip install py-cord requests python-dotenv
- py‑cord – Discord 봇 라이브러리
- requests – Ollama와 통신하기 위한 HTTP 클라이언트
- python‑dotenv – 환경 변수(예: Discord 토큰) 로드
Part 4: 프로젝트 준비하기
-
Discord 토큰을 저장할
.env파일을 생성합니다:vim .env -
다음 줄을 추가합니다(복사한 토큰을
your_token_here대신 입력):DISCORD_TOKEN="your_token_here"
Part 5: 완전한 봇 코드
bot.py 파일을 만들고 아래 코드를 붙여넣습니다.
# ============================================
# IMPORTS
# ============================================
import discord
from discord.ext import commands
import requests
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# ============================================
# CONFIGURATION
# ============================================
TOKEN = os.getenv("DISCORD_TOKEN")
OLLAMA_URL = "http://localhost:11434/api/generate"
OLLAMA_MODEL = "llama3.1"
PREFIX = "!"
# ============================================
# BOT SETUP
# ============================================
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
# ============================================
# HELPER: Talk to Ollama AI
# ============================================
def ask_ai(prompt, temperature=0.9):
"""
Send a prompt to Ollama and get the AI response.
"""
try:
payload = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"temperature": temperature,
"num_predict": 200
}
}
response = requests.post(OLLAMA_URL, json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
return data.get("response", "").strip()
else:
return "Sorry, I had trouble thinking of a response!"
except requests.exceptions.ConnectionError:
return "Error: Ollama is not running! Start it with 'ollama serve'"
except Exception as e:
return f"Error: {str(e)}"
# ============================================
# EVENTS
# ============================================
@bot.event
async def on_ready():
"""Called when the bot successfully connects to Discord."""
print(f"✅ Bot is online as {bot.user.name}")
print(f"✅ Connected to {len(bot.guilds)} server(s)")
print(f"✅ Prefix: {PREFIX}")
print("Ready to chat!")
@bot.event
async def on_message(message):
"""Called whenever a message is sent in a channel the bot can see."""
# Ignore messages from the bot itself or other bots
if message.author == bot.user or message.author.bot:
return
# Respond when the bot is mentioned
if bot.user.mentioned_in(message):
user_message = message.content.replace(f'', '').strip()
if not user_message:
return
# Show typing indicator while processing
async with message.channel.typing():
reply = ask_ai(user_message)
await message.reply(reply)
# Ensure commands still work
await bot.process_commands(message)
# ============================================
# RUN THE BOT
# ============================================
if __name__ == "__main__":
bot.run(TOKEN)
봇 실행하기
-
Ollama가 실행 중인지 확인합니다(
ollama serve). -
가상 환경을 활성화합니다.
-
다음 명령을 실행합니다:
python bot.py
봇이 온라인 상태가 되며, Discord에서 봇을 멘션하면 대화를 시작할 수 있습니다.
이제 로컬 Ollama 모델로 구동되는 완전한 AI Discord 봇을 갖게 되었습니다. 직접 커스터마이징하고 확장해 보세요!