async def set_member_color(self, user: discord.Member, color: str) -> discord.Role: """Applique la couleur demandée au membre en supprimant les anciens qu'il pourrait posséder Renvoie le rôle désormais possédé""" await self.bot.wait_until_ready() guild = user.guild all_colors = await self.config.guild(guild).roles() rolename = self.format_color(color, '#') user_colored_roles = [r for r in user.roles if r.name in all_colors] if rolename not in (r.name for r in user.roles): del_roles = user_colored_roles role = None for r in user_colored_roles: if self.get_members_with(r) == [user]: role = await self.replace_guild_color(r, color) del_roles.remove(r) break if del_roles: await user.remove_roles(*del_roles) await self.safe_bulk_clear_guild_colors( guild, [r.name for r in del_roles]) if not role: role = await self.create_guild_color(guild, color) await user.add_roles(role, reason="Attribution d'un rôle coloré") return role return discord_get(guild.roles, name=self.format_color(color, "#"))
async def delim(self, ctx, role: discord.Role = None): """Attribue le rôle de délimiteur à un rôle pour ranger auto. les rôles créés Les rôles créés seront automatiquement rangés sous le rôle délimiteur si celui-ci est défini Si le rôle donné est le même que celui enregistré précédemment, met à jour le positionnement des rôles""" guild = ctx.guild if role: if role.id != await self.config.guild(guild).delimiter(): await self.config.guild(guild).delimiter.set(role.id) await ctx.send( f"**Rôle délimiteur modifié** • Les rôles colorés se rangeront auto. sous ***{role.name}*** " f"dans la liste de rôles lors de leur création") delimpos = role.position all_roles = await self.config.guild(guild).roles() for r in all_roles: check = discord_get(guild.roles, name=r) if check: setpos = delimpos - 1 if delimpos > 1 else 1 await check.edit(position=setpos) await ctx.send( f"**Rôles rangés** • Les rôles ont été rangés conformément aux paramètres" ) else: await self.config.guild(guild).delimiter.set(None) await ctx.send( f"**Rôle délimiteur retiré** • Les rôles colorés ne se rangeront plus automatiquement (déconseillé)" )
async def get_emojis_webhook(ctx: Context) -> Webhook: """ Find the CustomEmojis webhook, or create it if it doesn't exist. """ webhooks = await ctx.channel.webhooks() emojis_webhook = discord_get(webhooks, name="CustomEmojis") return emojis_webhook or await ctx.channel.create_webhook( name="CustomEmojis")
async def jail_role(self, ctx, role: Union[discord.Role, bool] = None): """Définir le rôle de la prison Si aucun rôle n'est donné, celui-ci est créé automatiquement (si non déjà présent) Mettre 'False' désactive la prison""" guild = ctx.guild jail = await self.config.guild(guild).jail_settings() if type(role) == discord.Role: jail["role"] = role.id await ctx.send(f"**Rôle modifié** » Le rôle {role.mention} sera désormais utilisé pour la prison\n" f"Faîtes `[p]pset check` pour régler automatiquement les permissions. " f"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.") elif role != False: maybe_role = discord_get(guild.roles, name="Prisonnier") if maybe_role: jail["role"] = maybe_role.id await ctx.send( f"**Rôle détecté** » Le rôle {maybe_role.mention} sera désormais utilisé pour la prison\n" f"Faîtes `[p]pset check` pour régler automatiquement les permissions. " f"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.") else: role = await guild.create_role(name="Prisonnier", color=discord.Colour.default(), reason="Création auto. du rôle de prisonnier") jail["role"] = role.id await ctx.send(f"**Rôle créé** » Le rôle {role.mention} sera désormais utilisé pour la prison\n" f"Faîtes `[p]pset check` pour régler automatiquement les permissions. " f"Sachez que vous devez manuellement monter le rôle à sa place appropriée dans la hiérarchie.") else: jail['role'] = None await ctx.send(f"**Rôle retiré** » La prison a été désactivée.") await self.config.guild(guild).jail_settings.set(jail) if jail["role"]: role = guild.get_role(jail["role"]) await self.check_jail_role_perms(role)
async def get_colors_cache(self, ctx): """Affiche ce que contient le cache des rôles de couleur""" roles = await self.config.guild(ctx.guild).roles() txt = "\n".join([discord_get(ctx.guild.roles, name=r) for r in roles]) if txt: await ctx.send(txt) else: await ctx.send("**Cache vide**")
async def safe_clear_guild_color(self, guild: discord.Guild, color: str) -> bool: """Vérifie que des membres ne possèdent plus la couleur et supprime le rôle coloré""" name = self.format_color(color, "#") role = discord_get(guild.roles, name=name) if role: if not self.get_members_with(role): await role.delete( reason="Suppression de rôle de couleur obsolète") await self.remove_color_from_cache(guild, color) return True return False
async def init_emotes(): standard_characters = 'uoaeyiwUOAEYIWpbtdkgmnqjrlRfFsSxhvVzZ' special_mappings = { 'ú': 'u_', 'ó': 'o_', 'á': 'a_', 'é': 'e_', 'ý': 'y_', 'í': 'i_', '\xb5': 'w_', ' ': 'space', '.': 'dot', ',': 'comma', '?': 'question', '#': 'direction' } for c in standard_characters: emotes[c] = str( discord_get(runicbabble.discord.client.emojis, name=f'mdj_{c}')) for c, v in special_mappings.items(): emotes[c] = str( discord_get(runicbabble.discord.client.emojis, name=f'mdj_{v}'))
async def send_notification(context): # Check if channel is present in guild global already_sent channel = discord_get( context.guild.text_channels, name=config.DISCORD_CHANNEL, ) if channel is None: # else use the context print( f'[Notifications] Cannot find channel {config.DISCORD_CHANNEL}\n') channel = context try: notifications = get_github_notifications() notifications = json.loads(notifications) except Exception as err: print(f'Exception Occured. {str(err)}') notifications = None if notifications is None: if context.message: await context.message.reply else: await context.guild.send( "There was some error in getting notifications....\nTry Later." ) return # Loop through notifications and check if already sent for notifi in notifications: if notifi["id"] in already_sent[:100]: break # Log Current Notification to Console print(f'[Notification] ID: {notifi["id"]}') print(f'[Notification] Title: {notifi["subject"]["title"]}') print(f'[Notification] Updated At: {notifi["updated_at"]}') print(f'[Notification] URL: {notifi["subject"]["url"]}') # Get URL to the notification subject direct_url = str(notifi["subject"]["url"]).replace( "api.github", "github").replace("/repos/", "/") # Make a new message and send it embededMessage = discord.Embed( title=f'{notifi["id"]} - {notifi["subject"]["title"]}', url=direct_url, description= f'Reason: {notifi["reason"]}\nUpdated At: {notifi["updated_at"]}\nURL: {direct_url}', color=discord.Color.blue()) # Add the notification ID to list of already sent, so it does'nt repeat already_sent.insert(0, notifi["id"]) await channel.send(embed=embededMessage) return
async def join_default_channel(self, member): if self.voice: return default_name = 'Praying with Zulia' channel = find( lambda m: m.id == member.id and m.server.id == member.server.id and m.voice_channel is not None, member.server.members) if channel is not None: await self.zulia.join_voice_channel(channel.voice_channel) return channel = discord_get(member.server.channels, name=default_name) await self.zulia.join_voice_channel(channel)
async def cache_roles(self) -> None: """Store target scores and corresponding role objects.""" print('Waiting for bot to become available...') await self.bot.wait_until_ready() self.caramella_crew = self.bot.get_guild(684524607889473584) role_list = { 0: 'unenlightened', 600: 'Caramella Babies - 10 Minutes', 3600: 'Caramella Fans - 1 Hour', 43200: 'Caramella Captains - 12 Hours', 86400: 'Caramella Dancers - 1 Day' } for amount, name in role_list.items(): role_list[amount] = discord_get(self.caramella_crew.roles, name=name) self.role_list = role_list
async def is_regular(self, ctx: commands.Context): """Checks if they can be trusted to add help commands""" regular_roles = { 'Founder': 469158572417089546, 'Moderator': 490250496028704768, 'UT Discord Admin': 667104998714245122 } for role_id in regular_roles: test_role = discord_get(ctx.guild.roles, id=regular_roles[role_id]) if test_role in ctx.author.roles: return True await ctx.send("You do not have permission to do that") return False
async def deleteall_colors(self, ctx): """Supprime tous les rôles colorés créés par le bot""" guild = ctx.guild aut = str(ctx.author) all_roles = await self.config.guild(guild).roles() count = 0 for r in all_roles: role = discord_get(guild.roles, name=r) if role: await role.delete( reason=f"Suppression du rôle sur demande de {aut}") count += 1 await self.config.guild(guild).clear_raw("roles") await ctx.send( f"**Suppression réalisée** • {count} rôles ont été supprimés")
async def safe_bulk_clear_guild_colors(self, guild: discord.Guild, colors: list) -> list: """Vérifie que des membres ne possèdent pas les couleurs données et supprime les rôles obsolètes Retourne une liste des noms des rôles supprimés""" await self.bot.wait_until_ready() names = [self.format_color(c, '#') for c in colors] logs = [] for name in names: role = discord_get(guild.roles, name=name) if role: if not self.get_members_with(role): await role.delete( reason="Suppression de rôle de couleur obsolète") await self.remove_color_from_cache(guild, name) logs.append(name) return logs
async def on_play(self, msg, msg_obj): await self.join_default_channel(msg_obj.author) # Find a bot channel if we have one... if msg_obj.channel.name != 'bot': channel = discord_get(msg_obj.server.channels, name='bot') self.channel = channel or msg_obj.channel if 'playlist' not in msg[1]: song = await self.extract_info(url=msg[1], download=True) song['requestor'] = msg_obj.author.name if msg[-1] == 'side': self.side_playlist.append(song) self.use_side_playlist = True else: self.playlist.append(song) else: t = time() items = await self.extract_info(url=msg[1], process=False, download=False) playlist_task = gather(*(self.process_info(item) for item in items['entries'])) playlist = await playlist_task playlist = [x for x in playlist if x] end = time() await self.zulia.send_message( msg_obj.channel, '```Loaded: %s songs in %s seconds.```' % (len(playlist), end - t)) if msg[-1] == 'shuffle': for i in range(0, 5): shuffle(playlist) for song in playlist: song['requestor'] = msg_obj.author.name self.playlist.extend(playlist) if not self.current_song: self.play() if len(self.playlist) > 1: await self.on_queue(msg, msg_obj)
async def create_guild_color(self, guild: discord.Guild, color: str) -> discord.Role: """Crée un rôle avec la couleur demandée et le range si le délimiteur est configuré Retourne le rôle créé (ou trouvé si déjà présent)""" await self.bot.wait_until_ready() rolename = self.format_color(color, "#") role = discord_get(guild.roles, name=rolename) if not role: rolecolor = int(self.format_color(color, '0x'), base=16) await self.add_color_to_cache(guild, color) role = await guild.create_role( name=rolename, color=discord.Colour(rolecolor), reason="Création de rôle de couleur", mentionable=False) await self.sort_role(guild, role) return role
async def play_song(self): # if we're currently paused, resume our player. if self.paused: if self.music_player: self.paused = False self.music_player.resume() # if for some reason we're not connected, join our default channel (why networking why?!) if not self.voice: # default to AFK channel.. channel = discord_get(self.channel.server.channels, name='Praying With Zulia') await self.zulia.join_voice_channel(channel) # We do NOT want to have multiple songs attempting to play. with await self.music_lock: try: # I hate you Julia. if not self.use_side_playlist and not len(self.side_playlist): self.current_song = self.playlist.pop(0) else: self.current_song = self.side_playlist.pop(0) self.use_side_playlist = False except: return # Create our music player and send our info to the channel. self.music_player = self.voice.create_ffmpeg_player( '/tmp/' + self.current_song['id'], use_avconv=True) self.music_player.loops = 0 #??? self.music_player.after = lambda: self.zulia.loop.call_soon_threadsafe( self.on_finished) await self.send_np(self.channel) self.music_player.start() self.music_player.volume = self.volume
async def is_brandon(self, ctx: commands.Context): """Checks if I ran this""" brandon = discord_get(ctx.guild.members, id=158062741112881152) return brandon == ctx.author