Ejemplo n.º 1
0
 async def buildEmbed(user, language_pref, to_next_level, active_roles):
     final_text = ''
     # Checks if the user has a nickname
     nickname = ""
     if hasattr(user, 'nick'):
         if user.nick != None:
             nickname = " AKA \"{}\"".format(user.nick)
         
     # Checks if the user has 'unspecified'
     if ctx.guild.id == 715043968886505484:
         pronoun_role = admin.readDirectory(user, "pronouns")
         if type(admin.readDirectory(user, "pronouns")) == int:
             pronoun_role = get(user.guild.roles, id=admin.readDirectory(user, "pronouns")).name
             
     # Builds the embed
     embed=discord.Embed(color=get(user.guild.roles, id=active_roles["id"]).color, title=user.name + nickname)
     embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["join_date"], value=user.joined_at.strftime("%d/%m/%y, %H:%M"), inline=True)
     embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["language"], value=language_pref, inline=True)
     if ctx.guild.id == 715043968886505484:
         embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["pronouns"], value=pronoun_role, inline=True)
         embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["current_rank"], value=get(user.guild.roles, id=active_roles["id"]).mention + ", \"" + active_roles["translation"] + "\"")
     else:
         embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["current_rank"], value=get(user.guild.roles, id=active_roles["id"]).mention)
     embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["message_count"], value=to_next_level, inline=True)
     if type(admin.readDirectory(user, "na'vi only")) == int:
         final_text += "{} **messages**: {}\n".format(self.bot.get_channel(715050499203661875).mention, admin.readDirectory(user, "na'vi only"))
     final_text += "**{}** {}\n".format(config.text_file[language_pref]["profile"]["embed"]["server_leaderboard"], await self.buildLeaderboard(ctx, user.id, variant, "position"))
     final_text += "**{}** {}\n".format(config.text_file[language_pref]["profile"]["embed"]["times_thanked"], admin.readDirectory(user, "thanks"))
     embed.add_field(name="Additional Stats:", value=final_text, inline=False)
     embed.set_footer(text=config.text_file[language_pref]["profile"]["embed"]["footer"])
     embed.set_thumbnail(url=user.avatar_url) 
     
     return embed
Ejemplo n.º 2
0
 async def eightBall(self, ctx, *args):
     user = ctx.message.author
     question = " ".join(args)
     
     index = random.randint(0,12)
     options = config.text_file[admin.readDirectory(user, "language")]["8ball"]["options"]
     embed = discord.Embed(description=config.text_file[admin.readDirectory(user, "language")]["8ball"]["response"].format(user.mention, question, config.text_file[admin.readDirectory(user, "language")]["8ball"]["options"][index].format(question)))
     
     await ctx.send(embed=embed)
     if index == 12:
         await ctx.send("%q {}".format(question))
Ejemplo n.º 3
0
    async def buildLeaderboard(self, ctx, user_id, variant, requested_info):
        messageCounts = []
        userNames = []
        search_user = ctx.message.guild.get_member(user_id)
        t1 = time.time()
        
        ## -- Builds the Current Leaderboard
        async for member in ctx.guild.fetch_members(limit=None):
            profile = admin.readDirectory(member)
            
            if profile != None:
                if member.nick == None:
                    userNames.append(str(member.name))
                    user = ""
                else:
                    userNames.append(str(member.nick))
                    user = ""
                
                ## -- Checks the variant of leaderboard to build.
                if variant.lower() == "messages":
                    messageCounts.append(admin.readDirectory(member, "message count"))
                elif variant.lower() == "thanks":
                    try:
                        messageCounts.append(admin.readDirectory(member, "thanks"))
                    except:
                        messageCounts.append(0)
            
        sortedUserNames = [x for _,x in sorted(zip(messageCounts, userNames))]
        sortedMessageCounts = sorted(messageCounts)
        sortedUserNames.reverse()
        sortedMessageCounts.reverse()

        ## -- Indexes by the user who is being searched to find their position on the leaderboard
        if search_user.nick == None:
            pos = sortedUserNames.index(search_user.name) + 1
        else:
            pos = sortedUserNames.index(search_user.nick) + 1
            
        tDelta = round(time.time() - t1, 3)

        return {
            "full"    : [sortedUserNames, sortedMessageCounts, pos, tDelta], # Conditional return for !leaderboard
            "position": pos                                                  # Conditional return for !profile
            }.get(requested_info)
