async def tor_repo(self, ctx, *, search: str = None): """Search for a ToR related github repo. Search string can be "all".""" if not search: await ctx.send(embed=discord.Embed( description='[GrafeasGroup](https://github.com/GrafeasGroup)')) return graphql_query = """ query { organization(login: "******") { repositories(last: 100) { edges { node { resourcePath # Not using `url` because it's harder to show # the resourcePath. If we do both, that's extra # code to process the data. } } } } } """ headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.github_token, 'Accept': 'application/json' } r = requests.post('https://api.github.com/graphql', headers=headers, json={'query': graphql_query}) repos = ['/perryprog/tor-genius'] repos.extend([ item['node']['resourcePath'] for item in r.json()['data'] ['organization']['repositories']['edges'] ]) if search.lower() == 'all': p = Pages(ctx, entries=[ f'[{re[1:]}](https://github.com{re})' for re in repos ]) await p.paginate() return results = [] for re in repos: if search in re: results.append(f'[{re[1:]}](https://github.com{re})') if not results: await ctx.send('No results found.') return p = Pages(ctx, entries=results) await p.paginate()
async def discrim(self, ctx, discriminator: Discriminator = None, *, selector: Selector = '='): """Search for specific discriminators. Optional parameter for ranges to be searched. It can be >, >=, <=, or <. Ranges between two numbers hasn't been implemented yet.""" if not discriminator: discriminator = int(ctx.author.discriminator) if selector == '>': p = Pages(ctx, entries=[ f'{u.display_name}#{u.discriminator}' for u in ctx.guild.members if int(u.discriminator) > discriminator ]) elif selector == '<': p = Pages(ctx, entries=[ f'{u.display_name}#{u.discriminator}' for u in ctx.guild.members if int(u.discriminator) < discriminator ]) elif selector == '>=': p = Pages(ctx, entries=[ f'{u.display_name}#{u.discriminator}' for u in ctx.guild.members if int(u.discriminator) >= discriminator ]) elif selector == '<=': p = Pages(ctx, entries=[ f'{u.display_name}#{u.discriminator}' for u in ctx.guild.members if int(u.discriminator) <= discriminator ]) elif selector == '=': p = Pages(ctx, entries=[ f'{u.display_name}#{u.discriminator}' for u in ctx.guild.members if int(u.discriminator) == discriminator ]) else: raise commands.BadArgument('Could not parse arguments') if not p.entries: return await ctx.send('No results found.') await p.paginate()
async def reddit_wiki_page(self, ctx, *, search: str = None): """Search the wiki pages on r/ToR for something.""" sub = ctx.r.subreddit('transcribersofreddit') if not search: embed = discord.Embed( color=ctx.author.color, description='[ToR Wiki](https://www.reddit.com/' 'r/TranscribersOfReddit/wiki/index)') await ctx.send(embed=embed) return results = [] for page in sub.wiki: if search in str(page.name): results.append(f'[{page.name}](https://www.reddit.com' f'/r/TranscribersOfReddit/wiki/{page.name})') if results is not []: p = Pages(ctx, entries=results) p.embed.color = ctx.author.color await p.paginate() else: await ctx.send("Couldn't find any results for that. Sorry! ):")
async def help(ctx): await bot.delete_message(ctx.message) msg = open('cogs/utils/help.txt').read().replace('\\u200b', '\u200b').splitlines() for i, line in enumerate(msg): if line.strip().startswith('.'): x = line.strip().strip('.') x = ctx.prefix + x msg[i] = '`' + x + '`' try: p = Pages(bot, message=ctx.message, entries=msg) p.embed.set_author(name='Help - Darkness Commands', icon_url=bot.user.avatar_url) p.embed.color = 0x00FFFF await p.paginate() except: embed = discord.Embed(title='Darkness Commands', color=0xed) embed.add_field(name='Moderation:', value='kick, ban, unban, softban, warn, purge') embed.add_field(name='Information:', value='info, serverinfo, userinfo, avatar') embed.add_field(name='Miscellaneous:', value='ping, suggest, invite, support') embed.add_field(name='Utilities:', value='calc, remind, addrole, removerole') embed.add_field(name='Fun:', value='8ball, cat') embed.set_footer(text='Bot Dev: -= shadeyg56 =-#1702') await bot.say(embed=embed)
async def _whitelistList(self, ctx): """List whitelisted channels. NOTE: do this in a channel outside of the viewing public """ guildId = ctx.message.server.id guildName = ctx.message.server.name if guildId not in list(self.whitelist): await self.bot.say(":negative_squared_cross_mark: Word Filter: The " "guild **{}** is not registered, please add a " "channel first".format(guildName)) return if self.whitelist[guildId]: display = [] for channel in self.whitelist[guildId]: display.append("`{}`".format(channel)) # msg = "" # for word in self.whitelist[guildId]: # msg += word # msg += "\n" # title = "Filtered words for: **{}**".format(guildName) # embed = discord.Embed(title=title,description=msg,colour=discord.Colour.red()) # await self.bot.send_message(user,embed=embed) page = Pages(self.bot, message=ctx.message, entries=display) page.embed.title = "Whitelisted channels for: **{}**".format(guildName) page.embed.colour = discord.Colour.red() await page.paginate() else: await self.bot.say("Sorry, there are no whitelisted channels in " "**{}**".format(guildName))
async def _commandList(self, ctx): """List blacklisted commands. If the commands on this list are invoked with any filtered words, the entire message is filtered and the contents of the message will be sent back to the user via DM. """ guildId = ctx.message.server.id guildName = ctx.message.server.name if guildId not in list(self.commandBlacklist): await self.bot.say(":negative_squared_cross_mark: Word Filter: The " "guild **{}** does not have blacklisted commands, " "please add a command to the blacklist first, and " "try again.".format(guildName)) return if self.commandBlacklist[guildId]: display = [] for cmd in self.commandBlacklist[guildId]: display.append("`{}`".format(cmd)) page = Pages(self.bot, message=ctx.message, entries=display) page.embed.title = "Blacklisted commands for: **{}**".format(guildName) page.embed.colour = discord.Colour.red() await page.paginate() else: await self.bot.say("Sorry, there are no blacklisted commands in " "**{}**".format(guildName))
async def listFilter(self, ctx): """List filtered words in raw format. NOTE: do this in a channel outside of the viewing public """ guildId = ctx.message.server.id guildName = ctx.message.server.name user = ctx.message.author if guildId not in list(self.filters): await self.bot.send_message(user, "`Word Filter:` The guild **{}** is not " "registered, please add a word first".format(guildName)) return if self.filters[guildId]: display = [] for regex in self.filters[guildId]: display.append("`{}`".format(regex)) # msg = "" # for word in self.filters[guildId]: # msg += word # msg += "\n" # title = "Filtered words for: **{}**".format(guildName) # embed = discord.Embed(title=title,description=msg,colour=discord.Colour.red()) # await self.bot.send_message(user,embed=embed) page = Pages(self.bot, message=ctx.message, entries=display) page.embed.title = "Filtered words for: **{}**".format(guildName) page.embed.colour = discord.Colour.red() await page.paginate() else: await self.bot.send_message(user, "Sorry you have no filtered words in " "**{}**".format(guildName))
async def flair_count(self, ctx, *, flair: commands.clean_content = "Unclaimed"): """Get the number of posts left on r/ToR with a certain flair. It's by default 'Unclaimed'.""" sub = ctx.r.subreddit('transcribersofreddit') links = [] for submission in sub.new(limit=500): if submission.link_flair_text == flair: links.append(submission) word = 'post' if len(links) == 1 else 'posts' await ctx.send(f'{len(links)} {flair} {word}!') if len(links) == 0: return p = Pages(ctx, entries=tuple(f'[{s.title.split(" | ")[2][1:-1]}]' f'(https://reddit.com{s.permalink})' for s in links)) await p.paginate()
async def listroles(self, ctx): """Useful command to find every role and their ID's""" guild = ctx.guild roles = list(guild.roles)[:] roles.sort(key = lambda role: -role.position) p = Pages(ctx, entries=[f"{r.name}, {r.id}" for r in roles], per_page=25, show_index_count=False) await p.paginate()
async def _whitelist_listroles(self, ctx): """List roles on the bot's whitelist""" if not self.override_perms["roles"]: await self.bot.say("No roles are on the whitelist.") return page = Pages(self.bot, message=ctx.message, entries=self.override_perms["roles"]) page.embed.title = "Whitelisted roles in **{}**".format(ctx.message.server.name) page.embed.colour = discord.Colour.red() await page.paginate()
async def list(self, ctx, query=''): p = Pages(ctx, entries=[ name for name, e in self.config if query in e['text'] or query in name ]) if not p.entries: return await ctx.send('No results found.') await p.paginate()
async def names(self, ctx, *, query: str.lower = ''): """Search or list names on this guild, sorted by most common""" count = Counter( [u.name for u in ctx.guild.members if query in u.name.lower()]) p = Pages(ctx, entries=[f'**{i[0]}**: {i[1]}' for i in count.most_common()]) await p.paginate()
async def emojis(self, ctx, *, query=''): """List the servers emojis without spamming.""" entries = [ f'{str(e)}, `:{e.name}:`, `{str(e)}`' for e in ctx.guild.emojis if query in e.name ] if not entries: return await ctx.send('No results found for query.') p = Pages(ctx, entries=entries) await p.paginate()
async def help(ctx): await bot.delete_message(ctx.message) msg = open('cogs/utils/help.txt').read().replace('\\u200b','\u200b').splitlines() for i, line in enumerate(msg): if line.strip().startswith('.'): x = line.strip().strip('.') x = ctx.prefix + x msg[i] = '`' + x + '`' p = Pages(bot, message=ctx.message, entries=msg) p.embed.set_author(name='Help - KnightBot Commands', icon_url=bot.user.avatar_url) p.embed.color = 0x00FFFF await p.paginate()
async def _whitelist_listusers(self, ctx): """List users on the bot's whitelist""" if not self.override_perms["users"]: await self.bot.say("No users are on the whitelist.") return users = [] for uid in self.override_perms["users"]: user_obj = ctx.message.server.get_member(uid) if not user_obj: continue users.append(user_obj.mention) page = Pages(self.bot, message=ctx.message, entries=users) page.embed.title = "Whitelisted users in **{}**".format(ctx.message.server.name) page.embed.colour = discord.Colour.red() await page.paginate()
async def hoisters(self, ctx, role: commands.RoleConverter = None, limit: int = 0): """Get a list of possible hoisters, with an optional role, and an optional limit.""" if role: result = [ m.display_name for m in ctx.guild.members if role in m.roles ] else: result = [m.display_name for m in ctx.guild.members] result = result[:limit] if limit else result p = Pages(ctx, entries=sorted(result, key=locale.strxfrm)) await p.paginate()
async def _birthdayList(self, ctx): """Lists the birthdays of users.""" serverID = ctx.message.server.id serverName = ctx.message.server.name user = ctx.message.author sortedList = [] # List to sort by month, day. display = [ ] # List of text for paginator to use. Will be constructed from sortedList. # Add only the users we care about (e.g. the ones that have birthdays set). for user, items in self.settings[serverID][KEY_BDAY_USERS].items(): # Check if the birthdate keys exist, and they are not null. # If true, add an ID key and append to list. if KEY_BDAY_DAY in items.keys() and \ KEY_BDAY_MONTH in items.keys() and \ KEY_BDAY_DAY is not None and \ KEY_BDAY_MONTH is not None: items["ID"] = user sortedList.append(items) # Sort by month, day. sortedList.sort(key=lambda x: (x[KEY_BDAY_MONTH], x[KEY_BDAY_DAY])) for user in sortedList: # Get the associated user Discord object. userObject = discord.utils.get(ctx.message.server.members, id=user["ID"]) # Skip if user is no longer in server. if userObject is None: continue # The year below is just there to accommodate leap year. Not used anywhere else. userBirthday = datetime(2020, user[KEY_BDAY_MONTH], user[KEY_BDAY_DAY]) text = "{0:%B} {0:%d}: {1}".format(userBirthday, userObject.name) display.append(text) page = Pages(self.bot, message=ctx.message, entries=display) page.embed.title = "Birthdays in **{}**".format(serverName) page.embed.colour = discord.Colour.red() await page.paginate()
async def _help(self, ctx, module : str = None): cogs = {} for cog in self.bot.cogs: cogs[cog] = [] for com in self.bot.commands: if self.bot.commands[com].cog_name == cog: cogs[cog].append(com) cogs = OrderedDict(sorted(cogs.items())) #msg = "" #p = commands.Paginator() #for cog in cogs: # msg += "\n{}\n".format(cog) # for com in cogs[cog]: # desc = self.bot.commands[com].help # if desc: # if len(desc) > 30: # desc = desc[:30] + "..." # else: # desc = "" # msg += "{:<25} - {}\n".format(com, desc) # p.add_line(msg) #to_send = [] #for cog in cogs: # msg = "{}\n\n".format(cog) # for com in cogs[cog]: # desc = self.bot.commands[com].help # if desc: # if len(desc) > 30: # desc = desc[:30] + "..." # else: # desc = "" # msg += "{:<25} - {}\n".format(com, desc) # to_send.append(msg) info = [i.format(prefix=ctx.prefix) for i in self.info] p = Pages(self.bot, message=ctx.message, entries=info, per_page=1) try: await p.paginate() except Exception as e: print(e) await self.bot.say("I need the `embed links` and `add reactions` permissions.")
async def all_accounts(self, ctx): """Get a list of all the reddit accounts""" query = """ SELECT user_id, reddit_username FROM reddit_config; """ results = await ctx.db.fetch(query) if not results: await ctx.send("I couldn't find any results! Sorry!") return p = Pages(ctx, entries=tuple(f'{self.bot.get_user(r[0]).mention}: ' f'[/u/{r[1]}](https://reddit.com/u/{r[1]})' for r in results)) await p.paginate()
async def forum(self, ctx, *, search): """Search the Swift Discourse Forum for anything.""" with aiohttp.ClientSession() as s: async with s.get('https://forums.swift.org/search/query.json', params={'term': search}) as r: r = await r.json() if r['grouped_search_result'] is None: return await ctx.send('No results found.') data = [] # I'm sorry. (Ok not as bad now) # idk why, but topics seems to disappear sometimes data.extend([(f't/{t["id"]}', t['title']) for t in r.get('topics', [])]) data.extend([(f'u/{u["username"]}', f'{u["username"]} ({u["name"]})') for u in r['users']]) data.extend([(f'c/{c.id}', c['name']) for c in r['categories']]) data.extend([(f'tags/{t["name"]}', t['name']) for t in r['tags']]) data.extend([(f'p/{p["id"]}', p['blurb']) for p in r['posts']]) if not data: return await ctx.send('No results found.') p = Pages(ctx, entries=[ f'[{d[1]}](https://forums.swift.org/{d[0]})' for d in data ]) await p.paginate()
async def _history(self, ctx, user: str = None): """Gives you the name history of a player""" permissions = ctx.channel.permissions_for(ctx.me) if not permissions.send_messages: return await ctx.author.send( f'The bot doesn\'t have permissions to send messages in <#{ctx.channel.id}>' ) if not permissions.embed_links: return await ctx.send('Bot does not have embed links permission.') if not permissions.add_reactions: return await ctx.send('Bot does not have add reactions permission.' ) if user and any(char in user for char in punctuation) and not ctx.message.mentions: return await ctx.send('Illegal characters used.', delete_after=20) uuid = False if user and len(user.replace('-', '')) == 32: uuid = True if not user or ctx.message.mentions and ctx.message.mentions[ 0].id != self.bot.user.id: user, member, uuid = await self._get_user(ctx) if not user: return if uuid: if self.Mojang_history.format(uuid=user) in self.requestCache: r = self.requestCache[self.Mojang_history.format(uuid=user)] else: response = await self.bot.session.get( self.Mojang_history.format(uuid=user)) if not (str(response.status).startswith('2') ) and response.reason != 'OK': return await ctx.send('Service is not working.') elif str(response.status).startswith('2'): if response.reason == 'No Content': return await ctx.send('That user doesn\'t exist.') r = await response.json() response.close() self.requestCache[self.Mojang_history.format( uuid=user)] = r users = [escape(m['name']) for m in reversed(r)] users[0] = f"**{users[0]}**" p = Pages(ctx=ctx, entries=users, per_page=20) p.embed.title = f'{users[0]} past names' p.embed.colour = 0x738bd7 await p.paginate() if not uuid: if not user: return await ctx.send( 'Cannot search for a player if none is given.') if self.Mojang_username.format(username=user) in self.requestCache: response = self.requestCache[self.Mojang_username.format( username=user)] cached = True else: response = await self.bot.session.get( self.Mojang_username.format(username=user)) cached = False if not cached and not (str(response.status).startswith('2') ) and response.reason != 'OK': return await ctx.send('Service is not working.') elif cached or str(response.status).startswith('2'): if not cached and response.reason == 'No Content': return await ctx.send('That user doesn\'t exist.') r1 = await response.json() if not cached else response self.requestCache[self.Mojang_username.format( username=user)] = r1 if self.Mojang_history.format( uuid=r1['id']) in self.requestCache: response = self.requestCache[self.Mojang_history.format( uuid=r1['id'])] cached = True else: if not cached: response.close() response = await self.bot.session.get( self.Mojang_history.format(uuid=r1['id'])) cached = False if not cached and not (str(response.status).startswith('2') ) and response.reason != 'OK': return await ctx.send('Service is not working.') r2 = await response.json() if not cached else response if not cached: response.close() self.requestCache[self.Mojang_history.format( uuid=r1['id'])] = r2 users = [escape(m['name']) for m in reversed(r2)] users[0] = f"**{users[0]}**" p = Pages(ctx=ctx, entries=users, per_page=20) p.embed.title = f'{user} past names' p.embed.colour = 0x738bd7 await p.paginate()
def paginate(self, entries, per_page=5): Pages(self, entries=entries, per_page=per_page)