Add announce script for posting to Discord channels
Usage: ./scripts/announce.sh "message" [channel_name] Fetches the bot token from barge, resolves channel by name, and posts via the Discord API. Defaults to #general. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
63
scripts/announce.sh
Normal file
63
scripts/announce.sh
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# Post an announcement to a Discord channel using the bot's token.
|
||||
# Usage: ./scripts/announce.sh "Your message here" [channel_name]
|
||||
# Default channel: general
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
MESSAGE="${1:?Usage: announce.sh \"message\" [channel_name]}"
|
||||
CHANNEL_NAME="${2:-general}"
|
||||
|
||||
# Fetch bot token from barge
|
||||
TOKEN=$(ssh aj@barge.lan "grep DISCORD_BOT_TOKEN /mnt/docker/breehavior-monitor/.env" | cut -d= -f2-)
|
||||
|
||||
if [[ -z "$TOKEN" ]]; then
|
||||
echo "ERROR: Could not read bot token from barge." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get guilds the bot is in
|
||||
GUILDS=$(curl -s -H "Authorization: Bot $TOKEN" "https://discord.com/api/v10/users/@me/guilds")
|
||||
GUILD_ID=$(echo "$GUILDS" | python -c "import sys,json; print(json.load(sys.stdin)[0]['id'])")
|
||||
|
||||
if [[ -z "$GUILD_ID" ]]; then
|
||||
echo "ERROR: Could not find guild." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get channels and find the target by name
|
||||
CHANNEL_ID=$(curl -s -H "Authorization: Bot $TOKEN" "https://discord.com/api/v10/guilds/$GUILD_ID/channels" \
|
||||
| python -c "
|
||||
import sys, json
|
||||
channels = json.load(sys.stdin)
|
||||
for ch in channels:
|
||||
if ch['name'] == sys.argv[1] and ch['type'] == 0:
|
||||
print(ch['id'])
|
||||
break
|
||||
" "$CHANNEL_NAME")
|
||||
|
||||
if [[ -z "$CHANNEL_ID" ]]; then
|
||||
echo "ERROR: Channel #$CHANNEL_NAME not found." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Build JSON payload safely
|
||||
PAYLOAD=$(python -c "import json,sys; print(json.dumps({'content': sys.argv[1]}))" "$MESSAGE")
|
||||
|
||||
# Post the message
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Authorization: Bot $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$PAYLOAD" \
|
||||
"https://discord.com/api/v10/channels/$CHANNEL_ID/messages")
|
||||
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
|
||||
|
||||
if [[ "$HTTP_CODE" == "200" ]]; then
|
||||
echo "Posted to #$CHANNEL_NAME"
|
||||
else
|
||||
BODY=$(echo "$RESPONSE" | sed '$d')
|
||||
echo "ERROR: HTTP $HTTP_CODE" >&2
|
||||
echo "$BODY" >&2
|
||||
exit 1
|
||||
fi
|
||||
Reference in New Issue
Block a user