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()
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)
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)
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() ------------------------------" )
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)
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)
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() ------------------------------" )
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)
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)
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, {})
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() ------------------------------" )
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
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
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() ------------------------------" )
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") if name == None: name = "None found" elif len(name) > 0: namesDict[name] = None jsonHandling.dumpJSON(fname, namesDict) print("name=====", name) print(name) else: print("No name found")
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)
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)