async def 지식인(self, ctx, *args): if len(args) == 0: await self.bot.say("검색할 내용을 추가로 입력해주세용") return await self.bot.send_typing(ctx.message.channel) search = "".join([arg for arg in args]) encText = urllib.parse.quote(search.encode("utf-8")) url = "https://openapi.naver.com/v1/search/kin.json?query={}".format( encText) http = HTTPHandler() response = http.get(url, self.naverClient) rescode = response.getcode() if (rescode == 200): response_body = response.read().decode() response_body = json.loads(response_body) items = response_body["items"] title = "{}에 대한 지식인 검색 결과에용".format(search) em = discord.Embed(title=title, colour=0xDEADBF) cnt = 0 for item in items: cnt += 1 stripper = HTMLStripper() em.add_field(name=stripper.strip_tags(item["title"]), value=stripper.strip_tags(item["description"])) if cnt == 5: break await self.bot.send_message(ctx.message.channel, embed=em) else: await self.bot.say("오류가 발생했어용\n{}".format( response.read().decode("utf-8")))
async def 갱게서버(self, ctx): GG2_LOBBY_URL = "http://www.ganggarrison.com/lobby/status" http = HTTPHandler() response = http.get(GG2_LOBBY_URL, None) rescode = response.getcode() if (rescode == 200): response_body = response.read().decode() serverList = self.findServerList(response_body) em = discord.Embed(title="현재 GG2 로비 정보에용", colour=0xDEADBF) for server in serverList: personPercentage = server.current / server.max if personPercentage < 0.33: personEmoji = "☠️" elif personPercentage < 0.66: personEmoji = "🙇" else: personEmoji = "🙌" desc = "🗺️: {}\n🛠️: {}\n{}: {}/{}".format( server.map, server.mod, personEmoji, server.current, server.max) em.add_field(name="💠 {}".format(server.name), value=desc) await self.bot.send_message(ctx.message.channel, embed=em) else: await self.bot.say("오류가 발생했어용\n{}".format( response.read().decode("utf-8")))
async def 갱게스텟(self, ctx, *args): if len(args) == 0: await self.bot.say("닉네임도 주세용") return nickname = " ".join([arg for arg in args]) nickname = urllib.parse.quote(nickname.encode("utf-8")) url = "http://gg2statsapp.appspot.com/getstat?nickname={}".format( nickname) http = HTTPHandler() response = http.get(url, None) rescode = response.getcode() if not rescode == 200: await self.bot.say("오류가 발생했어용: {}".format(rescode)) return response_body = response.read().decode() stat = json.loads(response_body) if not stat: await self.bot.say("해당 유저의 정보가 없어용") return pages = [] pages.append(self.overall(stat)) pages.append(self.playtime(stat)) pages.append(self.classinfo(stat)) session = Session(self.bot, ctx.message, pages=pages, show_footer=True) await session.start()
def searchVideos(self, searchText): searchText = urllib.parse.quote(searchText) youtubeUrl = "https://www.youtube.com/results?search_query={}".format( searchText) http = HTTPHandler() response = http.get(youtubeUrl, self.headers) html = BeautifulSoup(response.read().decode(), 'html.parser') videoDOMs = html.find_all("div", {"class": "yt-lockup-content"}) videos = [] for videoDOM in videoDOMs: url = videoDOM.find('a').get("href") if self.isVideo(url): videos.append(self.parseVideo(videoDOM)) return videos
async def 나무위키(self, ctx, *args): await self.bot.send_typing(ctx.message.channel) searchText = " ".join([arg for arg in args]) if searchText == "랜덤": url = "https://namu.wiki/random" else: encText = urllib.parse.quote(searchText.encode("utf-8")) url = "https://namu.wiki/w/{}".format(encText) http = HTTPHandler() try: response = http.get(url, None) except URLError: await self.bot.say("문서가 존재하지 않아용") return html = BeautifulSoup(response.read().decode(), 'html.parser') content = html.find("article") for br in content.find_all("br"): br.replace_with("\n") for delete in content.find_all("del"): delete.string = "~~{}~~".format(delete.get_text()) title = content.find("h1", {"class": "title"}).find('a').string items = content.find_all('', {"class": "wiki-heading"}) indexes = [item.find('a').string.rstrip('.') for item in items] items = [item.get_text().rstrip("[편집]") for item in items] descs = content.find_all("div", {"class": "wiki-heading-content"}) for desc in descs: for ul in desc.find_all("ul", recursive=False): self.sanitizeUl(ul) unorderedArticleDOM = content.find("div", {"class": "wiki-inner-content"}) # 넘버링된 Article들 위의 문단 articles = self.checkUnorderedArticles(unorderedArticleDOM, title, url) for i in range(len(items)): desc = descs[i].get_text()[:2000] if desc: page = Page(title=title, desc=desc, url="{}#s-{}".format(url, indexes[i]), footer_format=items[i]) articles.append(page) if not articles: await self.bot.say("문서가 존재하지 않아용") return session = Session(self.bot, ctx.message, pages=articles, max_time=60, show_footer=True) await session.start()
def searchVideoList(self, playListId): url = "https://www.youtube.com/playlist?list={}".format(playListId) http = HTTPHandler() response = http.get(url, self.headers) html = BeautifulSoup(response.read().decode(), 'lxml') videos = [] videoDOMs = html.find_all("tr", {"class": "pl-video"}) for videoDOM in videoDOMs: title = videoDOM.get("data-title") url = "https://youtu.be/{}".format(videoDOM.get("data-video-id")) timeDOM = videoDOM.find("td", { "class": "pl-video-time" }).find("span") if not timeDOM: continue time = timeDOM.string videos.append(Video(url=url, video_title=title, video_time=time)) return videos
async def tts(self, ctx, *args): if len(args) == 0: await self.bot.say("말할 내용을 추가로 입력해주세용") return ttsText = " ".join([arg for arg in args]) encText = urllib.parse.quote(ttsText) data = "speaker=jinho&speed=0&text=" + encText url = "https://openapi.naver.com/v1/voice/tts.bin" http = HTTPHandler() response = http.post(url, self.naverClient, data) rescode = response.getcode() if (rescode == 200): response_body = response.read() millis = int(time.time() * 1000) fileDir = './temp/{}_{}.mp3'.format(ctx.message.server.id, millis) with open(fileDir, 'wb') as f: f.write(response_body) await Sound.instance.play(ctx, MusicType.TTS, fileDir, ttsText) else: self.bot.say("음성 다운로드에 실패했어용")
async def 네이버이미지(self, ctx, *args): await self.bot.send_typing(ctx.message.channel) searchText = " ".join([arg for arg in args]) encText = urllib.parse.quote(searchText) url = "https://openapi.naver.com/v1/search/image?query=" + encText http = HTTPHandler() response = http.get(url, self.naverClient) rescode = response.getcode() if (rescode == 200): response_body = response.read().decode("utf-8") response_body = json.loads(response_body) if response_body["total"]: picture = response_body["items"][0] em = discord.Embed(title=picture["title"], colour=0xDEADBF) em.set_image(url=picture["link"]) await self.bot.send_message(ctx.message.channel, embed=em) else: await self.bot.say("검색결과가 없어용") else: await self.bot.say("오류가 발생했어용\n{}".format( response.read().decode("utf-8")))
async def translate(self, lang, url, text, channel): self.bot.send_typing(channel) translateLangToEn = {"영어": "en", "중국어": "zh-CN", "일본어": "ja"} translateFlag = {"영어": '🇺🇸', "중국어": '🇨🇳', "일본어": '🇯🇵'} encText = urllib.parse.quote(text) data = "source=ko&target={}&text=".format( translateLangToEn[lang]) + encText http = HTTPHandler() response = http.post(url, self.naverClient, data) rescode = response.getcode() if (rescode == 200): response_body = response.read().decode("utf-8") response_body = json.loads(response_body) em = discord.Embed(description="{} {}".format( translateFlag[lang], response_body["message"]["result"]["translatedText"]), colour=0xDEADBF) await self.bot.send_message(channel, embed=em) else: await self.bot.say("오류가 발생했어용\n{}".format( response.read().decode("utf-8")))
async def 로마자변환(self, ctx, args): if len(args) <= 10: await self.bot.send_typing(ctx.message.channel) encText = urllib.parse.quote(args) url = "https://openapi.naver.com/v1/krdict/romanization?query=" + encText http = HTTPHandler() response = http.get(url, self.naverClient) rescode = response.getcode() if (rescode == 200): response_body = response.read().decode("utf-8") response_body = json.loads(response_body) if len(response_body["aResult"]): em = discord.Embed(description=response_body["aResult"][0] ["aItems"][0]["name"], colour=0xDEADBF) await self.bot.send_message(ctx.message.channel, embed=em) else: await self.bot.say("해당 이름에 대한 로마자변환에 실패했어용") else: await self.bot.say("오류가 발생했어용\n{}".format( response.read().decode("utf-8"))) else: await self.bot.say("10자 이하의 이름을 입력해주세용")
async def 히토미(self, ctx, index): if not self.isNSFW(ctx.message.channel): await self.alertOnlyInNSFW(ctx.message.channel) return try: index = int(index) except ValueError: self.bot.say("제대로 된 숫자를 인자로 주세용") return await self.bot.send_typing(ctx.message.channel) url = "https://hitomi.la/galleries/{}.html".format(index) http = HTTPHandler() try: response = http.get(url, None) except Exception as e: await self.bot.say("페이지가 존재하지 않아용") return html = BeautifulSoup(response.read().decode(), 'html.parser') coverDiv = html.find("div", {"class": "cover"}) coverUrl = "https:{}".format(coverDiv.find("img").get("src")) meta = html.find("div", {"class": "gallery"}) title = self.getMetaInfo(meta.find("h1")) artist = self.getAllMetaInfo(meta.find("h2")) meta = meta.find("div", {"class": "gallery-info"}) infoTypes = [ "Group", "Type", "Language", "Series", "Characters", "Tags" ] infoIsMultiple = [False, False, False, False, True, True] infoResults = [] infoLists = meta.find_all("tr") for i in range(len(infoTypes)): info = infoLists[i] if infoIsMultiple[i]: infoResults.append(self.getAllMetaInfo(info.find_all("td")[1])) else: infoResults.append(self.getMetaInfo(info.find_all("td")[1])) em = discord.Embed(title=title, url=url, colour=0xDEADBF) em.set_image(url=coverUrl) em.add_field(name="Artist", value=artist) for i in range(len(infoTypes) - 1): em.add_field(name=infoTypes[i], value=infoResults[i]) em.description = "Tags\n{}".format(infoResults[-1]) msg = await self.bot.send_message(ctx.message.channel, embed=em) # Check Type if infoResults[1] == "anime": emojiMenu = ["❌"] else: emojiMenu = ["▶", "❌"] for emoji in emojiMenu: await self.bot.add_reaction(msg, emoji) res = await self.bot.wait_for_reaction(emojiMenu, timeout=30, user=ctx.message.author, message=msg) if not res: for emoji in emojiMenu: await self.bot.remove_reaction(msg, emoji, self.bot.user) await self.bot.remove_reaction(msg, emoji, ctx.message.author) return elif res.reaction.emoji == "▶": await self.bot.delete_message(msg) url = "https://hitomi.la/reader/{}.html".format(index) http = HTTPHandler() response = http.get(url, None) html = BeautifulSoup(response.read().decode(), 'html.parser') images = html.find_all("div", {"class": "img-url"}) reader = discord.Embed(colour=0xDEADBF) reader.title = em.title reader.url = em.url await self.readHitomi(ctx.message, index, images, reader) return elif res.reaction.emoji == "❌": await self.bot.delete_message(msg) await self.bot.delete_message(ctx.message) return
async def 얼굴인식(self, ctx, args): EMOTION = dict() EMOTION["angry"] = "화난" EMOTION["disgust"] = "혐오감을 느끼는" EMOTION["fear"] = "공포를 느끼는" EMOTION["laugh"] = "웃고 있는" EMOTION["neutral"] = "무표정인" EMOTION["sad"] = "슬픈" EMOTION["surprised"] = "놀란" EMOTION["smile"] = "미소짓고 있는" EMOTION["talking"] = "말하고 있는" GENDER = {"male": "남자", "female": "여자", "child": "어린애"} await self.bot.send_typing(ctx.message.channel) tempDir = os.path.join( os.path.split(os.path.dirname(__file__))[0], "temp", "faceRecog.png") url_face = "https://openapi.naver.com/v1/vision/face" url_celebrity = "https://openapi.naver.com/v1/vision/celebrity" f = open(tempDir, "wb") http = HTTPHandler() image_url = args image = http.get(image_url, headers={"User-Agent": "Mozilla/5.0"}) f.write(image.read()) f.close() file = {"image": open(tempDir, "rb")} response_face = requests.post(url_face, files=file, headers=self.naverClient) rescode_face = response_face.status_code response_face = json.loads(response_face.text) file = {"image": open(tempDir, "rb")} response_celebrity = requests.post(url_celebrity, files=file, headers=self.naverClient) rescode_celebrity = response_celebrity.status_code response_celebrity = json.loads(response_celebrity.text) if (rescode_celebrity == 200 and rescode_face == 200): em = discord.Embed(title="얼굴인식 결과에용", colour=0xDEADBF) em.set_image(url=args) if response_celebrity["info"]["faceCount"]: celebrity = response_celebrity["faces"][0]["celebrity"] em.add_field(name="닮은꼴 연예인", value="**{}**을(를) 닮았어용!({:.1f}%)".format( celebrity["value"], 100 * celebrity["confidence"])) if response_face["info"]["faceCount"]: age = response_face["faces"][0]["age"] em.add_field(name="나이", value="**{}**살 같아용!({:.1f}%)".format( age["value"], 100 * age["confidence"])) gender = response_face["faces"][0]["gender"] em.add_field(name="성별", value="**{}**인 것 같아용!({:.1f}%)".format( GENDER[gender["value"]], 100 * gender["confidence"])) emotion = response_face["faces"][0]["emotion"] em.add_field(name="감정", value="**{}** 것 같아용!({:.1f}%)".format( EMOTION[emotion["value"]], 100 * emotion["confidence"])) await self.bot.send_message(ctx.message.channel, embed=em) else: if (rescode_face != 200): await self.bot.say("얼굴인식에 실패했어용: {}".format( response_face["errorMessage"])) elif (rescode_celebrity != 200): await self.bot.say("얼굴인식에 실패했어용: {}".format( response_celebrity["errorMessage"])) await self.bot.delete_message(ctx.message)
async def 메타(self, ctx, *args): if len(args) == 0: await self.bot.say("검색할 내용을 추가로 입력해주세용") return await self.bot.send_typing(ctx.message.channel) searchText = " ".join([arg for arg in args]) encText = urllib.parse.quote(searchText.encode("utf-8")) baseUrl = "http://www.metacritic.com" searchUrl = "{}/search/all/{}/results".format(baseUrl, encText) headers = {} headers[ "User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" http = HTTPHandler() try: response = http.get(searchUrl, headers) except URLError: await self.bot.say("문서가 존재하지 않아용") return html = BeautifulSoup(response.read().decode(), "html.parser") results = html.find("ul", {"class": "search_results"}) if not results: recommendation = html.find("div", { "class": "search_results" }).find('a').get_text() await self.bot.say( "검색결과가 존재하지 않아용, 혹시 **{}**을(를) 검색하려던거 아닌가용?".format( recommendation)) else: results = results.find_all("li") pages = list() for result in results: stats = result.find("div", {"class": "main_stats"}) score = stats.find("span", {"class": "metascore_w"}) if not score: continue score = score.get_text() title = stats.find("h3", { "class": "product_title" }).get_text().strip() url = stats.find("h3", { "class": "product_title" }).find('a')['href'] url = "{}{}".format(baseUrl, url) genre = stats.find("p").get_text().strip() desc = result.find("p", {"class": "basic_stat"}) if desc: desc = desc.get_text() if genre.count('\n'): genres = genre.split('\n') platform = genres[0] type_year = genres[2].strip().split(',') genre = "{}[{}]".format(type_year[0], platform) year = type_year[1].lstrip() else: year = genre.split(',')[1].lstrip() genre = genre.split(',')[0] thumb = result.find("img")['src'] try: score = int(score) if score > 60: color = 0x66cc33 elif score > 40: color = 0xffcc33 else: color = 0xff0000 except ValueError: color = Embed.Empty page = Page(title=title, desc=desc, url=url, thumb=thumb, color=color) page.add_field('score', "**{}**".format(score)) page.add_field('genre', genre) page.add_field('year', year) pages.append(page) session = Session(self.bot, ctx.message, pages, show_footer=True) await session.start()
def getHtml(self, url): http = HTTPHandler() response = http.get(url, self.headers) html = str(response.read()) return html