async def refresh(self, sortie): em = EmbedTemplate(title="Sorties", timestamp=datetime.utcnow()) count = 1 for i in sortie.missions: em.add_field(name=f"Mission {count}", value=str(i)) count += 1 await self.message.edit(embed=em)
async def refresh(self, nightwave_data): em = EmbedTemplate(title="Nightwave", timestamp=datetime.utcnow()) for i in nightwave_data: em.add_field(name=i.name, value=(Utilities.ts2string(i.start_time + (60 * 120)) + "\n\n")) await self.message.edit(embed=em)
def getEmbed(self, ) -> discord.Embed: em = EmbedTemplate( title="Crisscross", description= f"{self.player1[0].mention} :x: vs {self.player2[0].mention} :o:") em.add_field(name="Game", value=str(self.map).replace("x", ":x:").replace( "0", ":o:").replace("-", ":large_blue_diamond:")) return em
async def refresh(self, newswire_data: list[NewswireItem]) -> None: em = EmbedTemplate(title="GTA V Newswire", timestamp=datetime.utcnow(), inline=False) x = 1 for i in newswire_data: em.add_field(name=f"**{x}**. {i.title[:15]}...", value=f"[Link]({i.url})\n\n[Image]({i.image})\n") x += 1 await self.message.edit(embed=em)
def relicSearch(self, searched_value): vals = self.searchKey("relicRewards", searched_value) if len(vals) == 1: em = EmbedTemplate(title=self.data["relicRewards"]["title"], description=vals[0]) for i, j in self.data["relicRewards"]["data"][vals[0]].items(): em.add_field(name=i, value="\n".join(j)) return em else: return EmbedTemplate(title=self.data["relicRewards"]["title"], description="\n".join(vals))
def get_embed(self, ) -> discord.Embed: em = EmbedTemplate(title=self.name.title(), description=f"{self.description}\n\n{self.usage}") if self.stage_drop_list: sanity_costs = self.sanity_cost_per_stage() if sanity_costs: tmp = "" for i in sanity_costs: stage, sanity_per_item, drop_rate = i tmp += f"{stage.code} {sanity_per_item:.2f} Sanity/Item {drop_rate*100:.2f}%\n" em.add_field(name="Drop Rates", value=tmp) return em
async def add_to_queue(self, url): def add_playlist(data, new_songs): for x in data['entries']: song = Song( discord.FFmpegPCMAudio(x['url'], **self.ffmpeg_opts), x['title'], x['duration'], x['view_count'], x['url']) new_songs.append(song) data = await self.loop.run_in_executor( None, lambda: self.ytdl.extract_info(url, download=False)) new_songs = [] if 'entries' in data: await self.loop.run_in_executor( None, lambda: add_playlist(data, new_songs)) else: song = Song( discord.FFmpegPCMAudio(data['url'], **self.ffmpeg_opts), data['title'], data['duration'], data.get('view_count'), data.get('url')) new_songs.append(song) new_songs_str = "" for i in new_songs: if len(new_songs_str) < 1000: new_songs_str += f"[{i.title[:40]}]({i.url}), {datetime.timedelta(seconds=i.duration)} {i.views:,.0f} views\n" else: break self.playlist.extend(new_songs) em = EmbedTemplate(title=f"Added {len(new_songs)} to Playlist", description=new_songs_str) await self.channel.send(embed=em)
async def pause(self, ): if self.vc: if self.vc.is_playing(): em = EmbedTemplate(title="Player Paused", description="resume to continue playing") self.vc.pause() await self.channel.send(embed=em)
async def resume(self, ): if self.vc: if self.vc.is_paused(): em = EmbedTemplate(title="Player Resumed", description="pause to pause again") self.vc.resume() await self.channel.send(embed=em)
async def run(self, message: discord.Message, server: Server): parsed = self.args.parse(message.content) if parsed: tmp = list(self.database.runtime["gfl"]["dolls"]["names"].values()) tmp = [x for x in tmp if x.production_timer] tmp_str = [] for doll in sorted(tmp, key=lambda x: x.production_timer): tmp_str.append( f"{datetime.timedelta(seconds=doll.production_timer)} {doll.name} {doll.doll_type}" ) lists = [tmp_str[i:i + 30] for i in range(0, len(tmp_str), 30)] em = EmbedTemplate(title="Production Dolls") for i in lists: em.add_field(name="PRODUCTION", value="\n".join(i), inline=True) await message.channel.send(embed=em)
async def refresh(self, invasions): em = EmbedTemplate(title="Invasions", timestamp=datetime.utcnow()) for i in invasions: vals = [] if type(i.node) == str: vals.append(f"{i.node.title()}, {i.node.title()}") else: vals.append( f"{i.node.planet.name.title()}, {i.node.name.title()}") vals.append(i.start_time) vals.append(f"{i.defender.faction} vs {i.attacker.faction}"), vals.append(i.status) em.add_field( name=f"{i.defender.rewards} vs {i.attacker.rewards}", value=f"{vals[0]}\n{vals[1]}\n{vals[2]}\n{vals[3]}\n\u200b") await self.message.edit(embed=em)
async def run(self, message: discord.Message, server: Server) -> None: parse = self.args.parse(message.content) if parse: amount = int(parse['amount']) if parse['amount'] else 1 banner = parse['banner'] items = None if banner == "hunter": items = Banners.hunter() if amount > 500: amount = 500 if items: sim = ProtocolAssimilationBanner( ProtocolAssimilationBanner.MONTHLY_SVAROGS) sim.set_names(items) sim.set_prioritize([ "Manticore", "Nemeum", ProtocolAssimilationBanner.PRIORITIZE_WEIGHT ]) total_pulls = 0 total_results = [] for i in range(amount): pulls, results = sim.run() total_pulls += pulls total_results.append(results) sim.reset() combined_results, used_svarogs = self.combine_results( total_results) total_svarogs = sim.svarog_tickets * amount em = EmbedTemplate( title="Sim", description= f"Across {amount} banners, you got:\nTotal pulls: {total_pulls}\nTotal SVAROG tickets used: {used_svarogs}/{total_svarogs}" ) for banner_item_name, banner_item_data in combined_results.items( ): em.add_field(name=banner_item_name, value=f""" {f"Svarogs: {banner_item_data['svarogs']}" if 'svarogs' in banner_item_data else ""} {f"Failures: {banner_item_data['failures']}" if banner_item_data['failures'] > 0 else ""} Successes: {banner_item_data['successes']} Total: {banner_item_data['total']} Got {banner_item_data['successes']}/{banner_item_data['item']._original_amount*amount} """) await message.channel.send(embed=em)
async def run(self, message: discord.Message, server: Server) -> None: def check_author(m: discord.Message): if message.author == m.author: return True return False parse = self.args.parse(message.content) if parse: table_name = parse['table_name'] i = 1 columns = [] while True: em = EmbedTemplate( title=f"Column {i}", description= f"syntax: \*column name\*:\*column type\*:\*extra detail\*\nExtra detail is for example, PRIMARY, not null etc.\nType 'END;' to stop" ) em.add_field( name="Data types", value="https://www.postgresql.org/docs/9.5/datatype.html") await message.channel.send(embed=em) msg = await self.client.wait_for('message', timeout=120.0, check=check_author) if msg: content = msg.content if content == 'END;': break splitted = content.split(":") merged = f"{' '.join(splitted)}" columns.append(merged) i += 1 else: break if columns: nl = ',\n' query = f"CREATE TABLE {table_name} IF NOT EXISTS (\n{f'{nl}'.join(columns)}\n);" sql = f"```sql\n{query}\n```" await message.channel.send(sql) await message.channel.send( "Is this ok ? Y for Yes, anything for No") msg = await self.client.wait_for('message', timeout=60.0) if msg: if "y" in msg.content.lower(): await self.database.query(query)
async def run(self, message, server): parse = self.args.parse(message.content) if parse: steam_32id = None steam_64id = None vanity_url = parse.get("profile") steam_profile_id = parse.get("steamid") steam_id = parse.get('steamarg') if vanity_url is not None: if vanity_url[len(vanity_url) - 1] == '/': vanity_url = vanity_url[:len(vanity_url) - 1] steam_64id = await self.steam_api.resolve_vanity_url(vanity_url ) if steam_64id: steam_32id = self.steam_api.steam_64bit_id_to_32bit( steam_64id) elif steam_profile_id is not None: steam_32id = self.steam_api.steam_64bit_id_to_32bit( steam_profile_id) steam_64id = int(steam_profile_id) elif steam_id is not None: steam_32id = int( steam_id ) if steam_id < 76561197960265728 else self.steam_api.steam_32bit_id_to_64bit( steam_id) steam_64id = int( steam_id ) if steam_id > 76561197960265728 else self.steam_api.steam_64bit_id_to_32bit( steam_id) if steam_64id: await message.reply("> Might take a while, sit tight") account, new_matches = await self.steam_api.get_complete_account( steam_64id) for i in new_matches: await self.database.create_dota_match(i) em = EmbedTemplate( title=account.steam_profile.name, description= f"Win rate: {account.win_rate()*100}%\nWins: {account.match_history.wins}\nLosses: {account.match_history.losses}\nTotal matches:{account.match_history.total_matches}" ) em.set_thumbnail(url=account.steam_profile.get_full_avatar()) await message.reply(embed=em)
def __help(self, ): desc_string = self.description + "\n\n" for i in self.command_list.values(): desc_string += f""" **Command:** {self.command_key} {i.name} - {i.description} **Usage:** {i.usage} **Aliases:** ```{",".join(i.aliases)}``` """ embed = EmbedTemplate(title=self.module_name, description=desc_string) return embed
def get_embed(self, ) -> discord.Embed: em = EmbedTemplate(title=self.name) if self.production_timer: em.add_field( name="Production Time", value=f"{datetime.timedelta(seconds=self.production_timer)}", inline=False) if self.stats: em.add_field(name="Stats", value="\n".join(self.stats)) em.add_field(name="Skill", value=self.skill if self.skill else "N/A") return em
async def on_message(self, message): try: server = self.database.runtime.get("servers").get(message.guild.id) for key, module in self.commands.items(): if message.content.startswith(module.command_key): await module.parse(message, server) break if server: if server.voice: for i, f in server.voice.sounds.items(): if message.content == i: await server.voice.playFile(f) break if message.content.startswith(self.command_key+"help"): em = EmbedTemplate(title="Help", timestamp=datetime.utcnow()) for name, commandset in self.commands.items(): em.add_field(name=f"{name.title()}", value=commandset.command_key+" help") await message.channel.send(embed=em) except Exception as e: log([f"[COMMANDS][{datetime.now().strftime('%Y-%m-%d, %H:%I:%S.%f')}] {e}", traceback.format_exc()+"\r\n"])
async def run(self, message, server): vc = next( (x for x in self.client.voice_clients if message.guild == x.guild), None) if vc.is_connected(): em = EmbedTemplate(title="Left Voice Channel", description="Bot has left voice channel") await vc.disconnect() await message.channel.send(embed=em) if server: if server.voice: server.voice = None
async def parse(self, message, server): if self.timer["start"] < time.time() < self.timer["end"]: self.count += 1 else: self.timer["start"] = time.time() self.timer["end"] = time.time() + 5 self.count = 0 if self.count < self.rate_limit: await super().parse(message, server) self.count += 1 else: em = EmbedTemplate( title="Rate Limit", description="You're being rate limited. Try again soon") await message.channel.send(embed=em)
async def run(self, message: discord.Message, server: Server): parsed = self.args.parse(message.content) if parsed: res = dict_search(self.database["arknights"]["items"]["names"], parsed["resource"]) if res: if isinstance(res, str): em = self.database["arknights"]["items"]["names"][ res].get_embed() await message.channel.send(embed=em) elif isinstance(res, list): em = EmbedTemplate(title="Did you mean?", description="\n".join([ f"{i}. {res[i-1]}" for i in range(1, len(res) + 1) ])) await message.channel.send(embed=em) msg = await self.client.wait_for( 'message', check=lambda x: x.author == message.author, timeout=30) if msg: if msg.content.isdigit(): tmp = int(msg.content) if 1 <= tmp <= len(res): em = self.database["arknights"]["items"][ "names"][res[tmp - 1]].get_embed() await message.channel.send(embed=em) else: em = EmbedTemplate( title="Not found", description= "Resource wasn't found in the database, if you think this is an error, contact bot owner." ) await message.channel.send(embed=em)
def get_embed(self, ) -> discord.Embed: em = EmbedTemplate(title=self.name) if self.production_timer: em.add_field( name="Production Time", value=f"{datetime.timedelta(seconds=self.production_timer)}", inline=False) em.add_field(name="Skill", value=self.skill if self.skill else "N/A") if self.formation_bonus and self.formation_tiles: formation_tiles = self.formation_tiles.replace("0", "⬛").replace( "1", "⬜").replace("2", "🟦").replace("\\r\\n", "\r\n") formation_bonus = self.formation_bonus.replace("\\r\\n", "\r\n") em.add_field(name="Formation", value=f"{formation_tiles}\n\n{formation_bonus}", inline=False) return em
async def run(self, message, server): parse = self.args.parse(message.content) if parse: if parse.get("message") == "message": em = EmbedTemplate(title="GTANW Message", description="Updating soon..") msg = await message.channel.send(embed=em) nwmessage = NewswireMessage(msg) await self.database.create_updated_message(msg.guild.id, "gtanw", msg.channel.id, msg.id) server.updated_messages["name"]["gtanw"] = nwmessage server.updated_messages["id"][nwmessage.id] = nwmessage else: x = 5 posts = await self.newswire.getEmbeds(x) for i in posts: await message.channel.send(embed=i) x+=1
async def run(self, message: discord.Message, server: Server) -> None: parse = self.args.parse(message.content) if parse: doll = self.find_doll(parse) if doll: if isinstance(doll, Doll): em = doll.get_embed() image = discord.File(doll.get_image_path(), filename="doll.png") em.set_image(url="attachment://doll.png") await message.channel.send(file=image, embed=em) elif isinstance(doll, list): em = EmbedTemplate(title="Did you mean?", description="\n".join([ f"{i}. {doll[i-1]}" for i in range(1, len(doll) + 1) ])) await message.channel.send(embed=em) msg = await self.client.wait_for( 'message', check=lambda x: x.author == message.author, timeout=30) if msg: if msg.content.isdigit(): tmp = int(msg.content) if 1 <= tmp <= len(doll): chosen_doll = doll[tmp - 1] if chosen_doll in self.database["gfl"][ "dolls"]["names"]: chosen_doll = self.database["gfl"][ "dolls"]["names"].get(chosen_doll) elif chosen_doll in self.database["gfl"][ "dolls"]["aliases"]: chosen_doll = self.database["gfl"][ "dolls"]["aliases"].get(chosen_doll) if isinstance(chosen_doll, Doll): em = chosen_doll.get_embed() image = discord.File( chosen_doll.get_image_path(), filename="doll.png") em.set_image(url="attachment://doll.png") await message.channel.send(file=image, embed=em) else: em = EmbedTemplate( title="Not found", description= "Doll wasn't found in the database, if you think this is an error, contact bot owner." ) await message.channel.send(embed=em)
async def danbooru(keywords) -> discord.Embed: key = f"danbooru_{keywords}" if key not in cache: params = add_params(keywords, True) response = await fetch_url('https://danbooru.donmai.us/posts.json', params) if response: posts = json.loads(response) if key not in cache: cache.add(key, posts) try: post = random.choice(cache.get(key)) post = { 'img': post['file_url'], 'tags': post['tag_string'][:120] + "..." } return construct_embed(post['img'], post['tags'], keywords) except IndexError: return EmbedTemplate(title='No results!', description='No results for keywords found')
async def booruAPI(keywords, url, api) -> discord.Embed: key = f"{api}_{keywords}" if key not in cache: params = add_params(keywords, False) response = await fetch_url(url, params) if response: posts = ET.fromstring(response) posts = [{ "img": el.attrib.get('file_url'), "tags": el.attrib.get('tags')[:120] + "..." } for el in posts.findall('.//post')] if key not in cache: cache.add(key, posts) try: tmp = cache.get(key)["function"] post = random.choice(tmp) return construct_embed(post['img'], post['tags'], keywords) except IndexError: return EmbedTemplate(title='No results!', description='No results for keywords found')
async def refresh(self, cetus): em = EmbedTemplate(title="Plains of Eidolon", timestamp=datetime.utcnow()) em.add_field(name="Status", value=str(cetus)) em.add_field( name="Time until new rotation", value=f"{cetus.minutes_left() if cetus else 0.00:.0f} min") await self.message.edit(embed=em) if not self.lock: if cetus.isNight() and self.mention: self.lock = True self.notify_message = await self.message.channel.send( f"{self.mention.name} - {self.mention.role.mention}") self.client.loop.call_later(cetus.seconds_left() + 60, self.callback)
async def run(self, message, server): parse = self.args.parse(message.content) if parse: if message.author.voice.channel: if server: if not server.voice: vc = await message.author.voice.channel.connect() server.voice = VoicePlayer(vc, message.channel, self.client) if server.voice.vc.is_connected(): if parse.get("sound") == "list": em = EmbedTemplate( title="Sounds", description="\n".join( sorted(server.voice.sounds.keys()))) await message.channel.send(embed=em) elif parse.get("sound") in server.voice.sounds.keys(): await server.voice.playFile( server.voice.sounds[parse.get("sound")]) else: server.voice = None await self.run(message, server)
async def run(self, message, server): if message.author.guild_permissions.administrator: parse = self.args.parse(message.content) if parse: em = EmbedTemplate(title="WorldState Message", description="Updating soon..") new_message = None msg_type = None msg = await message.channel.send(embed=em) if parse.get("message") == "nightwave": new_message = NightwaveMessage(msg) elif parse.get("message") == "sorties": new_message = SortieMessage(msg) elif parse.get("message") == "fissures": new_message = FissureMessage(msg, []) elif parse.get("message") == "poe": new_message = CetusMessage(msg, [], self.client) elif parse.get("message") == "invasions": new_message = InvasionMessage(msg, []) if new_message: msg_type = parse.get("message") await self.database.create_updated_message(server.server_id, msg_type, msg.channel.id, msg.id) server.updated_messages["name"][msg_type] = new_message server.updated_messages["id"][msg.id] = new_message
def to_embed(self, ) -> discord.Embed: em = EmbedTemplate(title=self.title, description=self.url) em.set_image(url=self.image) return em
async def run(self, message, server): def is_number(s): try: float(s.content) return True except ValueError: return False try: parse = self.parser.parse(message.content) if parse: await message.channel.send(embed=EmbedTemplate( title="Probability", description="Amount of trials")) trials = await self.client.wait_for('message', timeout=30.0, check=is_number) await message.channel.send(embed=EmbedTemplate( title="Probability", description="Chance (in %)")) chance = await self.client.wait_for('message', timeout=30.0, check=is_number) await message.channel.send(embed=EmbedTemplate( title="Probability", description="Wanted amount of successes")) successes = await self.client.wait_for('message', timeout=30.0, check=is_number) if trials and chance and successes: successes = int(successes.content) trials = int(trials.content) chance = float(chance.content) / 100 em = EmbedTemplate(title='Probability', description="Calculated probability") em.add_field(name="Trials", value=f"{trials}") em.add_field(name="Successes", value=f"{successes}") em.add_field(name="Chance", value=f"{chance}") em.add_field( name="Probability", value= f"{Math.exact_probability(trials, successes, chance)}") await message.channel.send(embed=em) except asyncio.TimeoutError: await message.channel.send(embed=EmbedTemplate( title="Probability", description="Timed out"))