Skip to content

Instantly share code, notes, and snippets.

@Kyu
Last active April 24, 2023 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kyu/bb7c1aa3290f986da5cc0122fa2617ee to your computer and use it in GitHub Desktop.
Save Kyu/bb7c1aa3290f986da5cc0122fa2617ee to your computer and use it in GitHub Desktop.
# Pretty print messages
# https://discord.com/developers/docs/topics/gateway#transport-compression
# https://github.com/Rapptz/discord.py/blob/8ba830eeb86a52e54c727e71436bfe0e9ea51526/discord/gateway.py#L491
import json, base64, pprint, zlib
buffer = bytearray()
zlib_obj = zlib.decompressobj()
printer = pprint.PrettyPrinter()
def add(enc):
global buffer
msg = base64.b64decode(enc)
buffer.extend(msg)
if len(msg) < 4:
print("Message < 4")
return
if msg[-4:] != b'\x00\x00\xff\xff':
print("Does not end with 00 00 ff ff")
return
out = zlib_obj.decompress(buffer)
out = out.decode('utf-8')
buffer = bytearray()
return out
"""
dict(t="MESSAGE_CREATE", s=11, op=0,
d={"type": 0, "tts": false, "timestamp": "2023-04-23T23:34:52.416000+00:00", "referenced_message": null,
"pinned": false, "nonce": "1099840848327081984", "mentions": [], "mention_roles": [], "mention_everyone": false,
"member": {"roles": [], "premium_since": null, "pending": false, "nick": null, "mute": false,
"joined_at": "2023-04-23T22:23:04.580000+00:00", "flags": 0, "deaf": false,
"communication_disabled_until": null, "avatar": null}, "id": "1099840848830668863", "flags": 0,
"embeds": [], "edited_timestamp": null, "content": "4", "components": [], "channel_id": "1099822780943441993",
"author": {"username": "NotKyu", "public_flags": 0, "id": "209648537632374786", "global_name": null,
"display_name": null, "discriminator": "7547", "avatar_decoration": null,
"avatar": "d38f43fc0c4d2a6c443ef8d0fb3113ac"}, "attachments": [], "guild_id": "1099822780242985021"})
"""
# {"t":null,"s":null,"op":11,"d":null}
def parse_message(msg: str):
if not msg:
print("No message")
return
try:
body = json.loads(msg)
except Exception as e:
print(f"Exception loading json: {type(e)} {e}")
return
if not body['t']:
print("Null event")
return
if body['t'] != 'MESSAGE_CREATE':
print("Not a message event")
return
printer.pprint(body)
while True:
b64 = input(">>> Enter: ")
contents = add(b64)
parse_message(contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment