# Creating embed for Discord reading from dictionary

I have been working on where I create a payload of dicts with different values as store, name etc etc which you will see very soon. The idea is that with the payload I send to this script, it should see if the values is in the payload (dict) and if it is then add it into discord embed. As simple as it sounds.

I have done something like this:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from typing import Dict

import pendulum
from discord_webhook import DiscordEmbed, DiscordWebhook
from loguru import logger

mixed_filtered = {
'test1': 'https://discordapp.com/api/webhooks/529345345345345/6h4_yshmNDKktdT-0VevOhqdXG9rDhRWclIfDD4jY8IbdCQ5-kllob-k1251252151',
'test2': 'https://discordapp.com/api/webhooks/529674575474577/6h4_yshmNDKktdT-0VevOhqdXG9rDhRWclIfDD4jY8IbdCQ5-kllob-fhgdfdghfhdh'
}

mixed_unfiltered = {
'test1': 'https://discordapp.com/api/webhooks/12412421412412/6h4_yshmNDKktdT-0VevOhqdXG9rDhR12412412414Q5-kllob-kI2jAxCZ5PdIn',
'test2': 'https://discordapp.com/api/webhooks/529617352682110997/6h4_yshmNDKktdT-0VevOhqdXG912412412412IbdCQ5-kllob-kI2jAxCZ5PdIn'
}

# -------------------------------------------------------------------------
# Name of the product, URL of the product & New! or Restock! url
# -------------------------------------------------------------------------
embed = DiscordEmbed(
color=8149447
)

# -------------------------------------------------------------------------
# Image product
# -------------------------------------------------------------------------
embed.set_thumbnail(
)

# -------------------------------------------------------------------------
# Store Name
# -------------------------------------------------------------------------
name="Site",
)

# -------------------------------------------------------------------------
# The price of the product
# -------------------------------------------------------------------------
name="Price",
)

# -------------------------------------------------------------------------
# If store is Nike
# -------------------------------------------------------------------------

name="\u200b",
value="\u200b"
)

name="Status",
)

# -------------------------------------------------------------------------
# Nike  Sales Channel
# -------------------------------------------------------------------------
name="Sales Channel",
)

# -------------------------------------------------------------------------
# Sizes available
# Add extra spaces for sizes to make it cleaner for discord embed
# -------------------------------------------------------------------------

payload["sizes"] = [f"{k} - ({v})" if v else k for k, v in payload["sizes"].items()]
# If we have stock in values then sum it up

name="\u200b",
value="\u200b"
)

characterCount, i = 0, 0

# There is a limitation for Discord where if we reach over 1020 characters for one embed column.
# IT will throw a error. Now I check if the characters count is less than 900 then we create a new embed.
if len(item) + characterCount > 900:
name="Sizes",
)
characterCount, i = len(item), j
else:
characterCount += len(item)

if characterCount:
name="Sizes",
)

name="\u200b",
value="\u200b"
)

name="\u200b",
value="\u200b"
)

# -------------------------------------------------------------------------
# If store is footlocker
# -------------------------------------------------------------------------
)

name="\u200b",
value="\u200b"
)
name="Style Code",
)

# -------------------------------------------------------------------------
# Release date for the product
# -------------------------------------------------------------------------
name="Release Date",
)

# -------------------------------------------------------------------------
# Stock keeping unit etc. 508214-660
# -------------------------------------------------------------------------
name="SKU",
)

# -------------------------------------------------------------------------
# Total stock of the product
# -------------------------------------------------------------------------
name="Total Stock",
)

# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
value=f'{" | ".join(shortcuts for shortcuts in payload["shortcut"])}'
)

# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
)

# -------------------------------------------------------------------------
# Footer timestamp
# -------------------------------------------------------------------------
embed.set_footer(
text=f'AutoSnkr | {pendulum.now("Europe/Stockholm").format("YYYY-MM-DD [[]HH:mm:ss.SSSS[]]")}'
)

# -------------------------------------------------------------------------
# Set title on the embed
# -------------------------------------------------------------------------
else:

# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
collection = mixed_filtered if payload["keyword"] else mixed_unfiltered

for region, discord_collection in collection.items():
webhook = DiscordWebhook(
url=discord_collection,
)

# Adding thread so each URL can post as fast as possible without needing to wait for each other
target=post_embed,
args=(
region,
webhook
)
).start()

def post_embed(payload: Dict, region: str, webhook: DiscordWebhook) -> None:
success: bool = False

while not success:
try:
response = webhook.execute()
success = response.ok

# If we get a 429, retry after a short delay
if response.status_code == 429:
logger.debug(f"Rate limit -> Retrying in {sleep_time} seconds")
time.sleep(sleep_time)
continue

# any response other than a 429 or a 200 OK is an error.
if not response.ok:
# FIXME Add discord notficiation and raise exception
pass

logger.info(f"Succesfully sent to Discord Reporter -> {region}")

except Exception as err:
# FIXME Add discord notficiation and raise exception
pass

if __name__ == '__main__':
create_embed(
{
"name": "Nike PG5 Bred",
"price": "EUR 119.9",
"sizes": {
"webhook": "mixed",
"status": "Restock!",
"keyword": True
}
)


The mock data is at the very bottom but in the future I will instead send the payload to the function.

I wonder what can I do to try to have less code but that still does the job. I feel like there should be a way more cleaner way to do this than what I did but looking forward to see what can be improved :)

Let me know if there is any missing information. The script should be runnable by copy pasting it but make sure to create your own discord webhooks to test the embed. I will unfortunately need to modify them so no one can spam me :)

If I were a smart man I'd give up on recommending that you stop using a payload dictionary for internal data representation and instead use classes, but I'm not a smart man. Please. I implore you. We're not in JavaScript - objects don't have to be dictionaries. This could be well-represented by a class for product, and a class for product size.

Otherwise:

if payload.get("price") should be replaced by if 'price' in payload if it were only that statement; but since you actually use it,

if payload.get("price"):
name="Price",
)


should become

price = payload.get('price')
if price is not None:


More broadly: your create_embed is a presentation function but mixes in logic concerns such as stock summation, and store-specific logic (i.e. Footlocker). That should be separated.

Your

# FIXME Add discord notficiation and raise exception


first of all has a typo - notficiation -> notification - and second of all, while this is waiting to be fixed it's of crucial importance that you not swallow exceptions. Part of development and debugging is seeing errors, and your code breaks that. So replace your pass with a raise in the meantime.

• Hi again! :) Regarding the payload being dictionary it is something that I still have issue with and it is something we have worked on together as you remember :) My problem is that I do not know how I can work with only classes where I have previously asked for a code review regarding the part where I actually send the payload to the create_embed which can be found from here codereview.stackexchange.com/q/259867/223687 - If I could get more description over how I can actually do a comparision with just classes and throw away the dicts. That would be very cool to know how – ProtractorNewbie Apr 29 at 16:29
• Currently I do not know how to do it as for today but am willing to learn :) Regarding the seperation is something I will work on. I did realize that I have done something more complicated and harder to read, thanks for that :) Will work on that part but now im more concern if im going to change with classes then I most likely wont need the dicts at all. Lets see what you have to say :D Excited to see! – ProtractorNewbie Apr 29 at 16:31
• Let us continue this in chat: chat.stackexchange.com/rooms/123085/… – ProtractorNewbie Apr 29 at 18:37
• Hey again! Unfortunately I need to go back to sleep as I was waiting for a reply. :) I hope and wish that I could get an answer back, would mean alot for me! – ProtractorNewbie Apr 29 at 23:48