示例#1
0
    async def endMassSpeedsSession(self, ctx):
        """
        Callable function to end the current session. Clears the participant list

        """
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        if "msActive" in settings.keys():
            if settings["msActive"] == True:
                await self.message.delete()
                settings["msActive"] = False
            elif settings["msActive"] == False:
                await ctx.send("MS was not running.")
        else:
            settings["msActive"] = False

        MSfname = "massSpeeds/" + ctx.guild.name.replace(" ", "") + ".json"
        players = jsonHandling.loadJSON(MSfname)
        jsonHandling.dumpJSON(MSfname, {})

        jsonHandling.dumpJSON(fname, settings)
        for x in players.keys():
            member = ctx.guild.get_member(int(x))
            role = get(ctx.guild.roles, name="Mass Speeds")
            if role in member.roles:
                await member.remove_roles(role)

        if len(self.teamMessages) > 0:
            for x in range(len(self.teamMessages)):
                msg = self.teamMessages.pop()
                await msg.delete()
示例#2
0
    async def whitelistChannel(self, ctx):
        """
        Callable function for admins to whitelist the current channel. This approves certain functions to be called and gives more in-depth information for some functions

        """
        try:
            fname = "guildsettings/" + ctx.guild.name.replace(" ",
                                                              "") + ".json"

            if os.path.exists(fname):
                settings = jsonHandling.loadJSON(fname)
            else:
                settings = {}

            # check if any channels have ever been whitelisted
            if "whitelistedChannels" in settings.keys():
                settings["whitelistedChannels"].append(ctx.message.channel.id)
            else:
                settings["whitelistedChannels"] = []
                settings["whitelistedChannels"].append(ctx.message.channel.id)

            jsonHandling.dumpJSON(fname, settings)
            await ctx.send("Channel added to the whitelist.")
        except Exception as e:
            print(e)
示例#3
0
    async def renameVouchee(self, ctx, user: str, newName: str):
        """
        Callable function for an admin to rename a vouchee in the system

        Parameters:
        user - String of the name of the vouchee/antivouchee in the system
        newName - String of the new name to use

        """
        print(
            "------------------------------ beginning renameVouchee() ------------------------------"
        )
        if self.whitelistCheck(ctx) == False:
            await ctx.send("This command is not allowed in this channel.")

        fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
        vouches = jsonHandling.loadJSON(fname)

        data = vouches.pop(user.lower())
        vouches[newName.lower()] = data

        jsonHandling.dumpJSON(fname, vouches)

        await ctx.send("Rename complete.")
        print(
            "------------------------------ ending renameVouchee() ------------------------------"
        )
示例#4
0
    async def updateMessage(self, ctx):
        """
        Callable function to update the table to the latest vouches

        """
        print(
            "------------------------------ beginning updateMessage() ------------------------------"
        )
        #load server settings
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)

        #delete the message that sent this command
        usersMessage = ctx.message
        await usersMessage.delete()

        #find the channel + message ID that will be updated
        channel = self.bot.get_channel(
            settings["updatingVouchMessage"]["channelID"])
        message = await channel.fetch_message(
            settings["updatingVouchMessage"]["messageID"])

        #get the allVouches message
        newmessage = await self.allVouches(ctx, True)

        #edit the message with the new embed
        await message.edit(embed=newmessage)
        print(
            "------------------------------ ending updateMessage() ------------------------------"
        )
示例#5
0
    async def updatingmessage(self, ctx):
        """
        Callable function to create a table that can be filled with vouches

        """
        print(
            "------------------------------ beginning updatingmessage() ------------------------------"
        )
        # delete the senders message
        usersMessage = ctx.message
        await usersMessage.delete()

        # create a new message and send it
        message = await ctx.send(embed=discord.Embed(
            title="Type update message to initalise me."))

        # store the details of the sent message
        updatingVouchMessage = {
            "messageID": message.id,
            "channelID": message.channel.id
        }

        # load server settings
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)

        # update details of updating vouch message
        settings["updatingVouchMessage"] = updatingVouchMessage

        # save details
        jsonHandling.dumpJSON(fname, settings)
        print(
            "------------------------------ ending updatingmessage() ------------------------------"
        )