Ejemplo n.º 4
0
 async def on_message(self, message):
     user = message.author
     ctx = await self.bot.get_context(message)
     now = datetime.strftime(datetime.now(),'%H:%M')
     
     # If message is in Kelutral
     if message.guild and message.guild.id == 715043968886505484 and hasattr(user, 'top_role'):
         # If message is not a command.
         if not message.content.startswith("!") and not message.content.startswith("?") and not message.content.startswith("%"):
             # If message is in the #nìNa'vi-nì'aw channel
             if message.channel.id == 715050499203661875:
                 profile = admin.readDirectory(user, "na'vi only")
                 if type(profile) == int:
                     admin.writeDirectory(user, "na'vi only", admin.readDirectory(user, "na'vi only") + 1)
                 else:
                     admin.writeDirectory(user, "na'vi only", 1)
             
             # If message is in guild and isn't from the bot.
             if len(message.content) >= 5 and user.top_role.id != config.botRoleID:
                 print(now + " - Analyzing message from {} in {}.".format(user, message.channel.name))
                 try:
                     admin.writeDirectory(user, "message count", admin.readDirectory(user, "message count") + 1)
                 except KeyError:
                     print(now + " -- WARNING: {} does not have a profile!".format(user.name))
                         
                 await admin.roleUpdate(user)
                 admin.updateDirectory()
             
             if message.author.id != config.botID and config.watch_keywords:
                 for keyword in config.watched_phrases:
                     if keyword in message.content.lower():
                         await self.bot.get_channel(config.modLog).send("The following message requires review by an {}: {}".format(get(ctx.guild.roles, id=config.modID).mention, message.jump_url))
             
             if "eytukan" in message.content.lower():
                 await message.add_reaction("👀")
                 
             for user in message.mentions:
                 if config.botID == user.id:
                     responses = config.text_file[admin.readDirectory(user, "language")]["responses"]
                     index = random.randint(0,len(responses)-1)
                     await ctx.send(responses[index].format(message.guild.get_member(723257649055006740).mention))
                 
         elif message.content.startswith("!") and message.author.id == 723257649055006740:
             question = message.content.replace("!8ball ", "")
             
             options = config.text_file[admin.readDirectory(user, "language")]["8ball"]["options"]
             index = random.randint(0, len(options) - 1)
             embed = discord.Embed(description=config.text_file[admin.readDirectory(user, "language")]["8ball"]["response"].format(user.mention, question, config.text_file[admin.readDirectory(user, "language")]["8ball"]["options"][index]))
             
             await ctx.send(embed=embed)
