async def cc_add(self,ctx,name,*,content): """Adds a custom command for this server, requires manage server permissions. You can use arguments to the context class if you do {.messagearguments}. For example .guild.name .channel.id .author.display_name . if you want to use more than one ctx argument you add a 0, e.g {0.message.id} you can also add arguments that the user fills in with $A""" guildid = str(ctx.guild.id) name = name.lower() commands = await self.checkGuildDict(guildid) actualcommands = [command.name for command in self.bot.commands] for aliases in [command.aliases for command in self.bot.commands]: if aliases: for alias in aliases: actualcommands.append(alias) if name in actualcommands: await ctx.send("There is already an actual command named that.") return if name in commands: await ctx.send(f"Warning: There is already a command named `{name}` in this server continuing would overwrite it.\nIf you want to continue say `yes`.") def check(m): return m.content == 'yes' and m.channel == ctx.channel and m.author == ctx.author try: msg = await self.bot.wait_for('message',check=check,timeout=15) except asyncio.TimeoutError: await ctx.send("Timed Out. Not overwriting.") return else: if msg.content == "yes": await ctx.send("Overwriting.") commands[name] = content storage.write("commands",commands,path="cogs/custom/",key=guildid) await ctx.send(f"Command {name} added!")
async def logchannel(self, ctx, channel: discord.TextChannel = None): guildid = str(ctx.guild.id) setting = self.getmodsetting(guildid, 'logchannel') if not channel: channel = ctx.channel try: logchannel = self.bot.get_channel(int(setting)) except: logchannel = None if logchannel == channel: await ctx.send(f"The log channel is already {channel.mention}!") return if not channel.permissions_for( ctx.guild.me).read_messages or not channel.permissions_for( ctx.guild.me).send_messages: await ctx.send("I can't read and/or send messages in that channel." ) return settings = storage.read("mod", key=[guildid]) settings['logchannel'] = channel.id storage.write("mod", settings, key=guildid) if channel: await ctx.send("{} has been made the log channel".format( channel.name)) else: await ctx.send("The log channel has been removed")
def getMiniMap(self, name): #self.getMiniMapFromWeb(name) # the manager likes to use actual filenames, but # most other stuff will want to simply use the # name of the map with out the file extension name = self.getNameByShortName(name) storkey = 'mapManager.minimap.%s' % name if storage.exist(storkey): qimg = QtGui.QImage(storage.read(storkey), 1024, 1024, QtGui.QImage.Format_RGB16) return qimg # okay look and see if we have the map file locally if name not in self.maps: print('getMiniMap-name-not-found', name) return None dstdir = os.path.abspath('.\\7ztmp') archive = '%s%s' % (self.mapdir, name) if os.path.exists(dstdir): self.rmdir(dstdir) os.mkdir(dstdir) if archive[-4:] == '.sd7': subprocess.call(['7zr.exe', '-ir!*.smf', '-y', 'e', '-o%s' % dstdir, archive]) if archive[-4:] == '.sdz': zf = zipfile.ZipFile(archive) for node in zf.namelist(): ext = node[-4:] # skipping tile file... maybe little faster.. (if it goes missing look here for sdz files) if ext != '.smd' or ext != '.smf': continue data = zf.read(node) node = node.replace('/', '_').replace('\\', '_') fd = open('%s\\%s' % (dstdir, node), 'wb') fd.write(data) fd.close() nodes = os.listdir(dstdir) ''' .smd is plain text, lots of interesting information that the user could be interested in especially hardcore players, also seems very useful info too about start positions! .smf is the actual map file with height data and minimap data .smt is the tile file.. i dont know anything about this one yet ''' for node in nodes: ext = node[-4:] if ext == '.smd': pass if ext == '.smf': qimg, qimgraw = self.readSMF('%s\\%s' % (dstdir, node)) storage.write('mapManager.minimap.%s' % name, qimgraw, useDisk = True) return qimg if ext == '.smt': pass print('game archive did not contain SMF file!') self.rmdir('%s' % dstdir) return None
async def deluserpersist(self, ctx, user, role): guildid = str(ctx.guild.id) userid = str(user.id) roleid = str(role.id) persists = storage.read("persists", path="cogs/mod/", key=[guildid]) if roleid not in persists[userid]: return f"{user} doesn't have {role} on their persist list!" persists[userid].remove(roleid) storage.write("persists", persists, path="cogs/mod/", key=guildid) return f"{user} will no longer be given {role} when they rejoin."
async def cc_del(self,ctx,name): """Deltes a custom command for this server, requires manage server permission.""" guildid = str(ctx.guild.id) commands = await self.checkGuildDict(guildid) if commands.pop(name,None) is None: await ctx.send("{} wasn't found.".format(name)) return else: storage.write("commands",commands,path="cogs/custom/",key=guildid) await ctx.send("Command {} deleted!".format(name))
async def vote(self, ctx, num): voter = ctx.message.author.name result = currentPoll.vote(voter, num) storage.write(pollFile, currentPoll.suggestion) if result is None: response = (f'Thanks for your vote {voter}!') else: response = result await ctx.send(response)
async def setprefix(self, ctx, prefix="-"): guildid = str(ctx.guild.id) oldPrefix = storage.read("prefixes", key=[guildid]) if prefix == oldPrefix: await ctx.send("That's already the prefix!") return if len(prefix) > 14: await ctx.send("That's too long! It must be under 15 characters.") return storage.write("prefixes", prefix, key=guildid) await ctx.send(f"Prefix has been set to ``{prefix}``!")
def sync(): for key, date in storage.unprocessed(): try: logging.info(f"Processing data for {date}") df = storage.get_dataset(key) logging.info(f"Running clustering...") cluster = clustering.cluster(df) logging.info(f"Writing results...") storage.write(cluster, date) except Exception: logging.exception(f"Failed to process data for {date}")
async def suggest(self, ctx, *title): titleStr = " ".join(title) if movieList.add(titleStr): storage.write(movieFile, movieList.movies) response = f'"{titleStr}" has been added to the movie list.' else: response = f'"{titleStr}" has already been suggested.' await ctx.send(response)
async def modset_invitecensoring(self, ctx, enabled: bool = True): guildid = str(ctx.guild.id) settings = storage.read("mod", key=[guildid]) if "invite" not in settings: settings["invite"] = True storage.write("mod", settings, key=guildid) if enabled == settings["invite"]: await ctx.send("That's already the setting!") return settings["invite"] = enabled storage.write("mod", settings, key=guildid) await ctx.send(f"Invite Censoring has been set to {enabled}!")
async def adduserpersist(self, ctx, user, role): guildid = str(ctx.guild.id) userid = str(user.id) roleid = str(role.id) persists = storage.read("persists", path="cogs/mod/", key=[guildid]) if userid not in persists: persists[userid] = [] if roleid in persists[userid]: return f"{user} already has {role} on their persist list!" persists[userid].append(roleid) storage.write("persists", persists, path="cogs/mod/", key=guildid) return f"{user} will now be given {role} when they rejoin (until you remove it from them with `{prefix(self,ctx.message)}role remove '{role.name}' '{user.name}''`)"
async def load(self, ctx, *cogs): """Loads a cog.""" for cog in cogs: try: self.bot.load_extension(f"cogs.{cog}.{cog}") except: await ctx.send("Failed.") raise else: extensions = storage.read("cogs") extensions.append("cogs.{0}.{0}".format(cog)) storage.write("cogs", extensions) await ctx.send(f"Cog {cog} loaded.") self.bot.currently_loaded_cogs.append(cog)
async def remove(self, ctx, *num): titles = [] for number in num: try: choice = int(number) except ValueError: response = f'{number} is not a number. Please give me a number.' await ctx.send(response) return titles.append(movieList.movies[choice]['title']) #For every "entry" in the list "num" from above, call int() to cast the string value to an integer and save it to a list contained within the remove function movieList.remove([int(entry) for entry in num]) storage.write(movieFile, movieList.movies) response = f'{titles} has been removed from the movie list.' await ctx.send(response)
async def unload(self, ctx, *cogs): """Unloads a cog.""" for cog in cogs: if cog == 'owner': await ctx.send("Cannot unload owner.") return try: self.bot.unload_extension("cogs.{0}.{0}".format(cog)) except: await ctx.send("Cog not loaded but removing it.") pass extensions = storage.read("cogs") extensions.remove("cogs.{0}.{0}".format(cog)) storage.write("cogs", extensions) await ctx.send("Cog {} unloaded.".format(cog)) self.bot.currently_loaded_cogs.remove(cog)
async def close(self, ctx): if not currentPoll.isActive: response = "There is no active poll to close." await ctx.send(response) currentPoll.close() response = f'The winner is {currentPoll.winner}! "{currentPoll.winner}" will be removed from the movie list.' await ctx.send(response) winnerIndex = movieList.getMovieID(currentPoll.winner) if winnerIndex is None: response = f"Hey boss, I couldn't find the ID of the winning movie. Halp." await ctx.send(response) else: movieList.remove([winnerIndex]) os.remove(pollFile) storage.write(movieFile, movieList.movies)
async def close(self, ctx): if not currentPoll.isActive: response = "There is no active poll to close." await ctx.send(response) response = currentPoll.close() await ctx.send(response) winnerIndex = movieList.getMovieID(currentPoll.winner) if winnerIndex is None: response = f"Hey boss, someone already deleted the winner from the movie list. Rude." os.remove(pollFile) storage.write(movieFile, movieList.movies) await ctx.send(response) else: movieList.remove([winnerIndex]) os.remove(pollFile) storage.write(movieFile, movieList.movies)
def train(date): try: logging.info(f"Processing data for {date}") data = storage.get_dataset(date) # For testing: if you want to speed things up # data = data.sample(n=100) logging.info(f"Running clustering...") categorical_cols = None drop_cols = ["upload_time", "account", "system_id"] cluster = clustering.train.Cluster(data, categorical_cols=categorical_cols, drop_cols=drop_cols) cluster_info = cluster.train_the_cluster() logging.info(f"Writing results...") storage.write(cluster_info, date) except Exception: logging.exception(f"Failed to process data for {date}")
async def start(self, ctx, *choices): choiceList = [] response = f'{ctx.message.author.name} has started a poll! Please vote for one of the following:\n' for choice in choices: try: choice = int(choice) except ValueError: response = f'{choice} is not a number. Please give me a number.' await ctx.send(response) return choiceList.append(movieList.movies[choice]["title"]) if currentPoll.start(choiceList): response = f'{response}{currentPoll.status()}' if not storage.write(pollFile, currentPoll.suggestion): response = (f"{response}\nCouldn't save the poll to a file" f"after starting. Poll will not be saved (this is ok)") else: response = "Error starting the poll." await ctx.send(response)
def getPermissionsAndCheckForGuildAndCommand(ctx,command): # what the f**k perms = storage.read("permissions",path="cogs/permissions/",key=[str(ctx.guild.id)]) if command not in permissions["commands"]: permissions["commands"][command] = {"*": ["*"]} storage.write("permissions",permissions,path="cogs/permissions/",key=) return permissions
message = ' '.join(sys.argv[4:]) # Get the keys key_caesar = eval( sys.argv[2]) # In the Caesar cipher the key is an integer number key_vigenere = sys.argv[3] # In Vigenere cipher the key is a word # Apply ciphers caesar = cipher.caesar(message.lower(), key_caesar, encrypt) vigenere = cipher.vigenere(message.lower(), key_vigenere.lower(), encrypt) # Output results results = 'CAESAR CIPHER:\n' + caesar + '\n\nVIGENERE CIPHER:\n' + vigenere if '-o' in sys.argv: # Write result to file i = sys.argv.index('-o') storage.write(sys.argv[i + 1], results) else: # Write result to console print(results) # Analise by counting the letter in the alphabet plain_letter_count = analysis.count_letters(message.lower()) caesar_letter_count = analysis.count_letters(caesar) vigenere_letter_count = analysis.count_letters(vigenere) # Show theoretical letter frequency analysis.theoretical() analysis.show(legend=False) # Show comparison between theoretical and actual letter frequency analysis.theoretical_vs_actual(plain_letter_count) analysis.show()
async def checkGuildDict(self,guildid): if not storage.read("commands",path="cogs/custom/",key=[guildid]): storage.write("commands",{},path="cogs/custom/",key=guildid) return storage.read("commands",path="cogs/custom/",key=[guildid])