From f861c758d8f0ef4e65b1fd096617b39d04ac929a Mon Sep 17 00:00:00 2001 From: Zevaryx Date: Sun, 27 Jun 2021 18:06:27 -0600 Subject: [PATCH] Add DevCog with hash utility --- jarvis/cogs/dev.py | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 jarvis/cogs/dev.py diff --git a/jarvis/cogs/dev.py b/jarvis/cogs/dev.py new file mode 100644 index 0000000..c8a219a --- /dev/null +++ b/jarvis/cogs/dev.py @@ -0,0 +1,68 @@ +import jarvis +import hashlib +from discord.ext import commands +from jarvis.utils import build_embed, convert_bytesize +from jarvis.utils.field import Field + + +supported_hashes = { + x for x in hashlib.algorithms_guaranteed if "shake" not in x +} + + +def hash_obj(hash, data, text: bool = True) -> str: + """ + Hash data with hash object + + Data can be text or binary + """ + if text: + hash.update(data) + return hash.hexdigest() + BSIZE = 65536 + while block := data.read(BSIZE): + hash.update(block) + return hash.hexdigest() + + +class DevCog(commands.Cog): + def __init__(self, bot): + self.bot = bot + + @commands.command(name="hash") + async def _hash(self, ctx, method: str, *, data: str): + if method not in supported_hashes: + algo_txt = ", ".join(f"`{x}`" for x in supported_hashes) + await ctx.send( + "Unsupported hash algorithm. Supported:\n" + algo_txt + ) + return + if len(data) == 0 and len(ctx.message.attachments) == 0: + await ctx.send( + "No data to hash. Either attach a file or send text to hash" + ) + return + text = True + if len(ctx.message.attachments) > 0: + text = False + data = await ctx.message.attachments[0].read() + # Default to sha256, just in case + hash = getattr(hashlib, method, hashlib.sha256)() + hash = hash_obj(hash, data, text) + + data_size = convert_bytesize(len(data)) + title = data if text else ctx.message.attachments[0].filename + description = "Hashed using " + method + fields = [ + Field("Data Size", data_size, False), + Field("Hash", hash, False), + ] + + embed = build_embed( + title=title, description=description, fields=fields + ) + await ctx.send(embed=embed) + + +def setup(bot): + bot.add_cog(DevCog(bot))