Ejemplo n.º 5
0
    async def profile(self, ctx, user: discord.Member, *setting):
        preference = ''.join(setting).lower()
        variant = "messages"
        
        # Function for building the final profile output
        async def buildEmbed(user, language_pref, to_next_level, active_roles):
            final_text = ''
            # Checks if the user has a nickname
            nickname = ""
            if hasattr(user, 'nick'):
                if user.nick != None:
                    nickname = " AKA \"{}\"".format(user.nick)
                
            # Checks if the user has 'unspecified'
            if ctx.guild.id == 715043968886505484:
                pronoun_role = admin.readDirectory(user, "pronouns")
                if type(admin.readDirectory(user, "pronouns")) == int:
                    pronoun_role = get(user.guild.roles, id=admin.readDirectory(user, "pronouns")).name
                    
            # Builds the embed
            embed=discord.Embed(color=get(user.guild.roles, id=active_roles["id"]).color, title=user.name + nickname)
            embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["join_date"], value=user.joined_at.strftime("%d/%m/%y, %H:%M"), inline=True)
            embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["language"], value=language_pref, inline=True)
            if ctx.guild.id == 715043968886505484:
                embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["pronouns"], value=pronoun_role, inline=True)
                embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["current_rank"], value=get(user.guild.roles, id=active_roles["id"]).mention + ", \"" + active_roles["translation"] + "\"")
            else:
                embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["current_rank"], value=get(user.guild.roles, id=active_roles["id"]).mention)
            embed.add_field(name=config.text_file[language_pref]["profile"]["embed"]["message_count"], value=to_next_level, inline=True)
            if type(admin.readDirectory(user, "na'vi only")) == int:
                final_text += "{} **messages**: {}\n".format(self.bot.get_channel(715050499203661875).mention, admin.readDirectory(user, "na'vi only"))
            final_text += "**{}** {}\n".format(config.text_file[language_pref]["profile"]["embed"]["server_leaderboard"], await self.buildLeaderboard(ctx, user.id, variant, "position"))
            final_text += "**{}** {}\n".format(config.text_file[language_pref]["profile"]["embed"]["times_thanked"], admin.readDirectory(user, "thanks"))
            embed.add_field(name="Additional Stats:", value=final_text, inline=False)
            embed.set_footer(text=config.text_file[language_pref]["profile"]["embed"]["footer"])
            embed.set_thumbnail(url=user.avatar_url) 
            
            return embed
        
        # Time start
        t1 = time.time()
        
        # Pulls necessary information from the user profile
        message_count = admin.readDirectory(user, "message count")
        language_pref = admin.readDirectory(user, "language")
        if ctx.guild.id == 748700165266866227:
            active_roles = pr_admin.readDirectory(user, "pr_rank")
        else:
            active_roles = admin.readDirectory(user, "rank")
        
        # Retrieves the current and next rank from Discord
        current_rank = get(ctx.guild.roles, id=active_roles["id"])
        if ctx.guild.id == 748700165266866227:
            try:
                next_rank_index = config.prIDs.index(current_rank.id) - 1
            except AttributeError:
                next_rank_index = config.prIDs.index(782980232746893343)
            next_rank = get(ctx.guild.roles, id=config.prIDs[next_rank_index])
            next_rank_translation = next_rank.name
        else:
            next_rank_index = config.activeRoleIDs.index(current_rank.id) - 1
            next_rank = get(ctx.guild.roles, id=config.activeRoleIDs[next_rank_index])
            for entry in config.activeRoleDict:
                if entry[0] == next_rank.id:
                    next_rank_translation = entry[1]
                    break
        
        # Checks the total messages sent against the threshold.
        for i, count in enumerate(config.activeRoleThresholds):
            if message_count >= count and i == 0:
                toNextLevel = 0
                break
            elif message_count >= count:
                toNextLevel = config.activeRoleThresholds[i - 1] - int(message_count)
                break
            elif message_count <= 8:
                toNextLevel = 8 - int(message_count)
                break
        
        output2 = str(toNextLevel)
            
        # Checks the command arguments for updated language preference
        # No update
        if preference == "":
            preference = language_pref
            if preference == "Na'vi":
                str_message_count = bot.wordify(str(oct(message_count))[2:]).capitalize()
                output2 = bot.wordify(str(oct(toNextLevel))[2:])
            elif preference == "English":
                str_message_count = str(message_count)
                
            if toNextLevel < 0:
                to_next_level = config.text_file[language_pref]["profile"]["max_rank"].format(str_message_count)
            else:
                to_next_level = config.text_file[language_pref]["profile"]["rank_progress"].format(str_message_count, output2, next_rank.mention, next_rank_translation)
            
            embed = await buildEmbed(user, language_pref, to_next_level, active_roles)
        # Update
        elif user.id == ctx.message.author.id:
            if preference.capitalize() == "Na'vi":
                str_message_count = bot.wordify(str(oct(message_count))[2:]).capitalize()
                output2 = bot.wordify(str(oct(toNextLevel))[2:])
            elif preference.capitalize() == "English":
                str_message_count = str(message_count)
            else:
                await ctx.send(embed=discord.Embed(description=config.text_file[language_pref]["errors"]["profile"] + config.text_file[language_pref]["errors"]["profile_errors"]["invalid_language"], color=config.failColor))
                return
            
            language_pref = preference.capitalize()
            admin.writeDirectory(user, "language", language_pref)

            if toNextLevel < 0:
                to_next_level = config.text_file[language_pref]["profile"]["max_rank"].format(str_message_count)
            else:
                to_next_level = config.text_file[language_pref]["profile"]["rank_progress"].format(str_message_count, output2, next_rank.mention, next_rank_translation)
            
            embed = await buildEmbed(user, language_pref, to_next_level, active_roles)
        # Invalid entry
        else:
            embed=discord.Embed(description=config.text_file[language_pref]["errors"]["profile"] + config.text_file[language_pref]["errors"]["profile_errors"]["missing_perms"], color=config.failColor)
               
        # Checks debug state and sends final embed.
        if config.debug:
            embed.set_footer(text="Executed in {} seconds.".format(round(time.time() - t1, 3)))
        await ctx.send(embed=embed)
