안녕하세요! 김코딩입니다
디스코드 봇만들기 에서 discord.py
를 이용해 기본적인 봇을 만들고 간단한 명령어(!hello
, !roll
)를 구현해 봤습니다. 오늘은 한 단계 더 나아가 디스코드 봇을 더욱 똑똑하고 재미있게 만들어볼 예정입니다.
이번 글에서는 다음 기능을 추가할 예정입니다:
이벤트 처리: 서버에 누군가 들어오거나 나갈 때 자동 메시지 전송
명령어 확장: 메시지 삭제(!clear
) 및 서버 정보 확인(!server
)
봇 상태 설정: “봇이 ~을 하는 중” 같은 상태 메시지 표시
그럼 시작해볼까요?
1. 지난 글 복습: 어디까지 했었나요?
이전 글에서는 다음과 같은 작업을 완료했습니다:
discord.py
설치 및 디스코드 개발자 포털에서 봇 생성!hello
,!roll
같은 간단한 명령어 구현- 봇을 서버에 초대하고 실행
이제 이 기본 구조를 바탕으로 새로운 기능을 추가하여 봇을 업그레이드해 보겠습니다!
2. 이번 글의 목표
오늘 추가할 기능은 다음과 같습니다:
- 이벤트 처리 → 서버에 새로운 멤버가 들어오거나 나갈 때 자동 메시지 전송
- 명령어 확장 → 메시지 삭제(
!clear
) 및 서버 정보 확인(!server
) - 봇 상태 설정 → “!help 하는 중” 등의 활동 상태 표시
3. 전체 코드 및 설명
아래는 이번에 추가할 기능을 포함한 전체 코드입니다. 하나씩 분석해볼까요? 🧐
import discord
from discord.ext import commands
import random
# 봇 설정 (접두사: !)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
# 봇이 준비되었을 때 실행
@bot.event
async def on_ready():
print(f"{bot.user}가 온라인이에요!")
await bot.change_presence(activity=discord.Game(name="!help 하는 중"))
# 이벤트: 멤버가 서버에 들어올 때
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel
if channel:
await channel.send(f"{member.mention}님, 서버에 오신 걸 환영합니다! 😊")
# 이벤트: 멤버가 서버에서 나갈 때
@bot.event
async def on_member_remove(member):
channel = member.guild.system_channel
if channel:
await channel.send(f"{member.name}님이 서버를 떠났습니다. 안녕히 가세요... 😢")
# 명령어: 안녕
@bot.command()
async def hello(ctx):
await ctx.send("안녕하세요! 저는 여러분의 봇이에요!")
# 명령어: 주사위 굴리기
@bot.command()
async def roll(ctx):
result = random.randint(1, 6)
await ctx.send(f"주사위를 굴렸어요: {result}")
# 명령어: 메시지 삭제 (!clear 5)
@bot.command()
async def clear(ctx, amount: int):
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"{amount}개의 메시지를 삭제했어요!", delete_after=5)
# 명령어: 서버 정보 확인
@bot.command()
async def server(ctx):
guild = ctx.guild
embed = discord.Embed(title=f"{guild.name} 정보", color=discord.Color.blue())
embed.add_field(name="멤버 수", value=guild.member_count, inline=True)
embed.add_field(name="서버 생성일", value=guild.created_at.strftime("%Y-%m-%d"), inline=True)
if guild.icon:
embed.set_thumbnail(url=guild.icon.url)
await ctx.send(embed=embed)
# 봇 실행 (토큰 입력 필요)
bot.run("여기에-여러분의-토큰을-붙여넣으세요")
4. 주요 기능 분석
4-1. Intents 설정
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
Intents
는 봇이 감지할 수 있는 이벤트를 설정하는 기능입니다.- 중요: 개발자 포털 → Bot 탭 → “Presence Intent”와 “Server Members Intent”를 활성화해야 합니다.
4-2. 봇 상태 설정
await bot.change_presence(activity=discord.Game(name="!help 하는 중"))
- 봇이 “게임 중” 상태로 표시되며, “!help 하는 중”으로 보이게 됩니다.
- 다른 상태 설정 예시:
discord.Streaming(name="스트리밍 중", url="링크")
discord.Activity(type=discord.ActivityType.listening, name="음악 듣는 중")
4-3. 멤버 입장/퇴장 이벤트 처리
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel
if channel:
await channel.send(f"{member.mention}님, 서버에 오신 걸 환영합니다! 😊")
on_member_join
: 새 멤버가 서버에 들어오면 실행on_member_remove
: 멤버가 서버에서 나가면 실행member.mention
: 사용자 멘션system_channel
: 서버의 기본 채널 (#general 등)
4-4. 메시지 삭제 명령어 (!clear
)
@bot.command()
async def clear(ctx, amount: int):
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"{amount}개의 메시지를 삭제했어요!", delete_after=5)
!clear 5
입력 시 최근 5개의 메시지 삭제delete_after=5
: 5초 후 메시지 자동 삭제- 봇과 사용자 모두
Manage Messages
권한 필요
4-5. 서버 정보 확인 (!server
)
@bot.command()
async def server(ctx):
guild = ctx.guild
embed = discord.Embed(title=f"{guild.name} 정보", color=discord.Color.blue())
embed.add_field(name="멤버 수", value=guild.member_count, inline=True)
embed.add_field(name="서버 생성일", value=guild.created_at.strftime("%Y-%m-%d"), inline=True)
if guild.icon:
embed.set_thumbnail(url=guild.icon.url)
await ctx.send(embed=embed)
- 서버 이름, 멤버 수, 생성일, 서버 아이콘을 깔끔한
Embed
형태로 출력
아래는 글에 포함된 모든 기능을 하나의 코드로 합친 완성된 Discord 봇 코드입니다.
📌 포함된 기능:
기본 명령어 (!hello
, !roll
)
이벤트 처리 (on_member_join
, on_member_remove
)
메시지 삭제 (!clear
)
서버 정보 (!server
)
봇 상태 설정
📜전체 코드
import discord
from discord.ext import commands
import random
# 봇 설정 (접두사: !)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
# 봇이 준비되었을 때 실행
@bot.event
async def on_ready():
print(f"{bot.user}가 온라인이에요!")
await bot.change_presence(activity=discord.Game(name="!help 하는 중"))
# 이벤트: 멤버가 서버에 들어올 때
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel # 서버의 기본 채널
if channel is not None:
await channel.send(f"🎉 {member.mention}님, 서버에 오신 걸 환영합니다! 😊")
# 이벤트: 멤버가 서버에서 나갈 때
@bot.event
async def on_member_remove(member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f"😢 {member.name}님이 서버를 떠났습니다. 안녕히 가세요...")
# 명령어: 안녕
@bot.command()
async def hello(ctx):
await ctx.send("안녕하세요! 저는 여러분의 디스코드 봇이에요! 🤖")
# 명령어: 주사위 굴리기
@bot.command()
async def roll(ctx):
result = random.randint(1, 6)
await ctx.send(f"🎲 주사위를 굴렸어요: {result}")
# 명령어: 메시지 삭제 (예: !clear 5)
@bot.command()
async def clear(ctx, amount: int):
if ctx.author.guild_permissions.manage_messages: # 메시지 관리 권한 확인
await ctx.channel.purge(limit=amount + 1) # 명령어 포함 삭제
msg = await ctx.send(f"🗑️ {amount}개의 메시지를 삭제했어요!")
await msg.delete(delay=5) # 5초 후 삭제
else:
await ctx.send("🚫 이 명령어를 사용할 권한이 없습니다!")
# 명령어: 서버 정보
@bot.command()
async def server(ctx):
guild = ctx.guild
embed = discord.Embed(title=f"🌟 {guild.name} 정보", color=discord.Color.blue())
embed.add_field(name="👥 멤버 수", value=guild.member_count, inline=True)
embed.add_field(name="📅 서버 생성일", value=guild.created_at.strftime("%Y-%m-%d"), inline=True)
if guild.icon:
embed.set_thumbnail(url=guild.icon.url) # 서버 아이콘이 있다면 추가
await ctx.send(embed=embed)
# 봇 실행 (토큰 입력 필요)
bot.run("여기에-여러분의-토큰을-붙여넣으세요")

5. 마무리
오늘은 디스코드 봇을 한층 더 업그레이드해보았습니다! 💪
이벤트 활용하여 멤버 입장/퇴장 감지
새로운 명령어 추가 (!clear
, !server
)
봇 상태 설정 적용
다음 글에서는 음악 재생 기능이나 데이터 저장(예: 점수 기록)을 다뤄볼까요? 의견이 있다면 댓글로 알려주세요! 😊
[…] 지난 글에서 이벤트 처리와 유용한 명령어로 봇을 업그레이드해 봤죠? 오늘은 디스코드 서버를 더 신나게 만들어줄 음악 재생 기능을 추가해보겠습니다. 유튜브 링크를 입력하면 음성 채널에서 음악을 틀어주는 봇을 만들어볼게요! 준비물부터 코드까지 차근차근 설명해 드릴 테니 함께 시작해볼까요? […]