Skip to content

Instantly share code, notes, and snippets.

@Summertime
Created September 30, 2021 16:19

Revisions

  1. Summertime created this gist Sep 30, 2021.
    75 changes: 75 additions & 0 deletions mc-to-discord.bash
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    #!/usr/bin/env bash
    shopt -s extglob

    : ${WEBHOOK:?Requires envvar WEBHOOK}
    for C in jq curl; do
    if command -v "$C" > /dev/null; then
    echo "Requires $C to be installed"
    exit 1
    fi
    done

    RE_USER='[[:alnum:]_-]*'
    : '[[:xdigit:]]'
    RE_UUID="$_{8}-$_{4}-$_{4}-$_{4}-$_{12}"

    DEFAULT_UUID=870aba9340e848b389c532ece00d6630

    declare -A UUIDS=

    while read -r; do
    if ! [[ $REPLY =~ ^'['.*?'] ['.*?'] [minecraft/'(.*?)']: '(.*)$ ]]; then
    continue
    fi
    VIA="${BASH_REMATCH[1]}"
    MSG="${BASH_REMATCH[2]}"
    if [ ]; then : ;
    # Authentication stuff
    elif [[ $VIA = 'ServerLoginNetHandler' ]]; then
    # UUID notice
    if [[ $MSG =~ ^'UUID of player '($RE_USER)' is '($RE_UUID)$ ]]; then
    UUIDS[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
    fi
    # General messages
    elif [[ $VIA = 'DedicatedServer' ]]; then
    if [ ]; then : ;
    # Join
    elif [[ $MSG =~ ^($RE_USER)' joined the game'$ ]]; then
    jq -nc \
    --arg USERNAME "${BASH_REMATCH[1]}" \
    --arg UUID "${UUIDS[${BASH_REMATCH[1]}]:-$DEFAULT_UUID}" \
    '{ "content": "**\($USERNAME)** joined the game" }'
    # Part
    elif [[ $MSG =~ ^($RE_USER)' left the game'$ ]]; then
    jq -nc \
    --arg USERNAME "${BASH_REMATCH[1]}" \
    --arg UUID "${UUIDS[${BASH_REMATCH[1]}]:-$DEFAULT_UUID}" \
    '{ "content": "**\($USERNAME)** left the game" }'
    # User Message
    elif [[ $MSG =~ ^'<'($RE_USER)'> '(.*)$ ]]; then
    jq -nc \
    --arg USERNAME "${BASH_REMATCH[1]}" \
    --arg UUID "${UUIDS[${BASH_REMATCH[1]}]:-$DEFAULT_UUID}" \
    --arg MESSAGE "${BASH_REMATCH[2]}" \
    '{
    "content": $MESSAGE,
    "username": $USERNAME,
    "avatar_url": "https://crafatar.com/renders/head/\($UUID)?scale=10"
    }'
    # User Action
    elif [[ $MSG =~ ^'* '($RE_USER)' '(.*)$ ]]; then
    jq -nc \
    --arg USERNAME "${BASH_REMATCH[1]}" \
    --arg UUID "${UUIDS[${BASH_REMATCH[1]}]:-$DEFAULT_UUID}" \
    --arg MESSAGE "${BASH_REMATCH[2]}" \
    '{
    "content": "_\($MESSAGE)_",
    "username": $USERNAME,
    "avatar_url": "https://crafatar.com/renders/head/\($UUID)?scale=10"
    }'
    fi
    fi
    done |
    while read -r; do
    curl -sS -H "Content-Type: application/json" -d @- "$WEBHOOK" <<< $REPLY
    done