Ejemplo n.º 6
0
 async def thanks(self, ctx):
     language = admin.readDirectory(ctx.message.author, "language")
     await ctx.send(config.text_file[language]["thanks"].format(ctx.message.author.mention))
Ejemplo n.º 7
0
    async def on_raw_reaction_add(self, payload):
        channel = await self.bot.fetch_channel(payload.channel_id)
        if payload.guild_id == config.KTID or isinstance(channel, discord.DMChannel):
            added_emoji = payload.emoji
            guild = self.bot.get_guild(715043968886505484)
            
            if payload.member == None:
                member = guild.get_member(payload.user_id)
            else:
                member = payload.member
                
            emoji = ['<:irayo:715054886714343455>','<:prirayo:782966329317654569>'] 
            fileName = 'files/config/reactions.txt'

            if isinstance(channel, discord.DMChannel):
                if member.id != config.botID:
                    emojis = ['♂️','♀️','🏳️‍🌈','♾️']
                    pronounRole = ['He/Him','She/Her','They/Them','Any Pronouns']
                    
                    if added_emoji.name in emojis:
                        profile = admin.readDirectory(member)
                        pronouns = admin.readDirectory(member, "pronouns")
                        now = datetime.strftime(datetime.now(),'%H:%M')
                        
                        index = emojis.index(added_emoji.name)
                        role_to_add = get(guild.roles, name=pronounRole[index])
                        
                        if pronouns == role_to_add.id:
                            await member.send("You already have that role!")
                            print(now + " -- {} attempted to add the {} pronouns, but they already had them.".format(member.name, role_to_add.name))
                        elif pronouns != "Unspecified":
                            old_role = get(guild.roles, id=profile['pronouns'])
                            await member.remove_roles(old_role)
                            await member.add_roles(role_to_add)
                            await member.send("Removed {} and added {}.".format(old_role.name, role_to_add.name))
                            print(now + " -- {} swapped from {} pronouns to {} ones.".format(member.name, old_role.name, role_to_add.name))
                        else:
                            await member.add_roles(role_to_add)
                            await member.send("Successfully added you to {}.".format(role_to_add.name))
                            print(now + " -- {} was given the {} pronouns.".format(member.name, role_to_add.name))
                        
                        admin.writeDirectory(member, 'pronouns', role_to_add.id)
                        return
            
            # If reaction was added by the message author (sneaky sneaky!)
            message = await channel.fetch_message(payload.message_id)
            if message.author.id == payload.user_id:
                return
            else:
                with open(fileName, 'r') as fh:
                    contents = json.load(fh)
                
                # Checks to see if the reaction adder has already added a reaction to that message (prevents duplication)
                if str(added_emoji) in emoji: 
                    check = [message.id, payload.user_id]
                    if check not in contents:
                        contents.append([message.id, payload.user_id])
                        timesThanked = admin.readDirectory(message.author, "thanks")
                        
                        timesThanked += 1
                        
                        # Updates the reactions log
                        with open(fileName, 'w') as fh:
                            json.dump(contents, fh)
                
                    admin.writeDirectory(message.author, "thanks", timesThanked)
                admin.updateDirectory()
