Skip to content

Commit

Permalink
Removed empty values from database mapper.
Browse files Browse the repository at this point in the history
  • Loading branch information
why-not-try-calmer committed Jul 11, 2022
1 parent cc1684f commit 3302e53
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 25 deletions.
2 changes: 1 addition & 1 deletion app/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def registerHandlers(app: Application):
)
else:
print(
"Running without self-signed SSL certificate; your HTTPS requests will need to be decoded and encoded by the hosting!"
"Running without self-signed SSL certificate; your HTTPS requests will need to be decoded and encoded by the server!"
)
app.run_webhook(
listen="0.0.0.0",
Expand Down
7 changes: 3 additions & 4 deletions app/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

async def fetch_settings(chat_id: ChatId) -> Settings | None:
if doc := await chats.find_one({"chat_id": chat_id}):
print("Found settings: ", Settings(doc).as_dict_no_none())
return Settings(doc)


Expand All @@ -26,12 +27,10 @@ async def reset(chat_id: ChatId):


async def upsert_settings(settings: Settings) -> Settings | None:
if not hasattr(settings, "chat_id"):
return None

print("Trying to update: ", settings.as_dict_no_none())
if updated := await chats.find_one_and_update(
{"chat_id": settings.chat_id},
{"$set": asdict(settings)},
{"$set": settings.as_dict_no_none()},
upsert=True,
return_document=ReturnDocument.AFTER,
):
Expand Down
4 changes: 2 additions & 2 deletions app/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ async def setting_bot(update: Update, context: ContextTypes.DEFAULT_TYPE):
if len(s) == 1 or s[1] == "":
# Get
if fetched := await fetch_settings(chat_id):
reply = strings["settings"]["settings"] + str(fetched)
reply = strings["settings"]["settings"] + fetched.render(with_alert=True)
else:
reply = strings["settings"]["none_found"]
elif settings := Settings(received, chat_id):
# Set
if updated := await upsert_settings(settings):
reply = strings["settings"]["updated"] + str(updated)
reply = strings["settings"]["updated"] + updated.render(with_alert=True)
else:
reply = strings["settings"]["failed_to_update"]
else:
Expand Down
37 changes: 24 additions & 13 deletions app/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,31 @@ def __init__(self, settings: dict | str, chat_id: ChatId | None = None):
def as_dict_no_none(self) -> dict:
return {k: v for k, v in asdict(self).items() if v and v is not None}

def __str__(self) -> str:
d = self.as_dict_no_none()

def reducer(acc, item) -> str:
if item[0] in ["chat_url", "verification_msg"]:
return (
acc
+ "\n"
+ b"\xE2\x9A\xA0".decode("utf-8")
+ f"Missing an important value here ({escape_markdown(item[0])})! The bot won't be able to operate properly without it!"
)
return acc + f"{escape_markdown(item[0])}: {escape_markdown(item[1])}\n"
def render(self, with_alert: bool) -> str:
if with_alert:
d = asdict(self)

def reducer(acc, item) -> str:
if item[0] in ["chat_url", "verification_msg"] and (
not item[1] or item[1] == "None"
):
return (
acc
+ "\n"
+ b"\xE2\x9A\xA0".decode("utf-8")
+ f"Missing an important value here ({escape_markdown(item[0])})! The bot won't be able to operate properly without it!\n\n"
)
return acc + f"{escape_markdown(item[0])}: {escape_markdown(item[1])}\n"

return reduce(reducer, d.items(), "")

return reduce(reducer, d.items(), "")
else:
d = self.as_dict_no_none()
reducer = (
lambda acc, item: acc
+ f"{escape_markdown(item[0])}: {escape_markdown(item[1])}\n"
)
return reduce(reducer, d.items(), "")

def __len__(self) -> int:
return len(vars(self))
Expand Down
4 changes: 2 additions & 2 deletions strings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ uk = "Ласкаво просимо"
zn = "歡迎"

[settings]
settings = "You settings read:\n"
updated = "Thanks, your new settings read:\n"
settings = "Your settings read:\n"
updated = "Thanks, your new settings read:\n---\n"
failed_to_parse = "Unable to parse! You need to pass pairs of key-values separated by spaces, as in:\n `key1 val1 key2 val2`... The list of keys is available [here](https://github.com/why-not-try-calmer/notify-join#commands)."
failed_to_update = "Unable to update! There might be an issue with the database."
reset = "All settings reset. Get started with `/set mode auto`. Call `/help` if you need."
Expand Down
7 changes: 4 additions & 3 deletions test/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@
def test_settings():
s = Settings("/set mode auto helper_chat_id 123 chat_url abcd")
t = Settings({"mode": "auto", "helper_chat_id": "123", "chat_url": "abcd"})
print(t)
print(s.as_dict_no_none())
assert s == t


def test_settings_with_verification_msg():
s = Settings(
"/set mode auto helper_chat_id 123 chat_url abcd verification_msg\nEspace de discussion fribourgeois basé à la Gare CFF. Convivialité et bonne humeur bienvenues! Crypto, drogues, complots et sexe bannis."
)
print(s.as_dict_no_none())
assert len(s) == 4


def test_settings_pretty_print():
s = Settings("/set mode auto helper_chat_id 123")
s = Settings("/set chat_url 123")
print(s.as_dict_no_none())
assert len(s) == 2
assert len(s) == 1


def test_string():
Expand Down

0 comments on commit 3302e53

Please sign in to comment.