示例#6
0
    async def removeWhitelistChannel(self, ctx):
        """
        Callable function for admins to no longer whitelist the current channel

        """
        try:
            fname = "guildsettings/" + ctx.guild.name.replace(" ",
                                                              "") + ".json"
            print(fname)
            if os.path.exists(fname):
                settings = jsonHandling.loadJSON(fname)
            else:
                settings = {}

            # check if any channels have ever been whitelisted
            if "whitelistedChannels" in settings.keys():
                # try to remove the channel this message was sent from
                try:
                    settings["whitelistedChannels"].remove(
                        ctx.message.channel.id)

                # will throw an error if doesn't exist, so tell user it wasn't ever whitelisted.
                except Exception as e:
                    await ctx.send("This channel wasn't whitelisted.")
            # tell user that no channels have ever been whitelisted in this server
            else:
                await ctx.send(
                    "No channels have ever been whitelisted in this server.")

            jsonHandling.dumpJSON(fname, settings)
            await ctx.send("Channel removed from the whitelist.")
        except Exception as e:
            print(e)
示例#7
0
    async def forceCheckRole(self, ctx):
        """
        Checking function. Lists all users who have the role and in JSON

        """
        usersMessage = ctx.message
        await usersMessage.delete()
        MSfname = "massSpeeds/" + ctx.guild.name.replace(" ", "") + ".json"
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        if "msActive" not in settings.keys():
            await ctx.send(
                "No mass speeds session in progress. <a:EB:744967488751665303> (Not in settings)"
            )
            return

        if settings["msActive"] == False:
            await ctx.send(
                "No mass speeds session in progress. <a:EB:744967488751665303> (MS Session = False)"
            )
            return

        players = {}

        MSrole = get(ctx.guild.roles, name="Mass Speeds")

        for x in ctx.guild.members:
            if MSrole in x.roles and x.id != self.prodDGSBotID and x.id != self.testDGSBotID:
                players[x.id] = 0

        jsonHandling.dumpJSON(MSfname, players)
        await ctx.send(players)
示例#8
0
    async def startMassSpeedsSession(self, ctx):
        """
        Callable function to begin a mass speeds session. Initializes the participant list and creates a reactable message

        """
        usersMessage = ctx.message
        await usersMessage.delete()
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        if "msActive" in settings.keys():
            if settings["msActive"] == False:
                message = await ctx.send(
                    "React to this message to join the mass speeds session.")
                self.messageID = message
                self.message = message
                await message.add_reaction("<a:EB:744967488751665303>")
                settings["msActive"] = True
            elif settings["msActive"] == True:
                await ctx.send("MS session already running!")
        else:
            settings["msActive"] = True

        MSfname = "massSpeeds/" + ctx.guild.name.replace(" ", "") + ".json"
        jsonHandling.dumpJSON(MSfname, {})

        jsonHandling.dumpJSON(fname, settings)
示例#9
0
def addBuffer(serverName, bufferType, data):
    """
        Helper function to add arbitrary data to the buffer you specify. Assigns a unique ID for the data within that buffer

        Parameters:
        bufferType - string name of the buffer to add to: for example, "vouches"
        data - data to add to the buffer
    """
    # generate filename of settings file
    settingsFileName = "guildsettings/" + serverName + ".json"

    # load settings info
    if os.path.exists(settingsFileName):
        settings = jsonHandling.loadJSON(settingsFileName)
    else:
        settings = {}

    # determine which ID to grab
    IDType = bufferType + "IDcounter"

    # get unique ID of new buffer item
    try:
        ID = settings[IDType]
        settings[IDType] = settings[IDType] + 1
    except Exception as e:
        print(e)
        ID = 1
        settings[IDType] = ID + 1

    # update settings file
    jsonHandling.dumpJSON(settingsFileName, settings)

    # generate filename of buffer file for this server + buffer type
    buffername = "buffers/" + serverName + bufferType + ".json"
    print("buffername", buffername)
    # load buffer
    if os.path.exists(buffername):
        testBuffer = jsonHandling.loadJSON(buffername)
    else:
        testBuffer = {}

    # add data to the buffer at correct ID
    testBuffer[ID] = data

    # save the buffer data
    jsonHandling.dumpJSON(buffername, testBuffer)
    return