Ejemplo n.º 8
0
    async def on_member_join(self, member):
        if member.guild.id == 715043968886505484:
            channel = self.bot.get_channel(config.modLog)
            roles = member.guild.roles
            now = datetime.strftime(datetime.now(),'%H:%M')
            
            embed=discord.Embed(color=config.successColor)
            embed.set_thumbnail(url=member.avatar_url)
            embed.set_author(name="Member Joined",icon_url=member.avatar_url)
            embed.add_field(name="New Member:", value=str(member.mention) + " " + str(member), inline=False)
            embed.set_footer(text="ID: {} • Today at {}".format(member.id, datetime.now().strftime('%H:%M EST')))
            await channel.send(embed=embed)
            
            # Checks the Blacklist for Blacklisted IDs
            fileName = 'files/blacklist.txt'
            with open(fileName, 'r', encoding='utf-8') as fh:
                lines = fh.readlines()

            setLines = set(lines)
            
            if str(member.id) in setLines:
                print(now + " -- Found this user in the blacklist.")
                if member.dm_channel is None:
                       await member.create_dm()
                await member.send("Sorry, you are forbidden from joining Kelutral.org.")
                await member.ban()
                print(now + " -- " + member.name + " was banned.")
                
                target = member.guild.get_member(config.makoID)
                await target.send("{} attempted to join Kelutral.org.".format(member.name))
                
                return
            
            print(now + " -- {} joined the server.".format(member.name))
            # This will automatically give anyone the 'frapo' role when they join the server.
            
            frapoRole = get(member.guild.roles, name="frapo")
            await member.add_roles(frapoRole)

            print(now + " -- Gave {} the role {}.".format(member.name, frapoRole.name))
            
            with open('cogs/shared/files/kelutral/server_info.json', 'r', encoding='utf-8') as fh:
                server_info = json.load(fh)
            
            date = datetime.now().strftime("%m-%d-%Y")
            try:
                today_dict = server_info[date]
                today_dict['joins'] += 1
            except KeyError:
                server_info[date] = {
                    "joins" : 1,
                    "leaves" : 0,
                    "rds" : 0
                    }
            
            with open('cogs/shared/files/kelutral/server_info.json', 'w', encoding='utf-8') as fh:
                json.dump(server_info, fh)
            
            try:
                emojis = ['\U00002642','\U00002640','\U0001F3F3\U0000fe0f\U0000200d\U0001f308','\U0000267E']
                if member.dm_channel is None:
                    await member.create_dm()
                embed=discord.Embed()
                embed=discord.Embed(title="Welcome to the Kelutral.org Discord Server!", colour=config.welcomeColor)
                welcome_channel = await self.bot.fetch_channel(718309284705861647)
                embed.add_field(name="**Fwa ngal fìtsengit sunu ayoer!**", value="We are glad that you are here!\n\nWhen you get the chance, please read our rules and information channels to familiarize yourself with our code of conduct and roles. After that, please introduce yourself in {} so that a moderator can assign you the proper role.\n\nIf you would like to personally assign your own pronouns, you can react to this message with {}, {}, {} or {} (He/Him, She/Her, They/Them or Any Pronouns). If you want to change this selection at any time, simply add the corresponding reaction to any message Eytukan sends in DMs.\n\n**Zola'u nìprrte' ulte siva ko!** Welcome, let's go!".format(welcome_channel.mention, emojis[0],emojis[1],emojis[2],emojis[3]), inline=False)

                message = await member.send(embed=embed)
                
                pronounRole = ['He/Him','She/Her','They/Them','Any Pronouns']
                for emoji in emojis:
                    await message.add_reaction(emoji)
            except:
                now = datetime.strftime(datetime.now(),'%H:%M')
                print(now + " -- Cannot DM this user.")
                pronounChoice = "Unspecified"
                
            # This creates a profile for new joins.
            pronouns = "Unspecified"
            profile = admin.readDirectory(member)
            
            if profile != None:
                print(now + " -- This user already has an existing profile. Skipping generation of a new profile.")
                if type(profile['pronouns']) == int:
                    role_to_add = get(member.guild.roles, id=profile['pronouns'])
                    await member.add_roles(role_to_add)
                    print(now + " -- {} previously had the pronouns {}. Assigning now.".format(member.name, role_to_add.name))
            else:
                config.directory[str(member.id)] = {
                                                    "id" : member.id,
                                                    "message count" : 0,
                                                    "name" : member.name,
                                                    "language" : "English",
                                                    "pronouns" : pronouns,
                                                    "rank" : {
                                                        "id" : config.frapoID,
                                                        "translation" : "Everyone"
                                                    },
                                                    "thanks" : 0
                                                }
                print(now + " -- Created a new profile for {}.".format(member.name))
            admin.updateDirectory()