Notice
Recent Posts
Recent Comments
Link
Today
Total
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
관리 메뉴

나쵸

몬스터헌터 월드 아이스본(MHW - Ice Born) 디스코드 봇 만들기 본문

IT

몬스터헌터 월드 아이스본(MHW - Ice Born) 디스코드 봇 만들기

violeton 2020. 4. 3. 10:17

얼마전 파이썬을 처음 접해봤다.

 

c언어만 사용해왔던 나는 약간 생소하긴 하다.

 

처음엔 웹 크롤링을 목적으로 배우기 시작했는데 어쩌다보니 내가 주로 하는 게임의 봇을 만들어보면 어떨까 하다가

 

몬헌 봇을 만들게 되었다.

 

혹여 이 글을 보시는 분은 본인이 파이썬 경력이 일주일이 채 되지 않는걸 참고하고 봐주시길 바란다.

 

 

 

 

우선 몬헌에 대한 Base 데이터가 필요한데 구글링을 하다 보니 Json형태로(이것도 파이썬 배우면서 첨 앎)

 

데이터를 제공하는 사이트가 있길래 해당 사이트를 이용하기로 했다.

 

http://mhw.gamedb.kr/etc

 

API :: 몬헌월드DB

몬스터헌터월드 데이타베이스

mhw.gamedb.kr

위와 같이 카테고리별로 API를 제공하는데 이를 이용해 디스코드 봇에서 명령어를 입력해 정보를 불러올것이다.

 

처음에 Json파일을 보고 좀 당황했지만 해당 데이터를 보기 쉽게 파싱해주는 사이트가 있어 유용하게 사용했다.

http://json.parser.online.fr/

 

위와같이 Json을 파싱하여 사용자가 보기 좋게 만들어준다.

 

import discord
from discord.ext.commands import Bot
from discord import Game
import urllib
from urllib import parse
import json
import asyncio

# bot_id = "봇ID"
token = "토큰값"

client = discord.Client()


@client.event
async def on_ready():
    print(client.user.id)
    print("ready")
    game = discord.Game("몬헌")
    await client.change_presence(status=discord.Status.online, activity=game)