示例#10
0
def getAllBufferData(serverName, bufferType):
    """
        Helper function to get all data from a specific buffer

        Parameters:
        bufferType - string name of the buffer to view: for example, "vouches"
    """
    buffername = "buffers/" + serverName + bufferType + ".json"
    bufferData = jsonHandling.loadJSON(buffername)
    return bufferData
示例#11
0
    def joinMassSpeeds(self, guild, member):
        """
        Adds member to the list of active participants. Triggered by reacting to the emote in the bot message

        Parameters:
        Member - Discord ID for the user who reacted
        """
        MSfname = "massSpeeds/" + guild.name.replace(" ", "") + ".json"
        players = jsonHandling.loadJSON(MSfname)
        players[str(member.id)] = 0
        jsonHandling.dumpJSON(MSfname, players)
示例#12
0
    def leaveMassSpeeds(self, guild, member):
        """
        Remove member from the list of active participants. Triggered by removing reaction to the emote in the bot message

        Parameters:
        Member - Discord ID for the user who reacted
        """
        # remove participant from the JSON file
        MSfname = "massSpeeds/" + guild.name.replace(" ", "") + ".json"
        players = jsonHandling.loadJSON(MSfname)
        players.pop(str(member.id))
        jsonHandling.dumpJSON(MSfname, players)
示例#13
0
    async def resetMassSpeeds(self, ctx):
        """
        Callable function to reset the Mass Speeds Session

        """
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        settings["msActive"] = False
        jsonHandling.dumpJSON(fname, settings)

        MSfname = "massSpeeds/" + ctx.guild.name.replace(" ", "") + ".json"
        jsonHandling.dumpJSON(MSfname, {})
示例#14
0
    async def antivouch(self, ctx, user: str, *argv):
        """
        Callable function for a DGS rank to antivouch someone

        Parameters:
        user - string of the name of the vouchee
        *argv - additional arguments. Intended as a description of the reasoning for a antivouch

        """
        print(
            "------------------------------ beginning antivouch() ------------------------------"
        )
        if self.whitelistCheck(ctx) == False:
            await ctx.send("Cannot do that in this channel")
            return
        try:
            user = user.lower()
            vouchReason = self.argvCombiner(argv)
            fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
            vouches = jsonHandling.loadJSON(fname)

            if user not in vouches.keys() and self.userInBuffer(ctx,
                                                                user) == False:
                await ctx.send("They don't have any vouches you dumbfuck.")
                return
            acceptableVouch, vouchInfo = self.checkHistory(
                "antivouch", vouches, ctx, user)
            if acceptableVouch == False:
                await ctx.send(vouchInfo["reason"])
                return
            print(acceptableVouch, vouchInfo)
            authorName = str(ctx.author.id)

            voucherInfo = {
                "value": vouchInfo["rankValue"],
                "reason": vouchReason[:-1],
                "voucher": authorName,
                "voucherName": ctx.author.name
            }
            bufferData = {"vouchInfo": vouchInfo, "voucherInfo": voucherInfo}

            bufferHandling.addBuffer(ctx.guild.name.replace(" ", ""),
                                     "vouches", bufferData)
            await ctx.send(
                "Your vouch for " + user +
                " has been added to the queue to be reviewed by admins.")
        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)
        print(
            "------------------------------ ending antivouch() ------------------------------"
        )
示例#15
0
def getBufferIDs(serverName, bufferType):
    """
        Helper function to get a list of all IDs in a buffer

        Parameters:
        bufferType - string name of the buffer to view: for example, "vouches"
    """
    buffername = "buffers/" + serverName + bufferType + ".json"
    if os.path.exists(buffername):
        testBuffer = jsonHandling.loadJSON(buffername)
    else:
        testBuffer = {}
    return list(testBuffer)
示例#16
0
    def whitelistCheck(self, ctx):
        """
        Helper function to check if the current channel is whitelisted

        """
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        print(settings)
        print(ctx.message.channel.id)
        if ctx.message.channel.id in settings["whitelistedChannels"]:
            return True
        else:
            return False
