def playtime(self, stat): nickname = stat["nickname"] encodedNickname = urllib.parse.quote(nickname.encode("utf-8")) red = int(stat["time_red"] * 100 / stat["time_total"]) blue = int(stat["time_blue"] * 100 / stat["time_total"]) spec = int(stat["time_spectate"] * 100 / stat["time_total"]) redStr = self.timeToString(self.parseTime(stat["time_red"])) blueStr = self.timeToString(self.parseTime(stat["time_blue"])) specStr = self.timeToString(self.parseTime(stat["time_spectate"])) chartUrl = ["https://image-charts.com/chart?cht=p"] chartUrl.append("chtt={}'s+Playtime".format(stat["nickname"])) chartUrl.append("chs=300x300") chartUrl.append("chd=t:{},{},{}".format(red, blue, spec)) chartUrl.append("chl={}|{}|{}".format(redStr, blueStr, specStr)) chartUrl.append("chds=a") chartUrl.append("chdl=Red|Blue|Spectate") chartUrl.append("chco=FF6347,4169E1,757575") chartUrl = "&".join(chartUrl) author = AuthorInfo( name="{}{}의 스텟 정보에용".format(stat["clan"], nickname), url="http://gg2statsapp.appspot.com/profile?id={}".format( encodedNickname), icon_url="http://gg2statsapp.appspot.com/avatar?nickname={}". format(encodedNickname)) return Page(image=chartUrl, authorInfo=author, footer_format="플레이타임(%index/%total)")
def checkUnorderedArticles(self, dom, title, url): articles = [] for article in dom.find_all("p", recursive=False): if article.name == "p": if article.find("div"): break desc = article.get_text()[:2000] if desc: page = Page(title=title, desc=desc, url=url, footer_format="") articles.append(page) elif article.name == "ul": self.sanitizeUl(article) desc = article.get_text()[:2000] if desc: page = Page(title=title, desc=desc, url=url, footer_format="") articles.append(page) return articles
async def readHitomi(self, cmdMsg, index, images, em): images = [image.string for image in images] images = [image[image.rfind("/") + 1:] for image in images] if index % 2: url = "https://ba.hitomi.la/galleries/{}/{}" else: url = "https://aa.hitomi.la/galleries/{}/{}" images = [Page(image=url.format(index, image)) for image in images] session = Session(self.bot, cmdMsg, images, max_time=60, show_footer=True) await session.start()
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()
async def 이미지(self, ctx, *args): await self.bot.send_typing(ctx.message.channel) if len(args) == 0: await self.bot.say("검색어를 추가로 입력해주세용") return searchText = " ".join([arg for arg in args]) encText = urllib.parse.quote(searchText.encode('utf-8')) url = "https://www.google.co.kr/search?q={}&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg".format( encText) html = self.getHtml(url) images = self.findAllImages(html) if not images: self.bot.say("검색 결과가 없어용") return pages = [Page(image=image) for image in images] session = Session(self.bot, ctx.message, pages, show_footer=True) await session.start()
def classinfo(self, stat): nickname = stat["nickname"] encodedNickname = urllib.parse.quote(nickname.encode("utf-8")) classes = [ "runner", "firebug", "rocketman", "overweight", "detonator", "healer", "constructor", "infiltrator", "rifleman", "quote" ] killData = [] for cls in classes: killData.append(str(stat["{}_kill".format(cls)])) killData = ",".join(killData) deathData = [] for cls in classes: deathData.append(str(stat["{}_death".format(cls)])) deathData = ",".join(deathData) assistData = [] for cls in classes: assistData.append(str(stat["{}_assist".format(cls)])) assistData = ",".join(assistData) classData = [killData, deathData, assistData] classData = "|".join(classData) chartUrl = ["https://image-charts.com/chart?cht=bhs"] chartUrl.append("chs=600x300") chartUrl.append("chd=t:{}".format(classData)) chartUrl.append("chdl=Kill|Death|Assist") chartUrl = "&".join(chartUrl) author = AuthorInfo( name="{}{}의 스텟 정보에용".format(stat["clan"], nickname), url="http://gg2statsapp.appspot.com/profile?id={}".format( encodedNickname), icon_url="http://gg2statsapp.appspot.com/avatar?nickname={}". format(encodedNickname)) return Page(image=chartUrl, authorInfo=author, footer_format="클래스별 정보(%index/%total)")
def overall(self, stat): nickname = stat["nickname"] encodedNickname = urllib.parse.quote(nickname.encode("utf-8")) region = stat["region"][:2].lower() kda = (stat["kill"] + stat["assist"]) / max(stat["death"], 1) h, m, d = self.parseTime(stat["time_total"]) thumb = "http://gg2statsapp.appspot.com/avatar?nickname={}".format( encodedNickname) desc = [] desc.append(":flag_{}:".format(region)) if stat["title"]: desc.append("\"{}\"".format(stat["title"])) desc.append( "`LEVEL` **{}** `EXP` **{}** / **{}** `COIN` **{}**".format( stat["level"], stat["exp"], self.maxExp(stat["level"]), stat["coin"])) desc.append("**{}**시간 **{}**분 **{}**초동안 **{}**판 플레이".format( h, m, d, stat["playcount"])) desc.append( "🔫: **{}**, 💀: **{}**, 🤝: **{}**, `KDA`: **{:.2f}**".format( stat["kill"], stat["death"], stat["assist"], kda)) desc.append("🚩: **{}**, 🛡️: **{}**, 💥: **{}**".format( stat["capture"], stat["defense"], stat["destruction"])) desc.append("🗡️: **{}**, ♥️: **{}**, 🌟: **{}**".format( stat["stab"], self.strlize(stat["healing"]), stat["invuln"])) desc.append("**{}**`승` **{}**`패` **{}**`비김` **{}**`탈주`".format( stat["win"], stat["lose"], stat["draw"], stat["disconnect"])) desc = "\n".join(desc) author = AuthorInfo( name="{}{}의 스텟 정보에용".format(stat["clan"], nickname), url="http://gg2statsapp.appspot.com/profile?id={}".format( encodedNickname), icon_url="http://gg2statsapp.appspot.com/avatar?nickname={}". format(encodedNickname)) return Page(desc=desc, authorInfo=author, thumb=thumb, footer_format="종합정보(%index/%total)")
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()