async def sentry_callback(request: Request): data = await request.json() title = data["data"]["issue"]["title"] author = {"name": data["action"]} description = (f"Issue id: {data['data']['issue']['id']}\n" f"Times seen: {data['data']['issue']['count']}\n" f"Errored at: {data['data']['issue']['culprit']}") timestamp = datetime.datetime.strptime(data["data"]["issue"]["lastSeen"], "%Y-%m-%dT%H:%M:%S.%fZ") footer = { "text": "Last seen at:", "icon_url": "https://cdn.discordapp.com/avatars/698366484975714355/9bad78779883b3bd6dfd4022d997e406.png", } embed = Embed( title=title, author=author, description=description, timestamp=timestamp, footer=footer, ) if request.app.state.webhook_url: await request.app.state.client.post(request.app.state.webhook_url, json={"embeds": [embed.to_dict()]}) return Response(status_code=204)
async def get_info_embed(self, ctx : commands.Context, setting : str): doc = await self.config[setting].find_one({"_id": ctx.guild.id}) if doc: description = "" for k, v in doc.items(): if k == "_id": continue try: role = ctx.guild.get_role(v) if role: v = role.mention except AttributeError: pass try: channel = ctx.guild.get_channel(v) if channel: v = channel.mention except AttributeError: pass description += f"{k.capitalize()}: {v}\n" embed = Embed(self.bot, ctx.author, title=setting.capitalize() + " info", description=description) else: embed = Embed(self.bot, ctx.author, title=setting.capitalize() + " info", description="On: False") await embed.set_requested_by_footer() return embed
async def check(self, ctx, username: str): name, uuid = await fetch_uuid_uname(username) if not uuid: return await ctx.send("Could not find that username") scammer = await self.bot.scammer_db["scammer_list"].find_one( {"_id": uuid}) if not scammer: embed = Embed( title="Safe", description= "This user is not in our database as a scammer. Proceed with caution", bot=self.bot, user=ctx.author) embed.color = 0x00FF00 await embed.set_requested_by_footer() return await ctx.send(embed=embed) if scammer["report_id"] and not scammer["anonymous"]: report = await self.bot.scammer_db["reports"].find_one( {"_id": scammer["report_id"]}) if not report["anonymous"]: footer_text = f"reported by {report['reporter']}, confirmed by {scammer['mod']}" else: footer_text = f"reported anonymously, confirmed by {scammer['mod']}" else: footer_text = f"added by {scammer['mod']}" embed = discord.Embed(title="SCAMMER", description=scammer["reason"], color=0xff0000).set_footer(text=footer_text) await ctx.send(embed=embed)
async def cat_page(self, ctx, cat): showlist = [] for c in ctx.bot.commands: if c.hidden: continue help_str = c.help if help_str: if "|" in help_str: c_cat = help_str.split("|")[0] if c_cat.lower() == cat.lower(): showlist.append([c.name, " | ".join(c.aliases), True]) showlen = len(showlist) if showlen % 10 == 0: lastpage = int(showlen / 10) else: lastpage = int(showlen / 10) + 1 showlist.sort() title = f"[Amathy v1.8] - Help - {cat.title()} category page" desc = f"You have accessed the instruction manual.\nBelow are commands from the `{cat.title()}` category." if not showlist: footer = "1/1 - To see more details about a command, use ama help [command]." emb = Embed().make_emb(title, desc, footer=footer, empty_field=True) return await ctx.send(embed=emb) embeds = [] for i in range(1, lastpage + 1): fields = [] for j in range((i - 1) * 10, (i * 10) - 1): if not j < showlen: break fields.append(showlist[j]) footer = "{}/{} - To see more details about a command, use ama help [command].".format(i, lastpage) embed = Embed().make_emb(title, desc, None, fields, footer, empty_field=True) embeds.append(embed) await self.bot.funx.embed_menu(ctx, embeds)
async def slist(self, ctx): Embeds = [] Embeds.append( Embed(title="Bot changelogs", bot=self.bot, user=ctx.author)) count = 0 async for change in self.bot.admin_db["changelog"].find({}): if not count % 7 and count != 0: Embeds.append([ Embed(title="Bot changelogs", bot=self.bot, user=ctx.author) ]) #print(Embeds[len(Embeds) - 1]) Embeds[len(Embeds) - 1].add_field( name=f"{change['type']} {change['version']}", value=datetime.fromtimestamp( change['date']).strftime("%m/%d/%y")) count += 1 print(count) if not count == 0: msg = await ctx.send(embed=Embeds[0]) if count > 0: pages = Paginator(self.bot, msg, embeds=Embeds, timeout=60, use_more=True, only=ctx.author) await pages.start() else: return await ctx.send("Could not find any changelogs")
async def get_events_embed(self, ctx, events): embed = Embed(self.bot, ctx.author, title="All Timed Events", description="'on:' is utc+0") await embed.set_made_with_love_footer() for event in events: event_in, event_on = self.get_times(event) embed.add_field(name=event.event_name, value=f"In: {event_in}\nOn: {event_on}", inline=False) return embed
async def reminder(self, ctx, seconds: typing.Union[int], *, reason=None): if not seconds >= 0: raise commands.BadArgument() if reason is not None: embed = Embed.check( title="리마인더", description="리마인더에 기록 완료했어요! %s초 있다가 `%s`하라고 알려드릴께요!" % (str(seconds), reason), ) else: embed = Embed.check( title="리마인더", description="리마인더에 기록 완료했어요! %s초 있다가 알려드릴께요!" % (str(seconds)), ) embed.set_footer(text="봇이 꺼지면 초기화됩니다!") await ctx.send(embed=embed) await asyncio.sleep(seconds) await ctx.send(ctx.author.mention) embed = discord.Embed(title="⏰ 알림", description="시간이 다 되었어요!", color=0x1DC73A) if reason is not None: embed.add_field(name="내용", value=reason) await ctx.send(embed=embed)
async def on_command_error(self, ctx, error): if isinstance(error, commands.CheckFailure): return if isinstance(error, commands.errors.CommandNotFound): return if isinstance(error, commands.CommandOnCooldown): embed = discord.Embed( title="⚠ 쿨타임 중!", description="{}초 뒤에 재시도하세요.".format(int(error.retry_after)), color=0xD8EF56, ) return await ctx.send(embed=embed) if isinstance(error, commands.CommandInvokeError): original = error.original if isinstance(original, discord.Forbidden): embed = Embed.warn( "주의", "봇의 권한이 부족하여 {} 명령어를 수행할 수 없어요.".format(ctx.command.name), ) return await ctx.send(embed=embed) if ( isinstance(error, commands.BadArgument) or isinstance(error, commands.BadUnionArgument) or isinstance(error, commands.MissingRequiredArgument) ): name = str(ctx.command) try: embed = Embed.warn( "주의", "잘못된 형식으로 명령어를 사용했어요. \n올바른 사용 : `봇 {} {}`".format( name, self.argument_data[name] ), ) return await ctx.send(embed=embed) except KeyError: embed = Embed.warn("주의", "잘못된 형식으로 명령어를 사용했어요.") return await ctx.send(embed=embed) embed = Embed.error( "이런!", "{} 명령어 수행 중 핸들링 되지 않은 오류가 발생했어요!\n```{}```\n지속적인 문제 발생 시 `봇 문의` 명령어로 문의해주세요.".format( ctx.command.name, error ), ) await ctx.send(embed=embed) print( "Ignoring exception in command {}".format(ctx.command), file=sys.stderr, ) traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr ) self.logger.warning( "Error {} occured in command {}".format( type(error), ctx.command.name ) )
async def get_skills_embed(self, ctx, player): player.load_skills_slayers(False) if not player.enabled_api["skills"]: return await Embed( self.bot, ctx.author, title="Error", description= "Your skills API is disabled. Please enable it and try again." ).set_requested_by_footer() name = self.format_name(player.uname) embed = Embed( self.bot, ctx.author, title=f"{name} Skills on {player.profile_name}", description=f"Average skill level: {player.skill_average}") await embed.set_requested_by_footer() for name, level in player.skills.items(): embed.add_field( name=f"{skill_icons[name]} {name.capitalize()} Level", value= f"**LEVEL {level}**\n{player.skill_xp[name]:,}XP total\n{player.skills_needed_xp[name]:,}XP to next level" ) return embed
async def show_command(self, ctx, arg): if isinstance(arg, commands.Command): command = arg elif isinstance(arg, str): command = self.bot.get_command(arg) if has_is_staff(command) and not is_staff(ctx): raise commands.BadArgument(message="Command or Category not found") if command.parents: command_embed = Embed(title=f"{ctx.prefix}{' '.join([command.name.capitalize() for command in command.parents])} {command.name.capitalize()}", bot=self.bot, user=ctx.author) else: command_embed = Embed(title=f"{ctx.prefix}{command.name.capitalize()}", bot=self.bot, user=ctx.author) await command_embed.set_requested_by_footer() if command.description == "": description = "No Description." else: description = command.description if command.usage is None: usage = "No Usage." elif command.parents: usage = f"{ctx.prefix}{' '.join([command.name.capitalize() for command in command.parents])} {command.name.capitalize()} {command.usage}" else: usage = f"{ctx.prefix}{command.name.capitalize()} {command.usage}" if command.aliases == []: aliases = "No Aliases." else: aliases = str(command.aliases).replace("[", " ").replace("]", " ").replace("'", " ").replace(",", "\n") command_embed.add_field(name="Description", value=description, inline=False) command_embed.add_field(name="Usage", value=usage, inline=False) command_embed.add_field(name="Aliases", value=aliases, inline=False) await ctx.send(embed=command_embed)
async def get_event_embed(self): embed = Embed(self.bot, None, title="Timed Events") await embed.set_patron_footer() for event in self.bot.events: event.update_without_api() embed.add_field(name=event.event_name, value=f"Event in:\n**{str(event.event_in)[:-7]}**") return embed
async def avatar(self, ctx, target: MemberConverter = None): """Info|Returns a user's avatar.|""" if not target: target = ctx.author avatartext = "**👉 |** ***{} - avatar.***".format(target.name) emb = Embed().make_emb("", avatartext) emb.set_image(url=target.avatar_url) await ctx.send(embed=emb)
async def join(self, ctx): if not ctx.message.author.voice: embed = Embed.warn(title="먼저 음성 채널에 들어와주세요!") return await ctx.send(embed=embed) await self.bot.Wonstein.connect(ctx.message.author.voice.channel) embed = Embed.default( title=f"성공적으로 {ctx.message.author.voice.channel}에 연결했습니다.") await ctx.send(embed=embed)
async def invite(self, ctx): embed = Embed(title="Invite the bot to your server", bot=self.bot, user=ctx.author) embed.add_field( name="--------------------------------", value= f"The bot already is on {len(self.bot.guilds)} Guilds!\n[Click Here to invite the Bot]({self.bot.config['bot_invite']})" ) await embed.set_made_with_love_footer() await ctx.send(embed=embed)
async def changelog_embed(self, ctx, json_doc): embed = Embed( title=f"Changelogs for {json_doc['type']} `{json_doc['version']}`", description=json_doc["description"], bot=self.bot, user=ctx.author) embed.add_field(name="Bugs/plans", value=json_doc["bugs"], inline=False) embed.timestamp = datetime.fromtimestamp(json_doc["date"]) await embed.set_made_with_love_footer() return embed
async def price(self, ctx, *, name:str): await ctx.trigger_typing() async with aiohttp.ClientSession() as session: async with session.get("https://api.slothpixel.me/api/skyblock/items") as resp: item_data = await resp.json() names = {item_data[z]["name"].lower(): z for z in item_data} results = {} bazaar_results = {} matches = {z: y for (z, y) in names.items() if name.lower() in z.lower()} async with aiohttp.ClientSession() as session: for i, item in enumerate(matches): if i < 5: async with session.get(f"https://api.slothpixel.me/api/skyblock/auctions/{matches[item]}{self.bot.slothpixel_key_string}") as resp: if not (await resp.json())["average_price"]: pass else: results[item] = await resp.json() async with session.get(f"https://api.slothpixel.me/api/skyblock/bazaar/{matches[item]}") as resp: r = await resp.json() if "error" not in r: bazaar_results[item] = r if len(matches) < 5: string = f"showing all {len(results) + len(bazaar_results)} results" else: string = f"showing {len(results) + len(bazaar_results)} of {len(matches)} results." embed = Embed(self.bot, ctx.author, title=f"Price search for {name}", description=f"{string}\nAuction Items: {len(results)}\nBazaar Items: {len(bazaar_results)}") embeds = [embed] if not (results or bazaar_results): return await ctx.send(embed=discord.Embed(title=":x: Item not found!", description="No price could be found for that search on the auction house or bazaar", color=discord.Color.red())) if len(results) + len(bazaar_results) == 1: if results: result = list(results.keys())[0] return await ctx.send(embed=Embed(self.bot, ctx.author, title=f"Price of {result} on auction", description=f"Average Price: {results[result]['average_price']}\nPrice range: {results[result]['min_price']} - {results[result]['max_price']}")) else: result = list(bazaar_results.keys())[0] flip = round((bazaar_results[result]['buy_summary'][0]['pricePerUnit'] / bazaar_results[result]['sell_summary'][0]['pricePerUnit']) * 100) - 100 await ctx.send(embed=Embed(self.bot, ctx.author, title=f"Price of {result} at the Bazaar", description=f"Instant buy price: {round(bazaar_results[result]['buy_summary'][0]['pricePerUnit'])}\nInstant sell price: {round(bazaar_results[result]['sell_summary'][0]['pricePerUnit'])}\nProfit Margin: {flip}%")) for i, result in enumerate(results): if "texture" in item_data[names[result]]: url = f"https://sky.lea.moe/head/{item_data[names[result]]['texture']}" else: url = '' embeds.append(Embed(self.bot, ctx.author, title=f"Price of {result} on auction", description=f"Average Price: {results[result]['average_price']}\nPrice range: {results[result]['min_price']} - {results[result]['max_price']}").set_footer(text=f"page {i + 1} of {len(results) + len(bazaar_results)}").set_thumbnail(url=url)) for i, result in enumerate(bazaar_results): if "texture" in item_data[names[result]]: url = f"https://sky.lea.moe/head/{item_data[names[result]]['texture']}" else: url = '' flip = round((bazaar_results[result]['buy_summary'][0]['pricePerUnit'] / bazaar_results[result]['sell_summary'][0]['pricePerUnit']) * 100) - 100 embeds.append(Embed(self.bot, ctx.author, title=f"Price of {result} at the Bazaar", description=f"Instant buy price: {round(bazaar_results[result]['buy_summary'][0]['pricePerUnit'])}\nInstant sell price: {round(bazaar_results[result]['sell_summary'][0]['pricePerUnit'])}\nProfit Margin: {flip}%").set_footer(text=f"page {len(results) + i + 1} of {len(results) + len(bazaar_results)}").set_thumbnail(url=url)) msg = await ctx.send(embed=embeds[0]) pages = Paginator(self.bot, msg, embeds=embeds, timeout=60, use_more=True, only=ctx.author) await pages.start()
async def serverinfo(self, ctx, guild : discord.Guild=None): if not guild: guild = ctx.guild if not guild: return await ctx.send("Guild not found") embed = Embed(self.bot, ctx.author, title=guild.name) await embed.set_requested_by_footer() for setting in self.settings: info = await self.get_info(ctx, guild, setting) embed.add_field(name=setting.capitalize(), value=info) await ctx.send(embed=embed)
async def delete_message(self, ctx, amount: typing.Union[int]): if amount > 0 and amount <= 100: deleted_message = await ctx.channel.purge(limit=amount) embed = Embed.check( title="메시지 삭제", description="%s개의 메시지를 지웠어요." % len(deleted_message), ) await ctx.send(embed=embed, delete_after=3) else: embed = Embed.warn(title="오류 발생", description="지우는 메시지의 개수는 1개~100개여야 해요.") await ctx.send(embed=embed, delete_after=3)
async def get_list_embed(self, ctx, expanded=False): staff = is_staff(ctx) list_embed = Embed(title="Categories", bot=self.bot, user=ctx.author) list_embed.set_author(name=f"Use {ctx.prefix}help [Command/Category]") await list_embed.set_requested_by_footer() for name, cog in self.bot.cogs.items(): if name == "Admin" or name == "Help": continue if not cog.get_commands(): continue commands = [] for command in cog.get_commands(): if has_is_staff(command) and not staff: continue if hasattr(command, "commands") and expanded: sub_cmds = [command.name for command in command.commands if not has_is_staff(command) or staff] if sub_cmds: commands.append(f"`{command.name}` *({'*, *'.join(sub_cmds)})*") else: commands.append(f"`{command.name}`") else: commands.append(f"`{command.name}`") list_embed.add_field(name=name, value=", ".join(commands), inline=False) list_embed.add_field(name="Links", value="[Contribute](https://discord.gg/zqRsduD2JN) | [Vote](https://top.gg/bot/630106665387032576/vote) | [Invite the Bot to your server](https://discordapp.com/oauth2/authorize?client_id=630106665387032576&scope=bot%20applications.commands&permissions=8) | [Support Server](https://discord.gg/7fPv2uY2Tf) | [Todos](https://trello.com/b/2yBAtx82/skybot-rewrite) | [GitHub repo](https://github.com/Skybot-dev/Skybot-rewrite)", inline=False) return list_embed
async def stats(self): config = self.bot.config["support_guild"] guild = self.bot.get_guild(config["ID"]) config = config["stats"] channel = guild.get_channel(config["channel"]) message = await channel.fetch_message(config["message"]) guilds = self.bot.guilds members = 0 for guild in guilds: members += len(guild.members) guild_members = [] for guild in guilds: guild_members.append(len(guild.members)) guilds_sorted = sorted(guild_members, reverse=True)[:10] guilds_sorted_str = [ str(place + 1) + ". " + str(guild) for place, guild in enumerate(guilds_sorted) ] final_list = "\n".join(guilds_sorted_str) embed = Embed(title="Statistics", bot=self.bot, user=None) embed.add_field(name="Servers:", value=len(guilds), inline=False) embed.add_field(name="Members:", value=members, inline=False) embed.add_field(name="Top 10 Member count:", value=final_list, inline=False) await embed.set_made_with_love_footer() await message.edit(embed=embed)
async def shop(self, ctx): """Fun|See the shop. Buy or leave?|""" emb_links_perm = ctx.channel.permissions_for(ctx.me).embed_links if not emb_links_perm: return await ctx.send( "I need the `embed_links` permission to show you the shop.") # xpu = await funx.get_xp(u.id) # lv = funx.get_lvl(xpu) page_1 = Embed().make_emb( title="[Coin Shop] >>> Amathy sells:", desc="The following can be bought with coins.", footer="Page 1/2 - To buy something, type a buy [item]") page_2 = Embed().make_emb( title="[Gem Shop] >>> Amathy sells:", desc="The following can be bought with gems.", footer="Page 2/2 - To buy something, type a buy [item]") for item in self.shop: price = item["price"] # if lv > 0: # price = price * lv curr = item["currency"] field = " | ".join(item["name"]) field_str = self.bot.funx.group_digit(price) if curr == "coins": page_1.add_field(name=field, value=f"{field_str} coins", inline=True) else: page_2.add_field(name=field, value=f"{field_str} gems", inline=True) await self.bot.funx.embed_menu(ctx, [page_1, page_2])
async def show_cog(self, ctx, arg): cogs = {z.lower(): self.bot.cogs[z] for z in self.bot.cogs} cog : commands.Cog = cogs[arg] cog_embed = Embed(title=arg.capitalize() + " Help", bot=self.bot, user=ctx.author) await cog_embed.set_requested_by_footer() for command in cog.get_commands(): if command.description == "": description = "No Description." else: description = command.description cog_embed.add_field(name=command.name, value=description, inline=True) await ctx.send(embed=cog_embed)
async def list_reminder(self, ctx, user: discord.abc.User=None): if not user: user = ctx.author embed = Embed(self.bot, ctx.author, title=f"{str(user)} reminders") await embed.set_made_with_love_footer() docs = self.reminders.find({"id" : user.id}) async for doc in docs: event = self.get_event(TimedEvent(doc["event"])) event_in = str(event.event_in - timedelta(minutes=5))[:-7] if event.event_in.microseconds else event.event_in embed.add_field(name=f"Reminder for {event.event_name}", value=f"Will be reminded in {event_in}") if len(embed.fields) > 0: await ctx.send(embed=embed) else: await ctx.send(f"{str(user)} has no reminders set.")
async def qna(self, ctx, *, args): msg = await ctx.send( "정말로 전송할까요? 의미 없는 내용을 전송하시면 **블랙추가** 됨을 확인해주세요.\n전송을 원하시면 ✅ 를 눌러주세요." ) await msg.add_reaction("✅") def posi_check(reaction, user): # if user.is_bot: return False return (user == ctx.author and str(reaction.emoji) == "✅" and msg.id == reaction.message.id) answer = await self.bot.wait_for("reaction_add", check=posi_check, timeout=10) bgm = self.bot.get_user(289729741387202560) embed = discord.Embed( title="❔ 건의가 도착했어요!", description=args, color=0x1DC73A, timestamp=datetime.datetime.utcnow(), ) embed.set_footer( icon_url=ctx.author.avatar_url, text="{} / {}".format(ctx.author, ctx.author.id), ) await bgm.send(embed=embed) embed = Embed.check(title="성공", description="건의 전송을 성공했어요!") await ctx.send(embed=embed)
async def get_defs_by_author(self, def_author): def_author_id = def_author.id script = f"select def_name, def_global from amathy.definitions where def_author_id={def_author_id}" data = await self.bot.funx.fetch_many(script) if not data: return None showlen = len(data) if showlen % 10 == 0: lastpage = int(showlen / 10) else: lastpage = int(showlen / 10) + 1 embeds = list() title = f"{def_author.name}'s list of definitions [{showlen}]" desc = f"Here are {def_author.name}'s definitions:" for i in range(1, lastpage + 1): fields = [] for j in range((i - 1) * 10, (i * 10) - 1): if not j < showlen: break def_status = "• local" if data[j]["def_global"]: def_status = "• global" fields.append([data[j]["def_name"], def_status, True]) footer = "{}/{} - To see a definition, use ama define [definition].".format( i, lastpage) embed = Embed().make_emb(title, desc, None, fields, footer) embeds.append(embed) return embeds
async def submit(self, ctx, *, answer: str): embed = Embed(description=answer, bot=self.bot, user=ctx.author).set_author( name=ctx.author, icon_url=ctx.author.avatar_url) supportConfig = self.bot.config["support_guild"] suggestionChannel = self.bot.get_guild( supportConfig["ID"]).get_channel(supportConfig["suggest_channel"]) msg = await suggestionChannel.send(embed=embed) await msg.add_reaction(u"\u2705") await msg.add_reaction(u"\u274E") await ctx.send( f"Suggestion logged. Join the support server with `{ctx.prefix}support` to see it." ) await ctx.message.delete() if self.trelloEnabled: card_id = self.my_lists[0].add_card(answer).id else: card_id = None suggestion_doc = await self.bot.admin_db["suggestions"].insert_one({ "status": "submitted", "user": ctx.author.id, "content": answer, "message": msg.id, "datetime": time.time(), "card": card_id }) await msg.edit(embed=msg.embeds[0].set_footer( text=f"ID: {str(suggestion_doc.inserted_id)}"))
async def kick(self, ctx, member: discord.Member): await ctx.guild.kick(member, reason=str(ctx.author) + "님의 명령어 사용으로 인해 킥 당하셨습니다.") embed = Embed.check(title="멤버 킥", description="선택한 유저를 추방했어요.") await ctx.send(embed=embed)
async def fine_dust(self, ctx, *, args=None): params = { "serviceKey": CONFIG.MISAE, "numOfRows": 1, "pageSize": 1, "pageNo": 1, "startPage": 1, "itemCode": "PM10", "dataGubun": "HOUR", } misae_c = await HTTP.get( url= "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureLIst", params=params, ) soup = BeautifulSoup(misae_c, "lxml-xml") misae_sido = self._handle_pm(soup) params["itemCode"] = "PM25" chomisae_c = await HTTP.get( url= "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureLIst", params=params, ) soup = BeautifulSoup(chomisae_c, "lxml-xml") chomisae_sido = self._handle_pm(soup) embed = discord.Embed( title="💨 미세먼지", desciption="<미세먼지>\n<초미세먼지> 로 알려드려요.", color=0x1DC73A, ) embed.set_footer(text=f"에어코리아 | {misae_sido['date']}") if args is None: for i in misae_sido["sido"].keys(): embed.add_field( name=i, value= f"{misae_sido['sido'][i]}㎍/m³ | {self._checkpm10(misae_sido['sido'][i])}\n{chomisae_sido['sido'][i]}㎍/m³ | {self._checkpm25(chomisae_sido['sido'][i])}", inline=True, ) await ctx.send(embed=embed) else: if args in misae_sido["sido"].keys(): embed.add_field( name=args, value= f"{misae_sido['sido'][args]}㎍/m³ | {self._checkpm10(misae_sido['sido'][args])}\n{chomisae_sido['sido'][args]}㎍/m³ | {self._checkpm25(chomisae_sido['sido'][args])}", inline=True, ) await ctx.send(embed=embed) else: embed = Embed.warn( title="주의", description= "선택하신 지역 이름을 찾을 수 없어요.\n`봇 미세먼지` 로 전체 지역을 볼 수 있어요.", ) await ctx.send(embed=embed)
async def stats(self, ctx): """See the logging configuration.""" title = ctx.command.qualified_name author = { "name": ctx.bot.user.name, "icon_url": ctx.bot.user.avatar_url } desc = "You can see your configuration below:" enabled = "No" channel = "None" if check_logging(ctx.guild.id): with open(f"data/guilds/{ctx.guild.id}/logging.json") as f: data = json.load(f) set_chan = int(data["channel_id"]) if not set_chan == 0: enabled = "Yes" channel = self.bot.get_channel(set_chan).mention events_disabled = data["events_disabled"] active_events = "None" inactive_events = "None" if events_disabled: inactive_events = "\n".join(events_disabled) act_ev_list = list() for ev in self.events: if not ev in events_disabled: act_ev_list.append(ev) if act_ev_list: active_events = "\n".join(act_ev_list) fields = [["Enabled", enabled, True], ["Channel", channel, True], ["Enabled events", active_events, False], ["Disabled events", inactive_events, False]] await ctx.send(embed=Embed().make_emb(title, desc, author, fields), )
async def currencyy(self, ctx, origin, target, how: typing.Optional[int] = 1): origin = origin.upper() target = target.upper() async with aiohttp.ClientSession() as session: async with session.get( "https://free.currconv.com/api/v7/convert?q={}_{}&compact=ultra&apiKey=6bc5cad1b80bf7f58aa5" .format(origin, target)) as r: data = await r.json() if data == {}: embed = Embed.error(title="오류", description="잘못된 화폐 단위를 입력하였는지 확인해주세요.") await ctx.send(embed=embed) else: per = data["{}_{}".format(origin, target)] embed = discord.Embed( title="💰 {} {}".format(format(how, ","), origin), description="= {} {}".format(format(how * per, ","), target), color=0x1DC73A, ) await ctx.send(embed=embed)