示例#17
0
def viewBuffer(serverName, bufferType, embedTitle, embedMessage):
    """
        Helper function to view a buffer

        Parameters:
        bufferType - string name of the buffer to view: for example, "vouches"
    """
    buffername = "buffers/" + serverName + bufferType + ".json"
    testBuffer = jsonHandling.loadJSON(buffername)
    embed = Embed(title=embedTitle)
    embed.add_field(name="Note", value=embedMessage, inline=False)
    for k, v in testBuffer.items():
        embed.add_field(name=k, value=v, inline=False)
    return embed
示例#18
0
def getBufferData(serverName, bufferType, bufferNo: int):
    """
        Helper function to get a specific entry from a specified buffer

        Parameters:
        bufferType - string name of the buffer to view: for example, "vouches"
        bufferNo - integer ID of the buffer entry to delete
    """
    buffername = "buffers/" + serverName + bufferType + ".json"
    if os.path.exists(buffername):
        testBuffer = jsonHandling.loadJSON(buffername)
    else:
        testBuffer = {}
    return testBuffer[bufferNo]
示例#19
0
    async def unvouch(self, ctx, user: str):
        """
        Callable function for a DGS rank to unvouch someone they previously unvouched

        Parameters:
        user - string of the name of the vouchee
        *argv - additional arguments. Intended as a description of the reasoning for a antivouch

        """
        print(
            "------------------------------ beginning unvouch() ------------------------------"
        )
        if self.whitelistCheck(ctx) == False:
            await ctx.send("Cannot do that in this channel")
            return
        try:
            user = user.lower()
            fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
            vouches = jsonHandling.loadJSON(fname)
            print(vouches)

            authorName = str(ctx.author.id)

            if user not in vouches.keys() or (
                    user in vouches.keys()
                    and authorName not in vouches[user]["vouchers"]):
                await ctx.send("You haven't vouched them.")

            if user in vouches.keys(
            ) and authorName in vouches[user]["vouchers"]:
                vouches[user]['vouches'] = vouches[user]['vouches'] - vouches[
                    user]['vouchers'][authorName]['value']
                if vouches[user]['vouches'] <= 0:
                    ctx.send(
                        "Vouchee is at 0 or below - removing from vouch list")
                    await self.removeUser(ctx, user)
                else:
                    del vouches[user]['vouchers'][authorName]
                    jsonHandling.dumpJSON(fname, vouches)
                    await ctx.send("Vouch successfully removed.")

        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)

        print(
            "------------------------------ ending unvouch() ------------------------------"
        )
示例#20
0
def removeBuffer(serverName, bufferType, bufferNo: int):
    """
        Helper function to remove an entry from a buffer

        Parameters:
        bufferType - string name of the buffer to view: for example, "vouches"
        bufferNo - integer ID of the buffer entry to delete
    """
    buffername = "buffers/" + serverName + bufferType + ".json"
    testBuffer = jsonHandling.loadJSON(buffername)
    if bufferNo == 0:
        for x in list(testBuffer):
            del testBuffer[x]
    else:
        del testBuffer[bufferNo]
    jsonHandling.dumpJSON(buffername, testBuffer)
    return
示例#21
0
    async def allVouches(self, ctx, silent=False):
        """
        Callable function for seeing information about all vouchees. Functionality gives in-depth output for Wing+ in whitelisted channels and returns only the number of vouches in other cases.

        Parameters:
        silent - Boolean indicating whether or not to get verbose information

        """
        print(
            "------------------------------ beginning allVouches() ------------------------------"
        )
        try:
            fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
            if os.path.exists(fname):
                vouches = jsonHandling.loadJSON(fname)
            else:
                await ctx.send("No vouches have been made on this server yet.")
            embed = discord.Embed(title="All 3s Vouches")
            if len(vouches) == 0:
                embed.add_field(name="no vouches",
                                value="no vouches",
                                inline=False)
                return embed

            listVouches = ""
            for k, v in sorted(vouches.items()):
                listVouches = listVouches + k.title() + " - " + str(
                    v['vouches']) + "\n"
            embed.add_field(name="RSN - # of Vouches",
                            value=listVouches,
                            inline=False)
            if silent == False:
                await ctx.send(embed=embed)
            else:
                return embed
        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)
            await ctx.send("Couldn't printvouches")

        print(
            "------------------------------ ending allVouches() ------------------------------"
        )
