본문바로가기
자유게시판
수학을 주제로 떠들어 보세요!
[잡담] 그냥
자연상수 2021.01.18 20:00 조회 492

공유할게요

봇에 따라 바뀌는 것은(토큰, 접두사, 퍼스널 컬러 등)주석 찾으시면 쉽게 바꿀 수 있게 변수로 만들었습니다

discord 모듈, request 모듈, bs4 모듈 설치해야 돼요

 

token = "여기다가 토큰 입력"#토큰

personalcolor = 0x여기 헥스 코드로 퍼스널 컬러 입력

from discord.ext import commands

import requests 

import discord

client = discord.Client()

from bs4 import BeautifulSoup

import time

bot = commands.Bot(command_prefix='여기 접두사 입력')#접두사

start = time.time()

@bot.event

async def on_ready():

    print('Logged in as')

    print(bot.user.name)

    print(bot.user.id)

    print('------')

    await bot.change_presence(activity=discord.Game(name="with users | ``help")) #~하는 중이 name에 들어감

@bot.command()

async def ping(ctx):

    await ctx.send(f':ping_pong: pong! `{round(round(bot.latency, 4)*1000)}ms`')#핑

@bot.command()

async def test(ctx):

    await ctx.send("send completed")#발신 테스트

@bot.command()

async def weather(ctx, loc1):

    location = loc1# + " " + loc2 + " " + loc3

    Finallocation = location + '날씨' 

    LocationInfo = "" 

    NowTemp = "" 

    CheckDust = [] 

    url = 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=' + Finallocation 

    hdr = {'User-Agent': ('mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/78.0.3904.70 safari/537.36')} 

    req = requests.get(url, headers=hdr) 

    html = req.text 

    soup = BeautifulSoup(html, 'html.parser') 

    # 오류 체크 

    ErrorCheck = soup.find('span', {'class' : 'btn_select'}) 

    if 'None' in str(ErrorCheck): 

        await ctx.send("Error! 지역 검색 오류!") 

    else: # 지역 정보 

        for i in soup.select('span[class=btn_select]'): 

            LocationInfo = i.text # 현재 온도 

            NowTemp = soup.find('span', {'class': 'todaytemp'}).text + soup.find('span', {'class' : 'tempmark'}).text[2:] 

            # 날씨 캐스트 

            WeatherCast = soup.find('p', {'class' : 'cast_txt'}).text 

            # 오늘 오전온도, 오후온도, 체감온도 

            TodayMorningTemp = soup.find('span', {'class' : 'min'}).text 

            TodayAfternoonTemp = soup.find('span', {'class' : 'max'}).text 

            TodayFeelTemp = soup.find('span', {'class' : 'sensible'}).text[5:] 

            # 자외선 지수 

            TodayUV = soup.find('span', {'class' : 'indicator'}).text[4:-2] + " " + soup.find('span', {'class' : 'indicator'}).text[-2:] 

            # 미세먼지, 초미세먼지, 오존 지수 

            CheckDust1 = soup.find('div', {'class': 'sub_info'}) 

            CheckDust2 = CheckDust1.find('div', {'class': 'detail_box'}) 

            for i in CheckDust2.select('dd'): 

                CheckDust.append(i.text) 

            FineDust = CheckDust[0][:-2] + " " + CheckDust[0][-2:] 

            UltraFineDust = CheckDust[1][:-2] + " " + CheckDust[1][-2:] 

            Ozon = CheckDust[2][:-2] + " " + CheckDust[2][-2:] 

            # 내일 오전, 오후 온도 및 상태 체크 

            tomorrowArea = soup.find('div', {'class': 'tomorrow_area'}) 

            tomorrowCheck = tomorrowArea.find_all('div', {'class': 'main_info morning_box'}) 

            # 내일 오전온도 

            tomorrowMoring1 = tomorrowCheck[0].find('span', {'class': 'todaytemp'}).text 

            tomorrowMoring2 = tomorrowCheck[0].find('span', {'class' : 'tempmark'}).text[2:] 

            tomorrowMoring = tomorrowMoring1 + tomorrowMoring2 

            # 내일 오전상태 

            tomorrowMState1 = tomorrowCheck[0].find('div', {'class' : 'info_data'}) 

            tomorrowMState2 = tomorrowMState1.find('ul', {'class' : 'info_list'}) 

            tomorrowMState3 = tomorrowMState2.find('p', {'class' : 'cast_txt'}).text 

            tomorrowMState4 = tomorrowMState2.find('div', {'class' : 'detail_box'}) 

            tomorrowMState5 = tomorrowMState4.find('span').text.strip() 

            tomorrowMState = tomorrowMState3 + " " + tomorrowMState5 

            # 내일 오후온도 

            tomorrowAfter1 = tomorrowCheck[1].find('p', {'class' : 'info_temperature'}) 

            tomorrowAfter2 = tomorrowAfter1.find('span', {'class' : 'todaytemp'}).text 

            tomorrowAfter3 = tomorrowAfter1.find('span', {'class' : 'tempmark'}).text[2:] 

            tomorrowAfter = tomorrowAfter2 + tomorrowAfter3 

            # 내일 오후상태 

            tomorrowAState1 = tomorrowCheck[1].find('div', {'class' : 'info_data'}) 

            tomorrowAState2 = tomorrowAState1.find('ul', {'class' : 'info_list'}) 

            tomorrowAState3 = tomorrowAState2.find('p', {'class' : 'cast_txt'}).text 

            tomorrowAState4 = tomorrowAState2.find('div', {'class' : 'detail_box'}) 

            tomorrowAState5 = tomorrowAState4.find('span').text.strip() 

            tomorrowAState = tomorrowAState3 + " " + tomorrowAState5

            embed = discord.Embed(title = LocationInfo + " 날씨 정보", colour = personalcolor)

            embed.add_field(name = "오늘 날씨", value = ":thermometer: 현재온도: " + NowTemp + "\n" + ":thermometer: 체감온도: " + TodayFeelTemp + "\n" \

                + ":thermometer: 오전/오후 온도: " + TodayMorningTemp + "/" + TodayAfternoonTemp + "\n" + "현재 상태: " + WeatherCast + "\n" \

                + "현재 자외선 지수: " + TodayUV + "\n" + "현재 미세먼지 농도: " + FineDust + "\n" \

                + "현재 초미세먼지 농도: " + UltraFineDust + "\n" + "현재 오존 지수: " + Ozon, inline = False)

            embed.add_field(name = "내일 날씨",value = ":thermometer: 내일 오전 온도: " + tomorrowMoring + "\n" \

                + "내일 오전 상태: " + tomorrowMState + "\n" + ":thermometer: 내일 오후 온도: " + tomorrowAfter + "\n" \

                + "내일 오후 상태: " + tomorrowAState ,inline=False)

            embed.set_footer(text="Powered by naver.com")

            await ctx.send(embed=embed)

