async def ls(self, ctx, *, channel: typing.Optional[discord.TextChannel] = None): """ View the status of your live scores channels. """ e = discord.Embed(color=0x2ecc71) e.set_thumbnail(url=ctx.me.avatar_url) e.title = f"{ctx.guild.name} Live Scores channels" if channel is None: score_ids = [i[1] for i in self.cache if ctx.guild.id in i] if not score_ids: return await ctx.reply( f"{ctx.guild.name} has no live-scores channel set.", mention_author=True) else: score_ids = [channel.id] for i in score_ids: ch = self.bot.get_channel(i) if ch is None: continue e.title = f'{ch.name} tracked leagues ' # Warn if they f**k up permissions. if not ctx.me.permissions_in(ch).send_messages: e.description = "```css\n[WARNING]: I do not have send_messages permissions in that channel!" leagues = self.cache[(ctx.guild.id, i)] embeds = embed_utils.rows_to_embeds(e, sorted(leagues)) for x in embeds: x.description = f"```yaml\n{x.description}```" if embeds: self.bot.loop.create_task(paginate(ctx, embeds))
async def disabled(self, ctx): """ Check which commands are disabled on this server """ try: disabled = self.bot.disabled_cache[ctx.guild.id] header = f"The following commands are disabled on this server:" embeds = embed_utils.rows_to_embeds(discord.Embed(), disabled) await paginate(ctx, embeds, header=header) except KeyError: return await ctx.reply(f'No commands are currently disabled on {ctx.guild.name}', mention_author=False)
async def banlist(self, ctx): """ Show the banlist for the server """ ban_lines = [f"\💀 {x.user.name}#{x.user.discriminator}: {x.reason}\n" for x in await ctx.guild.bans()] if not ban_lines: ban_lines = ["☠ No bans found!"] e = discord.Embed(color=0x111) n = f"≡ {ctx.guild.name} discord ban list" e.set_author(name=n, icon_url=ctx.guild.icon_url) e.set_thumbnail(url="https://i.ytimg.com/vi/eoTDquDWrRI/hqdefault.jpg") e.title = "User (Reason)" ban_embeds = embed_utils.rows_to_embeds(e, ban_lines) await paginate(ctx, ban_embeds)
async def squad(self, ctx, *, qry: commands.clean_content = None): async with ctx.typing(): await ctx.send("Searching...", delete_after=5) fsr = await self._search(ctx, qry, mode="team") async with sl_lock: players = await self.bot.loop.run_in_executor( None, fsr.players, self.driver) srt = sorted(players, key=lambda x: x.number) embed = await fsr.base_embed embed.title = f"Squad for {embed.title}" players = [i.player_embed_row for i in srt] embeds = embed_utils.rows_to_embeds(embed, players) await embed_utils.paginate(ctx, embeds)
async def cog_embed(self, cog): e = discord.Embed() e.title = f'Category Help: {cog.qualified_name}' e.colour = 0x2ecc71 e.set_thumbnail(url=self.context.me.avatar_url) description_top = f"```fix\n{cog.description}\n```**Commands in this category**:\n\n" rows = sorted([descriptor(command) for command in cog.get_commands() if not command.hidden]) if len(rows) > 10: e.add_field(name="Changing pages", value="This category has more than 1 page of commands," " click ◀ and ▶ below to scroll", inline=False) e.add_field(value='Use help **command** to view the usage of that command.\n Subcommands are ran by using ' f'`{self.context.prefix}command subcommand`', name="More help", inline=False) embeds = embed_utils.rows_to_embeds(e, rows, description_top=description_top, per_row=10) return embeds
async def results(self, ctx, *, qry: commands.clean_content = None): """ Get past results for a team or league. Navigate pages using reactions. """ await ctx.send('Searching...', delete_after=5) fsr = await self._search(ctx, qry) if fsr is None: return async with sl_lock: results = await self.bot.loop.run_in_executor( None, fsr.fetch_fixtures, self.driver, '/results') results = [i.to_embed_row for i in results] embed = await fsr.base_embed embed.title = f"≡ Results for {embed.title}" embeds = embed_utils.rows_to_embeds(embed, results) await embed_utils.paginate(ctx, embeds)
async def ticker(self, ctx, channels: commands.Greedy[discord.TextChannel]): """ Get info on your server's transfer tickers. """ channels = await self._pick_channels(ctx, channels) # (guild_id, channel_id, mode) guild_cache = {i[1] for i in self.cache if ctx.guild.id in i} if not guild_cache: return await ctx.reply( f"{ctx.guild.name} has no transfer ticket channels set. Use `{ctx.prefix}tf " f"set #channel` to create one.", mention_author=True) e = discord.Embed() e.colour = ctx.me.color for c in channels: e.title = f"Transfer ticker for {c.name}" if c.id not in guild_cache: e.colour = discord.Colour.red() e.description = "â›” This channel is not set as a transfer ticker channel." await ctx.reply(embed=e, mention_author=True) continue wl_key = [i for i in self.cache if c.id in i][0] mode = wl_key[2] mode = "short" if mode is True else "Embed" whitelist = self.cache[wl_key] e.set_footer( text=f"New transfers are being output in {mode} mode.") if whitelist: wl = [] for x in whitelist: wl.append(f"{x[2]} ({x[1]})") # Alias, type. embeds = embed_utils.rows_to_embeds(e, wl) if embeds: self.bot.loop.create_task(paginate(ctx, embeds)) continue else: e.colour = discord.Colour.dark_orange() e.description = f'âš **All** Transfers are being output to this channel in **{mode}** mode.\n' \ f'You can create a whitelist with {ctx.prefix}tf whitelist add' await ctx.reply(embed=e, mention_author=False) continue
async def injuries(self, ctx, *, qry: commands.clean_content = None): """ Get a team's current injuries """ async with ctx.typing(): await ctx.send("Searching...", delete_after=5) fsr = await self._search(ctx, qry, mode="team") if fsr is None: return async with sl_lock: players = await self.bot.loop.run_in_executor( None, fsr.players, self.driver) embed = await fsr.base_embed players = [i.injury_embed_row for i in players if i.injury] players = players if players else ['No injuries found'] embed.title = f"Injuries for {embed.title}" embeds = embed_utils.rows_to_embeds(embed, players) await embed_utils.paginate(ctx, embeds)
async def squad(self, ctx, *, qry: commands.clean_content = None): """Lookup a team's squad members""" async with ctx.typing(): m = await ctx.reply("Searching...", mention_author=False) fsr = await self._search(ctx, qry, status_message=m, mode="team") if fsr is None: return m = await processing_update(m, "Processing...") async with sl_lock: players = await self.bot.loop.run_in_executor(None, fsr.players, self.bot.fixture_driver) srt = sorted(players, key=lambda x: x.number) embed = await fsr.base_embed embed.title = f"≡ Squad for {embed.title}" if embed.title else "≡ Squad " players = [f"`{str(i.number).rjust(2)}`: {i.flag} [{i.name}]({i.link}) {i.position}{i.injury}" for i in srt] embeds = embed_utils.rows_to_embeds(embed, players) await cleanup(m) await embed_utils.paginate(ctx, embeds)
async def injuries(self, ctx, *, qry: commands.clean_content = None): """Get a team's current injuries""" async with ctx.typing(): m = await ctx.reply("Searching...", mention_author=False) fsr = await self._search(ctx, qry, status_message=m, mode="team") if fsr is None: return m = await processing_update(m, "Processing...") async with sl_lock: players = await self.bot.loop.run_in_executor(None, fsr.players, self.bot.fixture_driver) embed = await fsr.base_embed players = [f"{i.flag} [{i.name}]({i.link}) ({i.position}): {i.injury}" for i in players if i.injury] players = players if players else ['No injuries found'] embed.title = f"≡ Injuries for {embed.title}" if embed.title else "≡ Injuries " embeds = embed_utils.rows_to_embeds(embed, players) await cleanup(m) await embed_utils.paginate(ctx, embeds)
async def results(self, ctx, *, qry: commands.clean_content = None): """Get past results for a team or league. Navigate pages using reactions.""" async with ctx.typing(): m = await ctx.reply("Searching...", mention_author=False) fsr = await self._search(ctx, qry, status_message=m) if fsr is None: return m = await processing_update(m, "Processing...") async with sl_lock: results = await self.bot.loop.run_in_executor(None, fsr.fetch_fixtures, self.bot.fixture_driver, '/results') results = [str(i) for i in results] embed = await fsr.base_embed embed.title = f"≡ Results for {embed.title}" if embed.title else "≡ Results " embeds = embed_utils.rows_to_embeds(embed, results) await cleanup(m) await embed_utils.paginate(ctx, embeds)
async def whitelist(self, ctx, channels: commands.Greedy[discord.TextChannel]): """ Check the whitelist of specified channels """ channels = await self._pick_channels(ctx, channels) for c in channels: try: key = [i for i in self.cache if c.id in i][0] except IndexError: print("Warning:", c.id, "not found in transfers cache.") await ctx.reply(f'No transfer ticker found for {c.mention}.', mention_author=True) continue whitelist = self.cache[key] if not whitelist: await ctx.reply(f"{c.mention} is tracking all transfers", mention_author=False) continue embed = discord.Embed(title=f"Whitelist items for {c.name}") embeds = embed_utils.rows_to_embeds(embed, [i[2] for i in whitelist]) await embed_utils.paginate(ctx, embeds)
async def scorers(self, ctx, *, qry: commands.clean_content): """ Get top scorers from a league, or search for a team and get their top scorers in a league. """ await ctx.send("Searching...", delete_after=5) fsr = await self._search(ctx, str(qry)) if fsr is None: return # rip if isinstance(fsr, football.Competition): async with sl_lock: players = await self.bot.loop.run_in_executor( None, fsr.scorers, self.driver) players = [i.scorer_embed_row_team for i in players] embed = await fsr.base_embed embed.title = f"Top Scorers for {embed.title}" else: async with sl_lock: choices = await self.bot.loop.run_in_executor( None, fsr.player_competitions, self.driver) embed = await fsr.base_embed embed.set_author(name="Pick a competition") index = await embed_utils.page_selector(ctx, choices, base_embed=embed) if index is None: return # rip async with sl_lock: players = await self.bot.loop.run_in_executor( None, fsr.players, self.driver, index) players = sorted([i for i in players if i.goals > 0], key=lambda x: x.goals, reverse=True) players = [i.scorer_embed_row for i in players] embed = await fsr.base_embed embed.title = f"Top Scorers for {embed.title} in {choices[index]}" embeds = embed_utils.rows_to_embeds(embed, players) await embed_utils.paginate(ctx, embeds)
async def scorers(self, ctx, *, qry: commands.clean_content = None): """Get top scorers from a league, or search for a team and get their top scorers in a league.""" m = await ctx.reply("Searching...", mention_author=False) fsr = await self._search(ctx, qry, status_message=m) if fsr is None: return m = await processing_update(m, "Processing...") embed = await fsr.base_embed if isinstance(fsr, football.Competition): async with sl_lock: sc = await self.bot.loop.run_in_executor(None, fsr.scorers, self.bot.fixture_driver) players = [f"{i.flag} [{i.name}]({i.link}) ({i.team}) {i.goals} Goals, {i.assists} Assists" for i in sc] embed.title = f"≡ Top Scorers for {embed.title}" if embed.title else "≡ Top Scorers " else: async with sl_lock: choices = await self.bot.loop.run_in_executor(None, fsr.player_competitions, self.bot.fixture_driver) embed.set_author(name="Pick a competition") index = await embed_utils.page_selector(ctx, choices, base_embed=embed) if index is None: return # rip async with sl_lock: players = await self.bot.loop.run_in_executor(None, fsr.players, self.bot.fixture_driver, index) players = sorted([i for i in players if i.goals > 0], key=lambda x: x.goals, reverse=True) players = [f"{i.flag} [{i.name}]({i.link}) {i.goals} in {i.apps} appearances" for i in players] embed.title = f"≡ Top Scorers for {embed.title} in {choices[index]}" if embed.title \ else f"Top Scorers in {choices[index]}" embeds = embed_utils.rows_to_embeds(embed, players) await cleanup(m) await embed_utils.paginate(ctx, embeds)
async def guilds(self, ctx): guilds = [f"{i.id}: {i.name}" for i in self.bot.guilds] embeds = embed_utils.rows_to_embeds(discord.Embed(), guilds) await embed_utils.paginate(ctx, embeds)
async def send_leagues(ctx, channel, leagues): e = discord.Embed() embeds = embed_utils.rows_to_embeds(e, list(leagues)) await embed_utils.paginate(ctx, embeds, header=f"Tracked leagues for {channel.mention}")
async def tv(self, ctx, *, team: commands.clean_content = None): """ Lookup next televised games for a team """ async with ctx.typing(): em = discord.Embed() em.colour = 0x034f76 em.set_author(name="LiveSoccerTV.com") em.description = "" if team is not None: item_list = [i for i in self.bot.tv if team in i.lower()] if not item_list: return await ctx.reply(f"Could not find a matching team/league for {team}.", mention_author=False) matching_teams = [i for i in self.bot.tv if team in i.lower()] index = await embed_utils.page_selector(ctx, matching_teams) if index is False: return team = matching_teams[index] em.url = self.bot.tv[team] em.title = f"Televised Fixtures for {team}" else: em.url = "http://www.livesoccertv.com/schedules/" em.title = f"Today's Televised Matches" tvlist = [] async with self.bot.session.get(em.url) as resp: if resp.status != 200: return await ctx.reply(f"🚫 <{em.url}> returned a HTTP {resp.status} error.", mention_author=False) tree = html.fromstring(await resp.text()) match_column = 3 if not team else 5 for i in tree.xpath(".//table[@class='schedules'][1]//tr"): # Discard finished games. complete = "".join(i.xpath('.//td[@class="livecell"]//span/@class')).strip() if complete in ["narrow ft", "narrow repeat"]: continue match = "".join(i.xpath(f'.//td[{match_column}]//text()')).strip() if not match: continue ml = i.xpath(f'.//td[{match_column + 1}]//text()') try: link = i.xpath(f'.//td[{match_column + 1}]//a/@href')[-1] link = f"http://www.livesoccertv.com/{link}" except IndexError: link = "" ml = ", ".join([x.strip() for x in ml if x != "nufcTV" and x.strip() != ""]) if not ml: continue date = "".join(i.xpath('.//td[@class="datecell"]//span/text()')).strip() time = "".join(i.xpath('.//td[@class="timecell"]//span/text()')).strip() if complete != "narrow live": # Correct TimeZone offset. try: time = datetime.datetime.strptime(time, '%H:%M') + datetime.timedelta(hours=5) time = datetime.datetime.strftime(time, '%H:%M') dt = f"{date} {time}" except ValueError as e: print("ValueError in tv", e) dt = "" elif not team: dt = i.xpath('.//td[@class="timecell"]//span/text()')[-1].strip() if dt == "FT": continue if dt != "HT" and ":" not in dt: dt = f"LIVE {dt}'" else: if date == datetime.datetime.now().strftime("%b %d"): dt = time else: dt = date tvlist.append(f'`{dt}` [{match}]({link})') if not tvlist: return await ctx.reply(f"No televised matches found, check online at {em.url}", mention_author=False) dtn = datetime.datetime.now().strftime("%H:%M") em.set_footer(text=f"Time now: {dtn} Your Time:") em.timestamp = datetime.datetime.now() embeds = embed_utils.rows_to_embeds(em, tvlist) await embed_utils.paginate(ctx, embeds)