示例#22
0
    async def removeUser(self, ctx, user: str):
        """
        Callable function for an admin to remove a vouchee from the system

        Parameters:
        user - String of the name of the vouchee/antivouchee

        """
        print(
            "------------------------------ beginning viewVouchBuffer() ------------------------------"
        )
        if self.whitelistCheck(ctx) == False:
            await ctx.send("This command is not allowed in this channel.")
        else:
            fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
            vouches = jsonHandling.loadJSON(fname)
            del vouches[user.lower()]
            jsonHandling.dumpJSON(fname, vouches)
            await ctx.send(user +
                           " was completely removed from the vouch list.")
        print(
            "------------------------------ ending viewVouchBuffer() ------------------------------"
        )
示例#23
0
    async def vouchInfo(self, ctx, user: str):
        """
        Callable function for seeing information about the vouches of a user. Functionality gives verbose output for Wing+ in whitelisted channels and returns only the number of vouches in other cases.

        Parameters:
        user - string of the vouchee name to display

        """
        print(
            "------------------------------ begining vouchInfo() ------------------------------"
        )
        fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
        if os.path.exists(fname):
            vouches = jsonHandling.loadJSON(fname)
        else:
            await ctx.send("No vouches have been made on this server yet.")

        user = user.lower()
        roles = self.getRoles(ctx)
        try:
            embedTitle = "Vouches for " + string.capwords(user)
            embed = discord.Embed(title=embedTitle)

            embed.add_field(name="Vouches",
                            value=vouches[user]["vouches"],
                            inline=False)

            try:
                #check if channel has been whitelisted
                if self.whitelistCheck(ctx) == False:
                    pass
                else:
                    #create text string with vouchers info
                    vouchers = ""
                    for k, v in vouches[user]["vouchers"].items():
                        vouchers = vouchers + self.vouchDict[
                            v["value"]] + " " + v["voucherName"]
                        if len(v["reason"]) > 0:
                            vouchers = vouchers + " - " + str(
                                v["reason"]) + "\n"
                        else:
                            vouchers = vouchers + "\n"
                    print("vouchers", vouchers)
                    embed.add_field(name="Vouchers",
                                    value=vouchers,
                                    inline=False)

                    #if there is antivouchers
                    print(len(vouches[user]["antivouchers"]))
                    if len(vouches[user]["antivouchers"]) > 0:
                        antivouchers = ""
                        #create text string with antivouchers info
                        for k, v in vouches[user]["antivouchers"].items():
                            antivouchers = antivouchers + self.vouchDict[abs(
                                v["value"])] + " " + v["voucherName"]
                            if len(v["reason"]) > 0:
                                antivouchers = antivouchers + " - " + str(
                                    v["reason"]) + "\n"
                            else:
                                antivouchers = antivouchers + "\n"
                    else:
                        antivouchers = "None"
                    print("antivouchers", antivouchers)
                    embed.add_field(name="Antivouchers",
                                    value=antivouchers,
                                    inline=False)
            except:
                pass
            await ctx.send(embed=embed)
        except KeyError:
            await ctx.send(user + " has no vouches.")

        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)

        print(
            "------------------------------ ending vouchInfo() ------------------------------"
        )