@bot.command()

async def info(ctx):

    infotime = time.time()

    S = round(infotime - start)

    D = 0

    H = 0

    M = 0

    while S > 86400:

        S = S - 86400

        D += 1

    while S > 3600:

        S = S - 3600

        H += 1

    while S > 60:

        S = S - 60

        M += 1  

    infoembed = discord.Embed(title = bot.user.name, colour = personalcolor)

    infoembed.add_field(name = "Version", value = "1.2.0", inline = True)

    infoembed.add_field(name = "Uptime", value = "{0} Days {1} Hours {2} Minutes {3} Seconds".format(D,H,M,S), inline = True)

    infoembed.add_field(name = "Code", value = "Python", inline = True)

    infoembed.add_field(name = "Id", value = bot.user.id, inline = True)

    infoembed.add_field(name = "Developer", value = "star0202#3327", inline = True)

    await ctx.send(embed=infoembed)

bot.run(token)

"""

명령어 쓰기

@bot.command()

async def 명령어_이름(ctx): 

    await ctx.send(말)

순서대로 게임 스트리밍 듣기 보기

await bot.change_presence(activity=discord.Game(name="xx")) 

await bot.change_presence(activity=discord.Streaming(name = 'xx', url='xx')) 

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="XX")) 

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="xx"))

"""

  •  
    자몽이 Lv.6 2021.01.18 20:39

    댓글 작성하기 좋아요0 댓글수0
  •  
    s.pie Lv.6 2021.01.19 03:48

    코알못이라 죄송.....

    댓글 작성하기 좋아요0 댓글수0
  •  
    원파 Lv.9 2021.01.19 08:17

    와!

    나중에 써볼게요! 감사합니다!

    댓글 작성하기 좋아요0 댓글수2
    •  
      자연상수 Lv.5 2021.01.19 18:42

      중간에 infoembed.add_field(name = "Developer", value = "star0202#3327", inline = True)에서 star0202#3327 제 디코여서 바꿔서 쓰세요

      친추보내지 마세요

      @원형파이

      좋아요0
    •  
      원파 Lv.9 2021.01.20 08:14

      @자연상수

      아... 네ㅠㅠ

      좋아요1
  • 폴리매스 문제는 과학기술진흥기금 및 복권기금의 재원으로 운영되고, 과학기술정보통신부와 한국과학창의재단의 지원을 받아 수행된 성과물로 우리나라의 과학기술 발전과 사회적 가치 증진에 기여하고 있습니다.

  • ☎문의 02-6749-3911