[Discord Bot] 마법의 소라고동 2편

김민창·2021년 10월 25일
0

discord bot

목록 보기
2/2
post-thumbnail
  • 파이썬이라는 언어도 모르고 학교선배를 놀리기위해 시작한 디스코드 봇 제작 회고록
  • 현재 가장 애착을 가지고 운영중인 프로젝트

Code

import discord
import asyncio
import random 
from discord.ext import commands

client =discord.Client()
#client = commands.Bot(command_prefix='!')

@client.event 
async def on_ready():
    print("login")
    print(client.user.name)
    print(client.user.id)
    print("-----------------")
    await client.change_presence(status=discord.Status.online, activity=discord.Game('김기담 제거'))



@client.event
async def on_message(message):
    if message.content.startswith('민창'):
        await message.channel.send("개발자님 너무 빛이납니다. 엉엉")
    if message.content.startswith('김기담'):
        await message.channel.send("뚱땡이!")

    if message.content.startswith('소라고동'):
        randomNum = random.randrange(1, 3)
        if randomNum==1:
            await message.channel.send(embed=discord.Embed(title="그래.", color=discord.Color.blue()))
        else:
            await message.channel.send(embed=discord.Embed(title="아니.", color=discord.Color.red()))
    if message.content.startswith('마법의'):
        randomNum = random.randrange(1, 3)
        if randomNum==1:
            await message.channel.send(embed=discord.Embed(title="그래.", color=discord.Color.blue()))
        else:
            await message.channel.send(embed=discord.Embed(title="아니.", color=discord.Color.red()))
client.run(token)

Code Analysis

  • 이곳저곳에서 짜집기를 했을때라 미관상 좋진않다.

추가된 라이브러리

import asyncio
import random
  • async, await 등 비동기 프로그래밍을 위한 asyncio 라이브러리 추가(근데 첫번째 글을 보면 안써도 가능했음)

  • 소라고동의 랜덤한 응답을 받기 위한 random 라이브러리 추가


특정 메세지로 시작할때 응답

@client.event
async def on_message(message):
    if message.content.startswith('민창'):
        await message.channel.send("개발자님 너무 빛이납니다. 엉엉")
  • 사용자가 메세지를 보낼때마다 startswith 를 활용하여 특정 단어로 시작될때마다 반응할 수 있도록 구성

랜덤반응 추가

if message.content.startswith('소라고동'):
	randomNum = random.randrange(1, 3)
	if randomNum==1:
		await message.channel.send(embed=discord.Embed(title="그래.", color=discord.Color.blue()))
	else:
		await message.channel.send(embed=discord.Embed(title="아니.", color=discord.Color.red()))
  • 사실상 특정 메세지로 시작할때 응답하는것과 똑같다.

  • 소라고동 이라는 단어로 시작한다면 랜덤한 난수를 뽑는다.

  • 이때, randrange(1, 3)은 1 이상 3 미만의 난수라고 생각하면 된다.


embed로 메세지 꾸미기

  • 단순한 텍스트가 아닌 embed 를 활용하여 메세지를 꾸밀 수 있다.

  • embed 내용으로 텍스트 외에 설정만 한다면 원하는 사진도 넣을수있다.

  • embed 를 활용하여 만든 예시와 코드는 다음과 같다.


embed = discord.Embed(color=discord.Color.blue())
embed.set_author(name=plus + "님의 티어는?")
embed.set_thumbnail(url=url1)
embed.add_field(
	name=level, value="소라고동이 인증합니다🙂", inline=False)
await ctx.send(embed=embed)
  • discord.Embed 로 선언함과 동시에 색을 정해줄 수 있다.

  • 쓰라고 정해진느낌의 함수들이 있었는데 나같은 경우는 미관상 어떤게 더 보기좋을까 고민하고 마음대로 사용했었다.

  • embed.set_author 를 통해 작성자를 상단에 위치시켰다.

  • embed.set_thumbnail 을 통해 url 로 이미지를 따오게 했는데 heroku 서버에 토큰들을 저장해놨음

  • embed.add_field 로 원한다면 계속 값을 추가할수있다.

  • namevalue 두가지 파라미터가 존재하는데 세트라고 생각하면 괜찮을것 같고, 글자 색으로 간단하게 구별할 수 있다.


  • 코드는 단순화시켜서 올리고 있답니다.

  • 다음번에는 크롤링했었던걸 가져오겠습니다.

profile
개발자 팡이

0개의 댓글