示例#24
0
    async def acceptVouch(self, ctx, vouchID: str, silent=False):
        """
        Callable function for admin's to accept a vouch from the buffer based on ID

        Parameters:
        vouchID - String representing the vouch to accept
        silent - Boolean indicating whether or not to get verbose information

        """
        try:
            print(
                "------------------------------ beginning acceptVouch() ------------------------------"
            )
            # Message to be printed out at the end.
            message = "Vouch complete!"
            # get data for this vouchID
            vouchData = bufferHandling.getBufferData(
                ctx.guild.name.replace(" ", ""), "vouches", vouchID)
            # get vouches data
            fname = "vouches/" + ctx.guild.name.replace(" ", "") + ".json"
            vouches = jsonHandling.loadJSON(fname)
            # add the vouch to the vouch datastore
            vouches = self.addVouchee(vouchData["vouchInfo"]["user"], vouches)

            # Remove any instances of this person already vouching/anti'ing the vouchee
            # We will update with their new information (new vouch/anti and rank value)
            try:
                del vouches[vouchData["vouchInfo"]["user"]]["antivouchers"][
                    vouchData["voucherInfo"]["voucher"]]
                print("removing exisiting antivouch entry")
            except:
                pass

            try:
                del vouches[vouchData["vouchInfo"]["user"]]["vouchers"][
                    vouchData["voucherInfo"]["voucher"]]
                print("removing exisiting vouch entry")
            except:
                pass

            # add the voucher info to the vouch datastore
            # if it's a vouch
            if vouchData["vouchInfo"]["vouchType"] == "vouch":
                vouches[vouchData["vouchInfo"]["user"]]["vouchers"][vouchData[
                    "voucherInfo"]["voucher"]] = vouchData["voucherInfo"]

            # if it's an antivouch
            elif vouchData["vouchInfo"]["vouchType"] == "antivouch":
                vouches[vouchData["vouchInfo"]["user"]]["antivouchers"][
                    vouchData["voucherInfo"]
                    ["voucher"]] = vouchData["voucherInfo"]

            # Update the number of vouches
            numVouches = 0
            for voucher in vouches[vouchData["vouchInfo"]["user"]]['vouchers']:
                numVouches += vouches[vouchData["vouchInfo"]
                                      ["user"]]['vouchers'][voucher]['value']

            for antivoucher in vouches[vouchData["vouchInfo"]
                                       ["user"]]['antivouchers']:
                numVouches -= vouches[vouchData["vouchInfo"]["user"]][
                    'antivouchers'][antivoucher]['value']

            # Add to dict
            vouches[vouchData["vouchInfo"]["user"]]["vouches"] = max(
                numVouches, 0)

            #c heck if user has been vouched to 0 and remove if so
            if vouches[vouchData["vouchInfo"]["user"]]["vouches"] == 0:
                del vouches[vouchData["vouchInfo"]["user"]]
                message = ("Reached 0 vouches. Removed " +
                           vouchData["vouchInfo"]["user"])
                silent = False

            # save vouch data
            jsonHandling.dumpJSON(fname, vouches)
            # remove vouch from buffer
            bufferHandling.removeBuffer(ctx.guild.name.replace(" ", ""),
                                        "vouches", vouchID)
            # await self.updateMessage(ctx)
            if silent == False:
                await ctx.send(message)
            else:
                return
            print(
                "------------------------------ ending acceptVouch() ------------------------------"
            )
        except KeyError:
            await ctx.send("No vouch with ID:" + vouchID +
                           " exists in the buffer.")
        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)
    def findNames(self, ctx):
        def equal(im1, im2):
            return ImageChops.difference(im1, im2).getbbox() is None

        def fuzzyEqual(im1, im2):
            im1 = np.array(im1)
            im2 = np.array(im2)
            err = np.sum((im1.astype("float") - im2.astype("float"))**2)
            err /= float(im1.shape[0] * im1.shape[1])
            return err

        def findRow(zero, time, charName):
            (glwidth, glheight) = zero.width, zero.height
            (twidth, theight) = time.width, time.height
            for x in range(twidth - glwidth):
                for y in range(theight - glheight):
                    im = time.crop((x, y, x + glwidth, y + glheight))

                    if fuzzyEqual(im, zero) < 0.05:
                        charDict = {
                            "character": charName,
                            "charLength": glwidth
                        }
                        fullTime[x] = charDict
                        mainX = x
                        mainY = y
                        im.save("test/" + str(x) + " " + str(y) + ".png")
                        return True, mainX, mainY
            mainX = 0
            mainY = 0
            return False, mainX, mainY

        def decoder(fullTime):
            timeDictList = (sorted(fullTime))
            timeStr = ""
            prevX = 0
            for x in timeDictList:
                if (x - prevX > 3 and prevX > 0):
                    timeStr = timeStr + " " + str(fullTime[x]["character"])
                elif x - prevX < 0:
                    continue
                else:
                    timeStr = timeStr + str(fullTime[x]["character"])
                prevX = int(x) + int(fullTime[x]["charLength"])
            return timeStr

        def findNonZeros(filepath, fullTime, glwidth, glheight, k):
            zero = Image.open(filepath)
            zero = zero.convert('1')
            (glwidth, glheight) = zero.width, zero.height
            for x in range(0, twidth - glwidth + 1):
                im = time.crop((x, rowY, x + glwidth, rowY + glheight))
                if fuzzyEqual(im, zero) < 0.05:
                    charDict = {"character": k, "charLength": glwidth}
                    fullTime[x] = charDict
            return fullTime

        chars = {
            "u": "charGlyph/glyphLowerU.png",
            "n": "charGlyph/glyphLowerN.png",
            "t": "charGlyph/glyphLowerT.png",
            "e": "charGlyph/glyphLowerE.png",
            "r": "charGlyph/glyphLowerR.png",
            "d": "charGlyph/glyphLowerD.png",
            "x": "charGlyph/glyphLowerX.png",
            "p": "charGlyph/glyphLowerP.png",
            "a": "charGlyph/glyphLowerA.png",
            "l": "charGlyph/glyphLowerL.png",
            "i": "charGlyph/glyphLowerI.png",
            "o": "charGlyph/glyphLowerO.png",
            "s": "charGlyph/glyphLowerS.png",
            "f": "charGlyph/glyphLowerF.png",
            "m": "charGlyph/glyphLowerM.png",
            "k": "charGlyph/glyphLowerK.png",
            "g": "charGlyph/glyphLowerG.png",
            "y": "charGlyph/glyphLowerY.png",
            "w": "charGlyph/glyphLowerW.png",
            "h": "charGlyph/glyphLowerH.png",
            "b": "charGlyph/glyphLowerB.png",
            "c": "charGlyph/glyphLowerC.png",
            "q": "charGlyph/glyphLowerQ.png",
            "z": "charGlyph/glyphLowerZ.png",
            "v": "charGlyph/glyphLowerV.png",
            "j": "charGlyph/glyphLowerJ.png",
            "H": "charGlyph/glyphCapH.png",
            "Q": "charGlyph/glyphCapQ.png",
            "C": "charGlyph/glyphCapC.png",
            "D": "charGlyph/glyphCapD.png",
            "S": "charGlyph/glyphCapS.png",
            "G": "charGlyph/glyphCapG.png",
            "O": "charGlyph/glyphCapO.png",
            "E": "charGlyph/glyphCapE.png",
            "T": "charGlyph/glyphCapT.png",
            "Y": "charGlyph/glyphCapY.png",
            "K": "charGlyph/glyphCapK.png",
            "B": "charGlyph/glyphCapB.png",
            "F": "charGlyph/glyphCapF.png",
            "M": "charGlyph/glyphCapM.png",
            "I": "charGlyph/glyphCapI.png",
            "U": "charGlyph/glyphCapU.png",
            "R": "charGlyph/glyphCapR.png",
            "P": "charGlyph/glyphCapP.png",
            "X": "charGlyph/glyphCapX.png",
            "W": "charGlyph/glyphCapW.png",
            "V": "charGlyph/glyphCapV.png",
            "Z": "charGlyph/glyphCapZ.png",
            "A": "charGlyph/glyphCapA.png",
            "L": "charGlyph/glyphCapL.png",
            "M": "charGlyph/glyphCapM.png",
            "N": "charGlyph/glyphCapN.png",
            "P": "charGlyph/glyphCapP.png",
            "J": "charGlyph/glyphCapJ.png",
            "1": "charGlyph/glyphName1.png",
            "2": "charGlyph/glyphName2.png",
            "3": "charGlyph/glyphName3.png",
            "4": "charGlyph/glyphName4.png",
            "5": "charGlyph/glyphName5.png",
            "6": "charGlyph/glyphName6.png",
            "7": "charGlyph/glyphName7.png",
            "8": "charGlyph/glyphName8.png",
            "9": "charGlyph/glyphName9.png",
            "0": "charGlyph/glyphName0.png"
        }

        namesFound = []

        times = []
        for file in os.listdir("./character"):
            times.append(file)

        for t in times:
            name = "Couldn't find name"
            fullTime = {}
            fname = "character/" + t
            time = Image.open(fname)
            enhancer = ImageEnhance.Contrast(time)
            time = enhancer.enhance(2)

            (twidth, theight) = time.width, time.height
            time = time.convert('1')

            rows, cols = time.size
            for i in range(1, rows - 1):
                for j in range(1, cols - 1):
                    amt = (time.getpixel((i - 1, j)) + time.getpixel(
                        (i + 1, j)) + time.getpixel(
                            (i, j - 1)) + time.getpixel(
                                (i, j + 1)) + time.getpixel(
                                    (i + 1, j - 1)) + time.getpixel(
                                        (i + 1, j + 1)) + time.getpixel(
                                            (i - 1, j - 1)) + time.getpixel(
                                                (i, j + 1)))
                    if amt == 0:
                        time.putpixel((i, j), 0)

            time.save("ahh/" + t + "test.png")
            matchFound = False
            for k, v in chars.items():
                zero = Image.open(v)
                zero = zero.convert('1')
                matchFound, rowX, rowY = (findRow(zero, time, k))
                if matchFound == True:
                    break

            (glwidth, glheight) = zero.width, zero.height

            if rowX == 0:
                print("Couldn't find name")

            for x in range(rowX + 1, twidth - glwidth + 1):
                im = time.crop((x, rowY, x + glwidth, rowY + glheight))
                if equal(im, zero):
                    fullTime[x] = 0

            for k, v in chars.items():
                fullTime = findNonZeros(v, fullTime, glwidth, glheight, k)

            name = decoder(fullTime)
            fname = "names/names.json"
            namesDict = jsonHandling.loadJSON(fname)
            # print(self.getNames())
            # possibleDgers = list(namesDict)
            possibleDgers = []
            for x in self.getNames():
                possibleDgers.append(x[0])
            if name in possibleDgers:
                print(fname[:-4], name)
            elif name is None:
                print(fname[:-4], "NA")
                continue
            else:
                closestMatch = difflib.get_close_matches(name, possibleDgers)
                if len(closestMatch) > 0:
                    print(fname[:-4], closestMatch[0])
                    name = closestMatch[0]
                else:
                    print(fname[:-4], "NA")

            if name == None:
                name = "None found"
            elif len(name) > 0:
                jsonHandling.dumpJSON(fname, namesDict)
                print("name=====", name)
                namesFound.append(name)
            else:
                namesFound.append("None")
        return namesFound
