core/services/notify.py

46 lines
1.5 KiB
Python
Raw Normal View History

2023-10-05 18:46:18 +00:00
import json
2023-12-17 20:30:20 +00:00
2023-10-23 14:47:11 +00:00
from services.rediscache import redis
2023-10-05 18:46:18 +00:00
2023-10-23 14:47:11 +00:00
async def notify_reaction(reaction, action: str = "create"):
2023-10-19 14:42:42 +00:00
channel_name = "reaction"
2023-11-24 01:53:30 +00:00
data = {"payload": reaction, "action": action}
2023-10-05 18:46:18 +00:00
try:
await redis.publish(channel_name, json.dumps(data))
except Exception as e:
2023-11-24 01:53:30 +00:00
print(f"[services.notify] Failed to publish to channel {channel_name}: {e}")
2023-10-05 18:46:18 +00:00
2023-10-23 14:47:11 +00:00
async def notify_shout(shout, action: str = "create"):
2023-10-19 14:42:42 +00:00
channel_name = "shout"
2023-11-24 01:53:30 +00:00
data = {"payload": shout, "action": action}
2023-10-05 18:46:18 +00:00
try:
await redis.publish(channel_name, json.dumps(data))
except Exception as e:
2023-11-24 01:53:30 +00:00
print(f"[services.notify] Failed to publish to channel {channel_name}: {e}")
2023-10-05 18:46:18 +00:00
2023-10-23 14:47:11 +00:00
async def notify_follower(follower: dict, author_id: int, action: str = "follow"):
2023-10-19 14:42:42 +00:00
channel_name = f"follower:{author_id}"
2023-10-05 18:46:18 +00:00
try:
2024-01-22 23:47:23 +00:00
# Simplify dictionary before publishing
simplified_follower = {k: follower[k] for k in ["id", "name", "slug", "pic"]}
data = {"payload": simplified_follower, "action": action}
# Convert data to JSON string
json_data = json.dumps(data)
# Ensure the data is not empty before publishing
if not json_data:
raise ValueError("Empty data to publish.")
# Use the 'await' keyword when publishing
await redis.publish(channel_name, json_data)
2023-10-05 18:46:18 +00:00
except Exception as e:
2024-01-22 23:47:23 +00:00
# Log the error and re-raise it
2023-11-24 01:53:30 +00:00
print(f"[services.notify] Failed to publish to channel {channel_name}: {e}")
2024-01-22 23:47:23 +00:00
raise