@client.event
async def on_message(message):
    try:
        if message.content.startswith("!"):
            if message.content == "!help" or message.content == "!도움":
                embed = discord.Embed(title="Commands", color=0x00ff00)
                embed.add_field(name="몬스터 검색", value="!몬스터 [몬스터명]", inline=False)
                embed.add_field(name="스킬 검색", value="!스킬 [스킬명]", inline=False)
                embed.add_field(name="장식주 검색", value="!장식주 [장식주명]", inline=False)
                embed.add_field(name="호석 검색", value="!호석 [호석명]", inline=False)
                embed.add_field(name="아이템 검색", value="!아이템 [아이템명]", inline=False)
                embed.add_field(name="도움말", value="!도움 or !help", inline=False)
                embed.add_field(name="몬헌봇 초대코드", value="!초대", inline=False)
                await message.channel.send(embed=embed)
            elif message.content == "!초대":
                embed = discord.Embed(title="Invite bot url", color=0x00ff00)
                embed.add_field(name="초대코드", value="https://discordapp.com/oauth2/authorize?client_id=697008516493213737&scope=bot", inline=False)
                await message.channel.send(embed=embed)
            else:
                if message.content.startswith("!몬스터"):
                    with open('monsters.json', encoding='utf-8') as f:
                        json_str = json.load(f)
                    in_msg = message.content
                    msg_1 = in_msg.split()[1]
                    for i in json_str:
                        if msg_1 in i['name']:
                            image = i['image']
                            size = i['gubun']
                            name = i['name']
                            type_a = i['nick']
                            type_b = i['type']
                            desc = i['description']
                            h_info = i['hunt_info']
                            fire_weak = i['weakness']['fire']
                            water_weak = i['weakness']['water']
                            thunder_weak = i['weakness']['thunder']
                            ice_weak = i['weakness']['ice']
                            dragon_weak = i['weakness']['dragon']
                            poison_de = i['debuff']['poison']
                            sleep_de = i['debuff']['sleep']
                            paralysis_de = i['debuff']['paralysis']
                            explosion_de = i['debuff']['explosion']
                            faint_de = i['debuff']['faint']
                            weak_txt = ("불 [" + str(fire_weak) + ']\n' + "물 [" + str(water_weak) + ']\n' + "번개 [" + str(
                                thunder_weak) + ']\n' + "얼음 [" + str(ice_weak) + ']\n' + "용 [" + str(
                                dragon_weak) + ']\n')
                            debuff_txt = (
                                        "독 [" + str(poison_de) + ']\n' + "수면 [" + str(sleep_de) + ']\n' + "마비 [" + str(
                                    paralysis_de) + ']\n' + "폭발 [" + str(explosion_de) + ']\n' + "기절 [" + str(
                                    faint_de) + ']\n')
                            embed = discord.Embed(title=name, color=0x00ff00)
                            embed.set_author(name="몬스터", icon_url="https://i.postimg.cc/L4ry51x7/2020-04-07-093142.png")
                            embed.add_field(name="크기", value=size, inline=True)
                            embed.add_field(name="구분1", value=type_a, inline=True)
                            embed.add_field(name="구분2", value=type_b, inline=True)
                            embed.add_field(name="약점", value=weak_txt, inline=True)
                            embed.add_field(name="유효상태이상", value=debuff_txt, inline=True)
                            embed.add_field(name="사냥정보", value=h_info, inline=False)
                            embed.set_image(url=image)
                            await message.channel.send(embed=embed)

                elif message.content.startswith("!스킬"):
                    with open('skills.json', encoding='utf-8') as f:
                        json_str = json.load(f)
                    in_msg = message.content
                    msg_1 = in_msg.split()[1]
                    for i in json_str:
                        if msg_1 in i['name']:
                            type = i['type']
                            name = i['name']
                            arr = []
                            for h in i['desc']:
                                desc_1 = h['name']
                                desc_2 = h['description']
                                dc_desc = ("{}\n {}".format(desc_1, desc_2))
                                arr.append(dc_desc)
                            txt = ('\n'.join(arr))
                            embed = discord.Embed(title=name, color=0x00ff00)
                            embed.set_author(name="스킬", icon_url="https://i.postimg.cc/tJwyypZn/2020-04-07-153305.png")
                            embed.add_field(name="타입", value=type, inline=False)
                            embed.add_field(name="스킬설명", value=txt, inline=False)
                            await message.channel.send(embed=embed)

                elif message.content.startswith("!장식주"):
                    in_key = message.content
                    msg_1 = in_key.split()[1]
                    with open('jewels.json', encoding='utf-8') as f:
                        json_str = json.load(f)
                    for i in json_str:
                        if msg_1 in i['name']:
                            i_val1 = i['name']
                            i_val2 = i['slot_level']
                            i_val3 = i['rare']
                            ii_arr1 = []
                            if i['slot_level'] == 1:
                                slot = "♢"
                            elif i['slot_level'] == 2:
                                slot = "♢♢"
                            elif i['slot_level'] == 3:
                                slot = "♢♢♢"
                            elif i['slot_level'] == 4:
                                slot = "♢♢♢♢"
                            for ii in i['skills']:
                                ii_val1 = ('[' + ii['name'] + ']')
                                ii_arr1.append(ii_val1)
                                for iii in ii['detail']:
                                    iii_val1 = iii['name']
                                    iii_val2 = iii['level']
                                    iii_val3 = iii['description']
                                    iii_txt = ("Lv - {} {}".format(iii_val2, iii_val3))
                                    ii_arr1.append(iii_txt)
                            skill_txt = ('\n'.join(ii_arr1))
                            embed = discord.Embed(title=i_val1, color=0x00ff00)
                            embed.set_author(name="장식주", icon_url="https://i.postimg.cc/hvHVGVg0/2020-04-06-150809.png")
                            embed.add_field(name="레어도", value=i_val3, inline=True)
                            embed.add_field(name="슬롯크기", value=slot, inline=True)
                            embed.add_field(name="스킬설명", value=skill_txt, inline=False)
                            await message.channel.send(embed=embed)

                elif message.content.startswith("!호석"):
                    in_key = message.content
                    msg_1 = in_key.split()[1]
                    with open('charms.json', encoding='utf-8') as f:
                        json_str = json.load(f)
                    arr1 = []
                    arr2 = []
                    for i in json_str:
                        if msg_1 in i['name']:
                            name = i['name']
                            m_level = i['max_level']
                            dc_desc_1 = ("{}".format(m_level))
                            # arr1.append(dc_desc_1)
                            for h in i['skills_info']:
                                desc_1 = h['name']
                                dc_desc = ("\n[{}][{}]".format(desc_1, dc_desc_1))
                                for j in h['detail']:
                                    desc_1_2 = j['level']
                                    desc_1_3 = j['description']
                                    dc_desc_1_1 = ("Lv - {} {}".format(desc_1_2, desc_1_3))
                                    arr1.append(dc_desc_1_1)
                            for n in i['upgrade_info']:
                                n_desc = n['level']
                                ndc_desc = ("\nLv - {}".format(n_desc))
                                arr2.append(ndc_desc)
                                for nn in n['items']:
                                    nn_desc1 = nn['name']
                                    nn_desc2 = nn['count']
                                    nndc_desc = (" {} [{}]".format(nn_desc1, nn_desc2))
                                    arr2.append(nndc_desc)
                            txt = ('\n'.join(arr1))
                            txt2 = (''.join(arr2))
                            embed = discord.Embed(title=name, color=0x00ff00)
                            embed.set_author(name="호석", icon_url="https://i.postimg.cc/02FfvH8w/2020-04-07-155836.png")
                            embed.add_field(name="스킬", value=desc_1, inline=True)
                            embed.add_field(name="최대강화레벨", value=dc_desc_1, inline=True)
                            embed.add_field(name="스킬효과", value=txt, inline=False)
                            embed.add_field(name="강화재료", value=txt2, inline=False)
                            await message.channel.send(embed=embed)

                elif message.content.startswith("!아이템"):
                    in_key = message.content
                    msg_1 = in_key.split()[1]
                    with open('items.json', encoding='utf-8') as f:
                        json_str = json.load(f)
                    for i in json_str:
                        if msg_1 in i['name']:
                            name = i['name']
                            desc = i['description']
                            rare = i['rare']
                            drop = i['drop_monster']
                            dc_desc = ("[드랍몬스터]\n{}\n레어도 - {}\n\n[설명]\n{}".format(drop, rare, desc))
                            embed = discord.Embed(title=name, color=0x00ff00)
                            embed.set_author(name="아이템", icon_url="https://i.postimg.cc/4xhZJ100/2020-04-07-162231.png")
                            embed.add_field(name="레어도", value=rare, inline=True)
                            embed.add_field(name="드랍 몬스터", value=drop, inline=True)
                            embed.add_field(name="설명", value=drop, inline=False)
                            await message.channel.send(embed=embed)
        print(message.content)

    except Exception as ex:
        await message.channel.send(ex)


client.run(token)

위와같이 소스코드를 작성하고 컴파일해보면 아래와 같이 데이터가 표시된다.

 

위에선 txt변수를 파이참에서 출력했지만 해당 변수를 디스코드 봇 메시지 send로 날려 보내면 된다.

 

 

쨔쟌 완성!

 

추가(봇 초대링크) : https://discordapp.com/oauth2/authorize?client_id=697008516493213737&scope=bot

Comments