async def me(self, ctx): user = self.get_user(ctx.author.id) if user is None: return await ctx.send("Du har ikke registrert en bruker enda.") (_id, discord_id, auth_token, github_username) = user user = requests.get("https://api.github.com/user", headers={ 'Authorization': "token " + auth_token, 'Accept': 'application/json' }).json() embed = easy_embed(self, ctx) embed.title = user["login"] embed.description = user["html_url"] embed.set_thumbnail(url=user["avatar_url"]) embed.add_field(name="Følgere / Følger", value="{} / {}".format(user["followers"], user["following"]), inline=False) embed.add_field(name="Biografi", value=user["bio"], inline=False) embed.add_field(name="Offentlige repos", value=user["public_repos"], inline=False) return await ctx.send(embed=embed)
async def check(self, ctx, user: discord.Member = None): """ Komanndo for å sjekke stjerner """ if not user: user = ctx.author embed = easy_embed(self, ctx) counter = 0 for msg in self.teller_data['meldinger']: for helper in self.teller_data['meldinger'][msg]['hjelper']: if helper == user.id: counter += 1 if counter <= 5: embed.add_field( name= f"Hjalp {self.bot.get_user(self.teller_data['meldinger'][msg]['giver']).name} her:", value= f"[Link]({self.teller_data['meldinger'][msg]['link']})", inline=False) embed.title = "Boken" desc = f'{user.mention} har {counter} stjerner i boka.' if counter == 1: desc = f'{user.mention} har {counter} stjerne i boka' if 5 <= counter: desc = f'{user.mention} har {counter} stjerner i boka' if 10 <= counter: desc = f'{user.mention} har jobbet bra, her er det {counter} stjerner i boka!' if 15 <= counter: desc = f'{user.mention} har lagt inn en fantastisk jobb, {counter} stjerner i boka!' if embed.fields: desc += f'\n\nViser de {len(embed.fields)} første:' embed.description = desc await ctx.send(embed=embed)
async def auth(self, ctx): """ Kommando for å koble din Github- til din Discord-bruker """ random_string = self.id_generator() is_user_registered = self.is_user_registered(ctx.author.id, random_string) if is_user_registered: return await ctx.reply(ctx.author.mention + " du er allerede registrert!") try: embed = easy_embed(self, ctx) discord_id_and_key = f"{ctx.author.id}:{random_string}" callback = f"{self.bot.settings.github['callback_uri']}" \ f"?params={discord_id_and_key}" registration_link = "https://github.com/login/oauth/authorize" \ f"?client_id={self.bot.settings.github['client_id']}" \ f"&redirect_uri={callback}" embed.title = "Hei! For å verifisere GitHub kontoen din, følg lenken under" embed.description = f"[Verifiser med GitHub]({registration_link})" await ctx.author.send(embed=embed) await ctx.reply(ctx.author.mention + " sender ny registreringslenke på DM!") await asyncio.sleep( 120) # Assume the user uses less than two minutes to auth self._get_users() except discord.Forbidden: raise NoDM except Exception as E: self.bot.logger.warn('Error when verifying Github user:\n%s', E)
async def toproller(self, ctx, antall: int = None): guild_roles = ctx.guild.roles # Avoids fetching roles multiple times. if len(guild_roles) == 1: return await ctx.reply("Serveren har ikke nok roller") if antall is not None: # Had to use "is not" due to 0 being type-casted to False if antall > len(guild_roles) - 1 or antall < 1: return await ctx.reply( f"Du må gi meg et rolleantall som er mellom 1 og {len(guild_roles) - 1}" ) roles = {} for role in guild_roles: if role.name != "@everyone": roles[role.id] = len(role.members) roles = dict( sorted(roles.items(), key=operator.itemgetter(1), reverse=True)) embed = easy_embed(self, ctx) desc = "" counter = 0 _max = antall or 10 for role, members in roles.items(): desc += f"{ctx.guild.get_role(role).mention}: {members}\n" counter += 1 if counter == _max: break embed.description = desc embed.title = f"Viser topp {counter} roller" embed.set_thumbnail(url=self.ico) await ctx.reply(embed=embed)
async def combined_stars(self, ctx): """ Kommando som viser de 15 brukerene med mest stjerner totalt """ embed = easy_embed(self, ctx) tot_stars = {} for repo_ in self.all_repos: repo = self.all_repos[repo_] try: tot_stars[str(repo["discord_user"])] = tot_stars[str( repo["discord_user"])] + repo["stargazers_count"] except KeyError: tot_stars[str(repo["discord_user"])] = repo["stargazers_count"] tot_stars = dict( sorted(tot_stars.items(), key=operator.itemgetter(1), reverse=True)) stop = 15 if (len(tot_stars) >= 15) else len(tot_stars) idrr = list(tot_stars.items()) embed.title = f"{stop} mest stjernede brukere" for n in range(0, stop): discord_user, stars = idrr[n] title = f"⭐:{stars}" desc = f"{self.bot.get_user(int(discord_user)).mention}" embed.add_field(name=title, value=desc, inline=False) return await ctx.reply(embed=embed)
async def add_star(self, message, **kwarg): emoji = self.bot.get_emoji(743471543706976256) emoji_str = f'<:forkast:{emoji.id}>' dudes = {'id': [], 'mention': []} embed = easy_embed(self, message) for dude in message.mentions: if dude is self.bot.user: continue if dude is message.author: continue dudes['id'].append(dude.id) dudes["mention"].append(dude.mention) if not dudes['id']: return await message.add_reaction(emoji) msg_data = { 'hjelper': dudes['id'], 'giver': message.author.id, 'link': message.jump_url } embed.title = "Ny stjerne tildelt!" embed.description = f'{message.author.mention} ga {",".join(dudes["mention"])} en stjerne!' msg = await message.channel.send( f"Registrerer stjerne\nreager med {emoji_str} for å avbryte") await message.channel.trigger_typing() def check(reaction, user): if user is None or user.id != message.author.id: return False if reaction.message.id != message.id: return False if reaction.emoji == emoji or (reaction.emoji == emoji and user.id == 120970603556503552): return True return False try: await self.bot.wait_for('reaction_add', timeout=10.0, check=check) await message.remove_reaction(emoji, self.bot.user) try: await message.remove_reaction(emoji, message.author) except Exception: self.bot.logger.warn( 'Missing permission to remove reaction (manage_messages)') return await msg.delete() except asyncio.TimeoutError: self.teller_data['meldinger'][str(message.id)] = msg_data self.cacher() await msg.edit(content=None, embed=embed) await message.remove_reaction(emoji, self.bot.user) try: return await message.remove_reaction(emoji, message.author) except Exception: return self.bot.logger.warn( 'Missing permission to remove reaction (manage_messages)')
async def _guilds(self, ctx): embed = easy_embed(self, ctx) guilds = "" for guild in self.bot.guilds: guilds += f"{guild.name}\n" embed.description = f"```\n{guilds}\n```" embed.title = f"{self.bot.user.name} is in" await ctx.send(embed=embed)
async def _uptime(self, ctx): embed = easy_embed(self, ctx) now = time.time() diff = int(now - self.bot.uptime) days, remainder = divmod(diff, 24 * 60 * 60) hours, remainder = divmod(remainder, 60 * 60) minutes, seconds = divmod(remainder, 60) embed.description = f"{days}d {hours}h {minutes}m {seconds}s" await ctx.send(embed=embed)
async def _ping(self, ctx): embed = easy_embed(self, ctx) embed.title = "Ping!" start = time.perf_counter() message = await ctx.send(embed=embed) end = time.perf_counter() duration = int((end - start) * 1000) edit = f"Pong!\nPing: {duration}ms | websocket: {int(self.bot.latency * 1000)}ms" embed.description = edit await message.edit(embed=embed)
async def _guilds(self, ctx): """ Komando for å liste servere """ embed = easy_embed(self, ctx) guilds = "" for guild in self.bot.guilds: guilds += f"{guild.name}\n" embed.description = f"```\n{guilds}\n```" embed.title = f"{self.bot.user.name} is in" await ctx.reply(embed=embed)
async def _ping(self, ctx): """ Komando for ping """ embed = easy_embed(self, ctx) embed.title = "Ping!" start = time.perf_counter() message = await ctx.reply(embed=embed) end = time.perf_counter() duration = int((end - start) * 1000) embed.description = f"Pong!\nPing: {duration}ms | websocket: {int(self.bot.latency * 1000)}ms" await message.edit(embed=embed, mention_author=False)
async def show_repos(self, ctx, user: discord.Member = None): """ Viser mest stjernede repoene til brukeren. maks 5 repoer """ is_self = False if not user: user = ctx.author is_self = True gh_user = get_user(self, user.id) if gh_user is None: usr = user.name if is_self: usr = "******" return await ctx.reply(f"{usr} har ikke registrert en bruker enda." ) embed = easy_embed(self, ctx) embed.set_author(name=f"{user.name}#{user.discriminator}", icon_url=user.avatar_url) (_id, discord_id, auth_token, github_username) = gh_user gh_repos = self._get_repos(github_username, auth_token) if len(gh_repos) == 0: return await ctx.reply("Denne brukeren har ingen repos") stars = {} new_obj = {} for gh_repo in gh_repos: if gh_repo["private"]: continue stars[gh_repo["id"]] = gh_repo["stargazers_count"] new_obj[gh_repo["id"]] = gh_repo stars = dict( sorted(stars.items(), key=operator.itemgetter(1), reverse=True)) stop = 5 if (len(stars) >= 5) else len(stars) idrr = list(stars.items()) embed.title = f"{stop} mest stjernede repoer" for n in range(0, stop): repo_id, *overflow = idrr[n] repo = new_obj[repo_id] title = f"{repo['name']} - ⭐:{repo['stargazers_count']}" desc = repo["description"] if not repo["description"]: desc = "Ingen beskrivelse oppgitt" desc += f"\n[Link]({repo['html_url']})" embed.add_field(name=title, value=desc, inline=False) await ctx.reply(embed=embed)
async def syntax(self, ctx): """ Guide på hvoran bruke kodeblokker """ embed = easy_embed(self, ctx) embed.title = "Hvordan få vakre meldinger når man poster kode" embed.description = """ Hei, du kan gjøre koden din mer leselig med å sende koden i kodeblokker.\n\n For vanlig kodeblokk skriv:\n\`\`\`\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)\n\`\`\`\n Den kommer til å se ut som dette:\n```\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)```\n Du kan også definere et språk, for å få syntax highlighting.\n For fargerik kodeblokk skriv:\n\`\`\`js\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)\n\`\`\`\n Den kommer til å se ut som dette:\n```js\nconst dinKode = "Laget av meg"\nconsole.log(dinKode)``` """ # noqa: W605 await ctx.reply(embed=embed)
async def show_discord_user(self, ctx, username): """ Kommando som viser hvilken Discord-bruker som eier en GitHub-konto """ discord_user = get_discord_user(self, username) if discord_user is None: return await ctx.reply( "GitHub-brukeren har ikke knyttet en konto til sin Discord-bruker" ) (_id, discord_id, auth_token, github_username) = discord_user user = self.bot.get_user(discord_id) embed = easy_embed(self, ctx) embed.description = f"Discord-brukeren til `{github_username}` er {user.mention}" return await ctx.reply(embed=embed)
async def show_user(self, ctx, user: discord.Member = None): """ Kommando som viser et sammendrag fra github brukeren """ is_self = False if not user: user = ctx.author is_self = True gh_user = get_user(self, user.id) if gh_user is None: usr = user.name if is_self: usr = "******" return await ctx.reply(f"{usr} har ikke registrert en bruker enda." ) (_id, discord_id, auth_token, github_username) = gh_user gh_user = requests.get("https://api.github.com/user", headers={ "Authorization": "token " + auth_token, "Accept": "application/json" }).json() embed = easy_embed(self, ctx) embed.title = gh_user["login"] embed.description = gh_user["html_url"] embed.set_author(name=f"{user.name}#{user.discriminator}", icon_url=user.avatar_url) embed.set_thumbnail(url=gh_user["avatar_url"]) embed.add_field( name="Følgere / Følger", value=f"{gh_user['followers']} / {gh_user['following']}", inline=False) embed.add_field(name="Biografi", value=gh_user["bio"], inline=False) embed.add_field(name="Offentlige repos", value=gh_user["public_repos"], inline=False) return await ctx.reply(embed=embed)
async def show_users(self, ctx): """ Kommando som viser top 10 stjernede repoer samlet mellom alle registrerte brukere """ embed = easy_embed(self, ctx) stop = 10 if (len(self.all_stars) >= 10) else len(self.all_stars) idrr = list(self.all_stars.items()) embed.title = f"{stop} mest stjernede repoer" for n in range(0, stop): repo_id, *overflow = idrr[n] repo = self.all_repos[repo_id] title = f"{repo['name']} - ⭐:{repo['stargazers_count']}" desc = repo["description"] if not repo["description"]: desc = "Ingen beskrivelse oppgitt" desc += f"\n[Link]({repo['html_url']}) - {self.bot.get_user(repo['discord_user']).mention}" embed.add_field(name=title, value=desc, inline=False) return await ctx.reply(embed=embed)
async def toproller(self, ctx, antall: int = None): roles = {} for role in ctx.guild.roles: if role.name != "@everyone": roles[role.id] = len(role.members) roles = dict( sorted(roles.items(), key=operator.itemgetter(1), reverse=True)) embed = easy_embed(self, ctx) desc = "" counter = 0 _max = antall or 10 for role, members in roles.items(): desc += f"{ctx.guild.get_role(role).mention}: {members}\n" counter += 1 if counter == _max: break embed.description = desc embed.title = f"Viser top {counter} roller" embed.set_thumbnail(url=self.ico) await ctx.send(embed=embed)