Switch Discord notifications from webhook to user ID DMs
Uses the existing bot token to send DMs to users by their Discord user ID instead of posting to a channel webhook. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -19,8 +19,8 @@ def _sendToEnabledChannels(notif_settings, message, user_uuid=None):
|
||||
"""Send message to all enabled channels. Returns True if at least one succeeded."""
|
||||
sent = False
|
||||
|
||||
if notif_settings.get("discord_enabled") and notif_settings.get("discord_webhook"):
|
||||
if discord.send(notif_settings["discord_webhook"], message):
|
||||
if notif_settings.get("discord_enabled") and notif_settings.get("discord_user_id"):
|
||||
if discord.send_dm(notif_settings["discord_user_id"], message):
|
||||
sent = True
|
||||
|
||||
if notif_settings.get("ntfy_enabled") and notif_settings.get("ntfy_topic"):
|
||||
@@ -44,7 +44,7 @@ def getNotificationSettings(userUUID):
|
||||
def setNotificationSettings(userUUID, data_dict):
|
||||
existing = postgres.select_one("notifications", {"user_uuid": userUUID})
|
||||
allowed = [
|
||||
"discord_webhook",
|
||||
"discord_user_id",
|
||||
"discord_enabled",
|
||||
"ntfy_topic",
|
||||
"ntfy_enabled",
|
||||
@@ -64,11 +64,33 @@ def setNotificationSettings(userUUID, data_dict):
|
||||
|
||||
class discord:
|
||||
@staticmethod
|
||||
def send(webhook_url, message):
|
||||
def send_dm(user_id, message):
|
||||
"""Send a DM to a Discord user via the bot."""
|
||||
bot_token = os.environ.get("DISCORD_BOT_TOKEN")
|
||||
if not bot_token:
|
||||
logger.warning("DISCORD_BOT_TOKEN not set, skipping Discord DM")
|
||||
return False
|
||||
headers = {"Authorization": f"Bot {bot_token}", "Content-Type": "application/json"}
|
||||
try:
|
||||
response = requests.post(webhook_url, json={"content": message})
|
||||
return response.status_code == 204
|
||||
except:
|
||||
# Open/get DM channel with the user
|
||||
dm_resp = requests.post(
|
||||
"https://discord.com/api/v10/users/@me/channels",
|
||||
headers=headers,
|
||||
json={"recipient_id": user_id},
|
||||
)
|
||||
if dm_resp.status_code != 200:
|
||||
logger.error(f"Failed to open DM channel for user {user_id}: {dm_resp.status_code}")
|
||||
return False
|
||||
channel_id = dm_resp.json()["id"]
|
||||
# Send the message
|
||||
msg_resp = requests.post(
|
||||
f"https://discord.com/api/v10/channels/{channel_id}/messages",
|
||||
headers=headers,
|
||||
json={"content": message},
|
||||
)
|
||||
return msg_resp.status_code == 200
|
||||
except Exception as e:
|
||||
logger.error(f"Discord DM error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user