Add DevCog with hash utility

This commit is contained in:
Zeva Rose 2021-06-27 18:06:27 -06:00
parent a43f45dfbb
commit f861c758d8

68
jarvis/cogs/dev.py Normal file
View file

@ -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))