지난 이야기
https://koilsdevelopment.tistory.com/3
디스코드 봇 만들기 대작전 (1) - 메시지 출력
https://koilsdevelopment.tistory.com/2 디스코드 봇 만들기 대작전 (0) - 준비 개발 블로그의 첫 게시글은 디스코드 봇으로 장식하고자 한다. 물론 인풋을 쌓고 쌓아 날 함양하는 것도 좋다지만, 인풋만큼
koilsdevelopment.tistory.com
이전 화에서 디스코드 봇을 이용해 메시지를 출력시키는 방법에 대해 공부해보았다. 매우 기초적인 과정이긴 하지만 대화가 주로 이루어지는 디스코드의 특성상 메시지는 꽤 중요한 역할을 수행한다. 오늘은 그 메시지를 조금 더 다양하게 보내는 방법에 대해 논해보고자 한다.
0. 전체 코드
우선 작성한 코드는 다음과 같다.
import discord
import random
from discord.ext import commands
mybot=commands.Bot(command_prefix='/', intents=discord.Intents.all())
@mybot.event
async def on_ready():
print('Bot is Working Now!')
# 커맨드 확인
@mybot.command()
async def ContextCommand(ctx):
await ctx.send(ctx.guild)
await ctx.send(ctx.command)
await ctx.send(ctx.author)
await ctx.send(ctx.author.mention)
# 명령어 입력받기
@mybot.command()
async def getArg(ctx, *args):
await ctx.send(args)
if args[0]=='key':
await ctx.send('```You just Typed the Key```')
# 주사위 구현
@mybot.command()
async def dice(ctx, num: int):
if num>0:
result=random.randrange(0, num)
await ctx.send(result+1)
mybot.run('사용할 토큰')
이전 코드에서 random을 새로 import했고, 기존의 hello 명령어는 제거했다. 참고로 명령어를 여러 개 선언하려면 코드와 같이 @mybot.command()를 여러번 선언해야 한다는 점이 불편하게 작용했다. 무언가 다른 방법이 있다면 그 방법을 찾아봐야겠다.
1. Context의 구성
@mybot.command()
async def ContextCommand(ctx):
await ctx.send(ctx.guild) # 서버 이름 반환
await ctx.send(ctx.command) # 입력받은 명령어 반환
await ctx.send(ctx.author) # 호출자 반환
await ctx.send(ctx.author.mention) # 호출자 멘션
함수에서 항상 매개변수로 받는 ctx의 정체는 Context였다. 정확히는 discord.ext.commands.Context이다.
이 매개변수로 할 수 있는 일은 다음과 같다. 메시지를 출력할 수도 있고, 도리어 받아온 메시지나 호출자의 아이디를 호출할 수도 있다. 내가 짠 코드 상에서 사용해본 기능은 서버이름 호출, 현재 입력받은 명령어 호출, 호출자 아이디 호출, 그리고 호출자 멘션이다.
실행 결과는 다음과 같다. 이 기능을 이용해 다양한 조건들을 걸어 여러 기능을 구현할 수 있을 것이다. Context에 대한 자세한 내용은 아래 링크를 참고할 것.
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#context
API Reference
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as i
discordpy.readthedocs.io
2. 입력 받고 이용하기
@mybot.command()
async def getArg(ctx, *args): # 여러 개의 값을 입력받음
await ctx.send(args) # 입력받은 값 출력
if args[0]=='key': # 만약 처음 입력한 값이 key면
await ctx.send('```You just Typed the Key```') # 임의의 메시지 추가 전송
다음으로 입력을 넣어주는 것이다. 매개변수로 ctx 이후에 *args를 선언함으로서 가변 길이의 입력값을 받아낼 수 있다. 참고로 개별의 값들은 공백을 통해 구분된다.
실행 결과다. 첫번째 값으로 key를 입력하면 다른 결과가 출력된다.
이렇듯 명령어의 입출력만 신경써준다면, 디스코드 봇으로 다양한 프로그램을 기존 코딩하듯 만들 수 있다는 것이다. 단지 API 일부만 신경 써주면서 기존 파이썬으로 코딩하듯 만들면 다양한 기능을 만들 수 있을 것이다.
3. 연습) 주사위 기능 구현
그래서 필자는 간단한 주사위 프로그램을 만들어보고자 했다. 최댓값을 입력해주면 해당 범위 내에서 랜덤한 숫자를 출력해주는 기능이다.
@mybot.command()
async def dice(ctx, num: int): # 정수형 입력 num을 받음
if num>0: # 만약 입력값이 양수면
result=random.randrange(0, num) # 양수 범위 내에서 무작위의 값을 얻어냄
await ctx.send(result+1) # 0부터 무작위 값을 받았으므로 1을 더해서 출력
위의 코드는 임의의 정수형 입력을 받은 뒤, 만약 입력값이 양수면 무작위의 수를 반환해주는 기능을 수행하고 있다.
실행 결과다. 무작위 값을 제대로 출력하는 모습을 보여주고 있다.
이렇게 보면 디스코드 봇도 생각보다 간단할지도 모르겠다. 다양한 기능들을 생각만 해낸다면 이후부턴 단순 코딩의 영역인지라 더 간단하게 느껴지는 것일지도 모르겠다. 그래도 섣부른 방심은 금물. 아직까지는 디스코드.py의 API를 뜯어보면서 어떻게 활용해볼 수 있을지 공부해봐야겠다.
참고한 링크
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#context
API Reference
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as i
discordpy.readthedocs.io
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
Commands
discordpy.readthedocs.io
5.3.1 랜덤(random) 모듈
이번에는 파이썬에서의 랜덤(random)에 대해 가볍게 정리해 볼까 합니다. 우선 랜덤이 무엇인지부터 살펴볼까요. 주사위를 던지는 상황을 생각해봅시다. 주사위의 각 면에는 1…
wikidocs.net
'프로그래밍 > Discord Bot' 카테고리의 다른 글
디스코드 봇 만들기 대작전 (4) - 24시간 호스팅 (koyeb) (2) | 2024.01.15 |
---|---|
디스코드 봇 만들기 대작전 (3) - 명령어 목록 출력 (3) | 2024.01.13 |
디스코드 봇 만들기 대작전 (1) - 메시지 출력 (0) | 2024.01.09 |
디스코드 봇 만들기 대작전 (0) - 준비 (1) | 2024.01.09 |