Esempio n. 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.messageID.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()
Esempio n. 2
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)
Esempio n. 3
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() ------------------------------"
        )
Esempio n. 4
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)
                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)
Esempio n. 5
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() ------------------------------"
        )
Esempio n. 6
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)
Esempio n. 7
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() ------------------------------"
        )
Esempio n. 8
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)
Esempio n. 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
Esempio n. 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
Esempio n. 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)
Esempio n. 12
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, {})
Esempio n. 13
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)
Esempio n. 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() ------------------------------"
        )
Esempio n. 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)
Esempio n. 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
Esempio n. 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
Esempio n. 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]
Esempio n. 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() ------------------------------"
        )
Esempio n. 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
Esempio n. 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() ------------------------------"
        )
Esempio n. 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() ------------------------------"
        )
Esempio n. 23
0
    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 fuzzyEqual(im, zero) < 0.05:
            fullTime[x] = 0

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

    print(fullTime)
    print(decoder(fullTime))
    name = decoder(fullTime)
    fname = "names/names.json"
    namesDict = jsonHandling.loadJSON(fname)
    possibleDgers = list(namesDict.keys())

    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")
Esempio n. 24
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)
Esempio n. 25
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)
Esempio n. 26
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() ------------------------------"
        )