示例#26
0
    async def formTeams(self, ctx):
        """
        Callable function to creates teams based on active participants, rank values and then outputs those teams into the server

        """
        usersMessage = ctx.message
        await usersMessage.delete()
        MSfname = "massSpeeds/" + ctx.guild.name.replace(" ", "") + ".json"
        fname = "guildsettings/" + ctx.guild.name.replace(" ", "") + ".json"
        settings = jsonHandling.loadJSON(fname)
        if "msActive" not in settings.keys():
            await ctx.send(
                "No mass speeds session in progress. <a:EB:744967488751665303> (Not in settings)"
            )
            return

        if settings["msActive"] == False:
            await ctx.send(
                "No mass speeds session in progress. <a:EB:744967488751665303> (MS Session = False)"
            )
            return

        if len(self.teamMessages) > 0:
            for x in range(len(self.teamMessages)):
                msg = self.teamMessages.pop()
                await msg.delete()

        players = jsonHandling.loadJSON(MSfname)
        MSrole = get(ctx.guild.roles, name="Mass Speeds")

        playersValue = {}
        toBeRemoved = []
        for x in players.keys():
            member = ctx.guild.get_member(int(x))
            if MSrole in member.roles:
                value = self.rankValue(getRoles(member.roles))
                if member.nick == None:
                    playersValue[member.name] = value
                else:
                    playersValue[member.nick] = value
            else:
                toBeRemoved.append(x)

        for x in toBeRemoved:
            players.pop(str(x))

        jsonHandling.dumpJSON(MSfname, players)
        teams, leftovers = self.runRandomMassSpeeds(playersValue)

        for k, v in teams.items():
            team = discord.Embed()
            message = ""
            for x in v:
                message = message + x + "\n"

            team.add_field(name=k, value=message, inline=False)
            messageSent = await ctx.send(embed=team)
            self.teamMessages.append(messageSent)

        message = ""
        if len(leftovers) > 0:
            for x in leftovers:
                message = message + x + "\n"
        else:
            message = "None"
        leftovers = discord.Embed()
        leftovers.add_field(name="Leftovers", value=message)
        messageSent = await ctx.send(embed=leftovers)
        self.teamMessages.append(messageSent)