From 5d94dae366eb5c89673550701d49ea6232e5e215 Mon Sep 17 00:00:00 2001 From: Nick Chambers Date: Tue, 7 Dec 2021 03:35:23 -0600 Subject: [PATCH] bash/irc: a bare-bones IRC line parser --- bash/irc | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 bash/irc diff --git a/bash/irc b/bash/irc new file mode 100755 index 0000000..da6847f --- /dev/null +++ b/bash/irc @@ -0,0 +1,52 @@ +#!/usr/bin/env bash + +host=irc.libera.chat port=6667 +nick=bashbot ident=bashbot realname=bashbot +channels=##bashbot + +exec {sock}<>/dev/tcp/"$host"/"$port" + +while IFS= read -ru "$sock" line; do + line=${line%$'\r'} + declare -A msg=( [words]=no [original]="$line" ) + + if [[ ${line:0:1} = : ]]; then + prefix=${line%% *} line=${line#"$prefix"} line=${line# } prefix=${prefix#:} + msg[host]=${prefix#*@} prefix=${prefix%"${msg[host]}"} prefix=${prefix%@} + msg[from]=${msg[host]} + + if [[ $prefix ]]; then + msg[ident]=${prefix#*!} + msg[from]=${msg[ident]} + + if [[ ${msg[ident]} != "$prefix" ]]; then + msg[nick]=${prefix%!*} + msg[from]=${msg[nick]} + fi + fi + fi + + msg[cmd]=${line%% *} msg[cmd]=${msg[cmd]^^} + line=${line#"${msg[cmd]}"} line=${line# } + msg_args=( ) + + while [[ $line ]]; do + if [[ ${line:0:1} = : ]]; then + msg_args+=( "${line:1}" ) msg[words]=yes line= + read -ra msg_words <<< "${msg_args[-1]}" + else + arg=${line%% *} msg_args+=( "$arg" ) + line=${line#"$arg"} line=${line# } + fi + done + + if [[ ${msg[cmd]} = @(PRIVMSG|NOTICE) ]]; then + if [[ ${msg_args[0]:0:1} = \# ]]; then + msg[to]=${msg_args[0]} + else + msg[to]=${msg[from]} + fi + fi + + printf '%s\n' "${msg[original]}" +done