-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbircbot
1057 lines (962 loc) · 24.8 KB
/
bircbot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, June 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/gpl-2.0.html>,
# or in pdf format at <http://www.dhampir.no/stuff/private/gpl-2.0.pdf>
# Copyright 2012-2016 - Øyvind 'bolt' Hvidsten <[email protected]>
# Description:
#
# BIRCBOT is an IRC bot written for Bash 3 / Bash 4
# It creates the network connection using NetCat (nc) or ncat (nmap package)
# Tested on Linux (Debian, RedHat and CentOS)
#
# Please note: An IRC bot in Bash is a bad idea. This was written solely for
# experimental and educational purposes. Do not attempt to run
# this script as a privileged user.
#
# User config belongs in:
# $HOME/.bircbot
#
# For updates, please see <http://www.dhampir.no/stuff/bash/bircbot>.
#
# Comments welcome, improvements/patches twice as welcome.
#
# Releases / Changelog:
#
# v0.10, 2012-06-11 - Initial v0.1 release
# * All intended functionality implemented
#
# v0.11, 2012-07-31 - First update after extended field test
# * Fixed a bug where addressing the bot privately wouldn't
# remove the address character or nickname from the data
# * Added lots of comments
# * Some general cleanup
#
# v0.20, 2013-04-24 - Admin re-write
# * Admins are now authenticated by host instead of passwords
# * All relevant modules updated for above change
# * Default help factoid can now be set using the magic factoids_help fact
#
# v0.60, 2013-09-15 - Feature creep
# * New release with lots more functionality added and various fixes
# * Core: Reply nicks can be overridden
#
# v1.00, 2013-09-18 - Release
# * Ability to disable mods
# * Stress tests and unstable network tests passed
# * All planned features implemented
#
# v1.01, 2014-01-21 - Bugfix
# * Bot now handles servers with no configured MOTD
#
# v1.02, 2014-08-23 - Better addressing
# * Case insensitive nick check when addressing the bot
#
# v1.03, 2015-12-11 - Changed to use full version of shellfunc, as maintaining the reduced
# edition was a waste of time
# * Fixed broken CTCP replies
#
# v1.10, 2016-01-09 - Ticking modules no longer consume vast amounts of CPU time
# * Option to disable ticking mods removed
#
# v1.12, 2016-01-16 - Changes to allow bircbot to run from any directory
#
# v1.13, 2016-03-13 - Numerous security fixes and general improvements
#
# v1.14, 2016-03-28 - FIFO now contains generic messages
#
# v1.15, 2016-09-29 - Reset RX timeout on reconnect
#
# v1.20, 2016-10-10 - SSL
# * Added support for ncat (nmap), with SSL
# * Added support for network specific error handling
# * Added support for nick release and ghosting on Freenode
# * Added support for waiting for a hidden host before joining channels
# * Fixed a bunch of smaller bugs and minor issues
#
# v1.21, 2016-10-10 - Debian Squeeze support
# * Fixed "bad substitution" errors
#
# v1.30, 2017-02-24 - Mosquitto integration
#
# v1.31, 2017-02-25 - Better special functions and communication export
#
# v1.32, 2017-04-21 - Fake ping, handles communication corruption somewhat better...
#
# v1.33, 2017-07-21 - Small code style cleanup. Hopefully no functional changes.
#
# v1.40, 2017-10-01 - Switched to using bashdb for large tables previously stored space
# separated in memory
#
_scriptname="bircbot"
set -e
set -u
# version
VERSION=("BIRCBOT" "v1.40")
# statics
declare -ri STATE_INIT=0
declare -ri STATE_CONNECTED=1
declare -ri STATE_RUNNING=2
declare -ri STATE_SHUTDOWN=3
# smart sourcing
function ssource {
while (( $# )); do
if [[ -f "$1" ]] && [[ -r "$1" ]]; then
source "$1"
return
fi
shift
done
return 1
}
# source
botdir="$(dirname "${BASH_SOURCE[0]}")"
ssource /cathedral/src/lib/shellfunc "${botdir}/shellfunc"
ssource /cathedral/src/lib/bashdb "${botdir}/bashdb"
ssource /cathedral/userbin/.bircbot/irccodes.src "${botdir}/irccodes.src"
# print bircbot version
sf_stdout "${VERSION[@]}"
# print bash version, and quit if version is too low
sf_stdout "Running on Bash version: $BASH_VERSION"
if (( BASH_VERSINFO[0] < 4 )); then
sf_error "$_scriptname requires Bash 4 to run!"
exit 1
fi
# print basic usage instructions
function printusage
{
cat - >&2 <<EOF
Description:
Bash IRC Bot - configuration should reside in \$HOME/.bircbot/
- Requires Bash 4.0 or above -
Usage: ${_scriptname}
Options:
-n
Force the use of ncat even for non-ssl connections.
-v
Verbose. Will output extra information about what's going on.
Can be specified multiple times for extra debug spam.
EOF
}
# check if a variable is declared
function isset { declare -p "$@" >/dev/null 2>&1; }
# read options
_sf_verbose=false
moddebug=false
use_ncat=false
OPTIND=1
while getopts ":nvV" opt; do
case "$opt" in
n) use_ncat=true ;;
v)
if ! $_sf_verbose; then
_sf_verbose=true
else
set -x
fi
;;
V) moddebug=true ;;
[?])
sf_error_unknown_option
printusage
exit 1
;;
:)
sf_error_missing_argument
printusage
exit 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# config
CONFIG="${1:-"${CONFIG:-"${HOME}/.bircbot"}"}"
if ! source "$CONFIG/bircbot.conf" 2>/dev/null; then
sf_error "Unable to read $CONFIG/bircbot.conf"
sf_stderr
sf_stderr "To configure, try this:"
sf_stderr " mkdir ${HOME}/.bircbot"
sf_stderr " cp /cathedral/userbin/.bircbot/bircbot.conf.example ${HOME}/.bircbot/bircbot.conf"
sf_stderr " * edit ${HOME}/.bircbot/bircbot.conf using your favorite editor *"
sf_stderr " run the bot :)"
exit 1
fi
# variables
SERVER=${SERVER:-"irc.freenode.net"}
PORT=${PORT:-"6667"}
SSL=${SSL:-false}
NETWORK=${NETWORK:-"freenode"}
NICK=${NICK:-"bircbot"}
NICK=${NICK:0:16}
USER=${USER:-"bot"}
NAME=${NAME:-"BIRCBOT"}
PASS=${PASS:-""}
MODE=${MODE:-"8"}
RELAX=${RELAX:-"0.25"}
ADDRESS=${ADDRESS:-"!"}
PRIVADDRESS=${PRIVADDRESS-"There is no need to address me in a private message. I already know you're talking to me :)"}
isset CHANNELS || declare -a CHANNELS=()
MAXLENGTH=${MAXLENGTH:-400}
QUITMSG=${QUITMSG:-"${VERSION[@]}"}
FLOOD_COUNT=${FLOOD_COUNT:-4}
FLOOD_TIME=${FLOOD_TIME:-10}
PING_TIME=${PING_TIME:-120}
TIMEOUT=${TIMEOUT:-600}
# misc
isset floodcheck || declare -A floodcheck=()
shopt -s nullglob
nick=""
hidden=false
connect_time=0
TXCOUNT=0
catpid=""
# chew
if $SSL; then
use_ncat=true
fi
# find the cat
if $use_ncat; then
if ! type "ncat" &>/dev/null; then
sf_error 'Unable to find the "ncat" command. Install NMap, or modify your $PATH'
exit 1
fi
else
if ! type "nc" &>/dev/null; then
sf_error 'Unable to find the "nc" command. Install NetCat, or modify your $PATH'
exit 1
fi
fi
# clean up temporary files
function cleanup
{
code=$?
set +e
if [[ -n "$catpid" ]]; then
if kill -0 $catpid 2>/dev/null; then
sf_stdout "Killing the cat($catpid)"
kill -TERM $catpid
else
sf_stdout "The cat isn't running"
fi
fi
sf_killchildren
sf_stdout "Waiting for all children to die"
wait
sf_rm_process
sf_stdout "Cleanup complete"
}
trap cleanup EXIT
# get temp dir
TMP=${TMP:-$(sf_tmpdir)}
# array of variables to be unset when the connection to the server is restarted
# can be used by mods that store the current state of channels and conversations
isset unset_on_reset || declare -a unset_on_reset=()
function unset_on_reset
{
local i
if (( $# == 0 )); then
if [[ -n "${unset_on_reset[*]:-}" ]]; then
for i in "${unset_on_reset[@]}"; do
unset "$i"
done
fi
else
if [[ -n "${unset_on_reset[*]:-}" ]]; then
for i in "${unset_on_reset[@]}"; do
[[ "$i" != "$1" ]] || return 0
done
fi
unset_on_reset+=( "$1" )
sf_stdoutv "Unset on reset: $1"
fi
return 0
}
# how to limit crap
craplimiter_lock="${TMP}/bircbot_craplimiter_$$.lock"
function craplimiter
{(
crap_data="$1" id="$2" delay="$3" add="$4"
sf_force -d 0.5 sf_mkfile -f "$craplimiter_lock" >/dev/null
trap "rm \"$craplimiter_lock\"" EXIT
code=0
lines=()
while read -r time oid; do
(( time > SECONDS )) || continue
[[ "$oid" != "$id" ]] || code=1
lines+=( "$time $oid" )
done <"$crap_data"
! $add || lines+=( "$((SECONDS + delay)) $id" )
>"$crap_data"
for line in "${lines[@]:-}"; do
echo "$line" >>"$crap_data"
done
exit $code
)}
# How to curl
function curl
{
# shellcheck disable=SC2086
command curl \
--silent \
--insecure \
--user-agent "Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.2.0" \
${CURL_PROXY:+--socks4 "$CURL_PROXY"} \
${CURL_OPTS:-} \
"$@"
}
# Fast curl (no proxy)
function fcurl { CURL_PROXY='' curl "$@"; }
# start netcat
function startnetcat
{
state=$STATE_INIT
sf_stdout "State: init"
unset_on_reset
# generate fifo's for communication between subshells
sf_stdoutv "Generating FIFO's"
if [[ -n "${rx:-}" ]]; then
rm "$rx"
sf_rm_abort "$rx"
fi
if [[ -n "${tx:-}" ]]; then
rm "$tx"
sf_rm_abort "$tx"
fi
sf_mkfifo -qo tx
sf_stdoutv "TX: $tx"
sf_mkfifo -qo rx
sf_stdoutv "RX: $rx"
# go cat go
if $use_ncat; then
ncat "$(! $SSL || echo "--ssl")" "$SERVER" "$PORT" >"$rx" <"$tx" &
else
nc "$SERVER" "$PORT" >"$rx" <"$tx" &
fi
exec 3<"$rx" 4>"$tx"
catpid=$!
hidden=false
connect_time=$(sf_unixtime)
last_rx=$SECONDS
ping_target=""
sf_stdout "Connecting..."
sf_stdoutv "Cat: $catpid"
}
startnetcat
# submit a raw message to the server - only length is limited, no other processing is done
function tx
{
((++TXCOUNT))
local text="$*"
if (( ${#text} > MAXLENGTH )); then
sf_warning "Output text limited to $MAXLENGTH characters!"
text=${text:0:$MAXLENGTH}
fi
sf_stdout "TX: $*"
echo "$*" >&4
}
# perform an action (like /me in mIRC)
function action
{
local reply=$1
shift
if [[ -z "${reply:-}" ]]; then
sf_error "$FUNCNAME was called without a valid reply target!"
exit 1
fi
tx "PRIVMSG $reply :"$'\x01'"ACTION $*"$'\x01'
log_output "$reply" "CTCP ACTION $*"
}
# perform an action in all channels
function action_all
{
local channel
for channel in "${current_channels[@]}"; do
action "$channel" "$*"
done
}
# fallback action - performs an action as a fallback if no other reply was given
function faction
{
if [[ -z "${reply:-}" ]]; then
sf_error "$FUNCNAME was called without a valid reply target!"
exit 1
fi
if (( $# != 0 )); then
local priority=$1
if ! sf_integer -vq -- "$priority"; then
sf_error "Invalid priority in call to $FUNCNAME"
exit 1
fi
shift
local message="$*"
if [[ -z "$message" ]]; then
sf_error "No message in call to $FUNCNAME"
exit 1
fi
sf_stdoutv "$FUNCNAME: Adding fallback action \"$message\" with priority $priority"
bircbot_factions[$priority]=$message
else
local priority=-1 p
for p in "${!bircbot_factions[@]}"; do
if (( p > priority )); then
priority=$p
fi
done
if (( priority != -1 )); then
action "$reply" "${bircbot_factions[$priority]}"
else
return 1
fi
fi
return 0
}
# say something in a channel
function say
{
local reply=$1
shift
if
[[ -z "${reply:-}" ]] ||
[[ -z "$*" ]]
then
sf_error "$FUNCNAME was called with invalid parameters!"
exit 1
fi
tx "PRIVMSG $reply :$*"
log_output "$reply" "PRIVMSG $*"
}
# say something in all channels
function say_all
{
local channel
for channel in "${current_channels[@]}"; do
say "$channel" "$*"
done
}
# reply to whoever sent us the message
function reply
{
if [[ -z "${reply:-}" ]]; then
sf_error "$FUNCNAME was called without a valid reply target!"
exit 1
fi
if [[ -z "$@" ]]; then
sf_warning "$FUNCNAME was called with no text"
return
fi
if [[ "$reply" = "#"* ]]; then
tx "PRIVMSG $reply :${reply_nick:-"$(src_nick)"}: $*"
log_output "$reply" "PRIVMSG ${reply_nick:-"$(src_nick)"}: $*"
else
tx "PRIVMSG $reply :$*"
log_output "$reply" "PRIVMSG $*"
fi
}
# fallback reply - replies if no other reply was given
function freply
{
if [[ -z "${reply:-}" ]]; then
sf_error "$FUNCNAME was called without a valid reply target!"
exit 1
fi
if (( $# != 0 )); then
local priority=$1
if ! sf_integer -vq -- "$priority"; then
sf_error "Invalid priority in call to $FUNCNAME"
exit 1
fi
shift
local message="$*"
if [[ -z "$message" ]]; then
sf_error "No message in call to $FUNCNAME"
exit 1
fi
sf_stdoutv "$FUNCNAME: Adding fallback reply \"$message\" with priority $priority"
bircbot_freplies[$priority]=$message
bircbot_freplynicks[$priority]=${reply_nick:-"$(src_nick)"}
else
local priority=-1 p
for p in "${!bircbot_freplies[@]}"; do
if (( p > priority )); then
priority=$p
fi
done
if (( priority != -1 )); then
reply_nick="${bircbot_freplynicks[$priority]}" \
reply "${bircbot_freplies[$priority]}"
else
return 1
fi
fi
return 0
}
# check if an admin is speaking - should be overridden by admin.bmod or another mod
function admin_has
{
sf_warning "Default implementation of $FUNCNAME was called. This should never happen!"
exit 1
}
# same as admin_has, but reply if admin access is not granted - should be overridden by admin.bmod or another mod
function admin_verbosehas
{
admin_has "$@"
}
# export input and output to modules
function log_input
{
local func
for func in "${loginputs[@]:-}"; do
[[ -n "$func" ]] || continue
$func
done
}
function log_output
{
local func
for func in "${logoutputs[@]:-}"; do
[[ -n "$func" ]] || continue
$func "$@"
done
}
# verify that a user is not flooding the bot
function floodcheck
{
if ! ${FLOOD_CHECK:-true}; then
sf_stdoutv "$FUNCNAME: Flood checking disabled"
return 0
fi
local nick=$1 warn=true now i count=0 silent=${2:-false}
now=$(sf_unixtime)
if ! $silent && [[ -z "${reply:-}" ]]; then
sf_error "$FUNCNAME was called non-silently without a valid reply target!"
exit 1
fi
isset times || declare -a times=()
if [[ -n "${floodcheck[$nick]:-}" ]]; then
read -r warn <<<"${floodcheck[$nick]%% *}"
read -ra times <<<"${floodcheck[$nick]#* }"
for i in "${times[@]}"; do
((i + FLOOD_TIME < now)) || ((++count))
done
fi
if ((${#times[@]} >= FLOOD_COUNT)); then
unset "times[0]"
fi
times[FLOOD_COUNT]=$now
if ((count >= FLOOD_COUNT)); then
sf_stdoutv "$FUNCNAME ($1): DENY message"
if ! $silent && $warn; then
reply "Whoa! Relax! You are flooding the bot! Please wait 10 seconds and try again."
warn=false
fi
floodcheck["$nick"]="$warn ${times[*]}"
return 1
else
sf_stdoutv "$FUNCNAME ($1): ALLOW message"
warn=true
floodcheck["$nick"]="$warn ${times[*]}"
return 0
fi
}
# perform a clean exit on SIGINT (ctrl+c)
function clean_exit
{
trap - INT
sf_stdoutv
if ((state != STATE_SHUTDOWN)) || ((state == STATE_RUNNING)); then
sf_stdout "State: shutdown"
state=$STATE_SHUTDOWN
tx "QUIT :$QUITMSG"
fi
sleep 1
}
trap clean_exit INT
# function to cut our address character or nick off of the data
function data_address_size
{
local lowdata=${data,,}
local lowadd=${ADDRESS,,}
local lownick=${nick,,}
# addressing by the address character(s)
if [[ "$lowdata" = "$lowadd"* ]]; then
echo "${#ADDRESS}"
return 0
fi
# addressing by nick
if
[[ "$lowdata" = "${lownick}, "* ]] ||
[[ "$lowdata" = "${lownick}: "* ]] ||
[[ "$lowdata" = "${lownick} "* ]]
then
echo "$((${#nick}+1))"
return 0
fi
# addressing with an at
if
[[ "$lowdata" = "@${lownick}, "* ]] ||
[[ "$lowdata" = "@${lownick}: "* ]] ||
[[ "$lowdata" = "@${lownick} "* ]]
then
echo "$((${#nick}+2))"
return 0
fi
# not addressing the bot
echo "0"
return 1
}
function cutdata
{
local size
size=$(data_address_size)
if (( size == 0 )); then
return 1
fi
data=${data:$size}
read -r data <<<"$data"
if [[ -n "$data" ]]; then
return 0
else
return 1
fi
}
# get info from $src
function src_nick
{
echo -n "${src%%\!*}"
}
function src_host
{
echo -n "${src#*\!}"
}
# get data from a given case insensitive word
function dfrom
{
local from="${*,,}"
local d="${data,,}"
local cut="$data"
while [[ -n "$d" ]] && [[ "$d" != "$from "* ]]; do
read -r d <<<"${d#* }"
read -r cut <<<"${cut#* }"
done
read -r cut <<<"${cut#* }"
echo "$cut"
}
# get data from a given index
function dfromi
{
local i="$*"
if ! sf_integer -vq -- "$i" || ! (( i )); then
sf_error "Invalid index in call to $FUNCNAME"
exit 1
fi
local cut="$data"
while (( i-- )); do
read -r cut <<<"${cut#* }"
done
echo "$cut"
}
# utility function to cut ctcp from text
function filtertext
{
sed -e 's/^[\x01]//g' <<<"$@"
}
# utility function to cut one character off of the right
# bash 4.2.37 (debian wheezy) has a bug with %?
# $ a='foo\'; echo ${a%?}
# foo\
function cutright
{
local line="$*"
if [[ -n "$line" ]]; then
echo -n "${line:0:$((${#line}-1))}"
fi
}
# change to a random nick
function guestnick
{
nick="Guest$((RANDOM%90000+10000))"
tx "NICK $nick"
}
# attempt to process a network error handler
function network_error
{
[[ -n "$NETWORK" ]] || return 1
local eh
for eh in "$CONFIG/${NETWORK}.eh" "${botdir}/${NETWORK}.eh" "/cathedral/userbin/.bircbot/${NETWORK}.eh"; do
sf_goodfile "$eh" || continue
source "$eh" && return 0 || return 1
done
sf_stdout "No error handler for $NETWORK"
return 1
}
# tick tock - runs every second
tick=$SECONDS
last_rx=$SECONDS
ping_target=""
function tick
{
(( ++tick ))
if (( state != STATE_SHUTDOWN )) && [[ -n "$catpid" ]] && ! kill -0 $catpid 2>/dev/null; then
catpid=""
sf_error "The cat died!"
startnetcat
fi
if (( last_rx + TIMEOUT < SECONDS )); then
sf_warning "No messages from server in $((SECONDS-last_rx)) seconds - timeout!"
kill -TERM $catpid
elif (( last_rx + PING_TIME < SECONDS )) && ! (( tick % 10 )); then
sf_warning "No messages from server in $((SECONDS-last_rx)) seconds - ping attempt"
tx "PING :$nick"
[[ -z "$ping_target" ]] || tx "PONG $ping_target"
fi
}
# list of ticker functions - used for ticking modules
declare -a tickers=()
# list of logger functions - used to export communications
declare -a loginputs=()
declare -a logoutputs=()
# main loop
while true; do
# attempt to read input
if read -r -t "$RELAX" -u 3 line; then
# got input - reset timeout
last_rx=$SECONDS
# reset the reply counter
TXCOUNT=0
# read the line and print it
line=${line%$'\r'}
echo "RX: $line"
# reset variables
botnick="$nick" # our current nick
src="" # source of message (nick@host)
cmd="" # message type
target="" # target of message (channel, bot...)
data="" # message content
data_export="" # message content, suitable for export
data_array=() # message content array
data_larray=() # message content array (lowercase)
data_count=0 # message content array length
reply="" # where to reply to
srv=false # message is from the server
# if the message starts with a colon, read src
[[ "$line" != :* ]] || read -r src line <<<"$line"
# read cmd
read -r cmd line <<<"$line"
# read target and data (quit messages have no target)
case "$cmd" in
QUIT)
read -r data <<<"$line"
;;
*)
read -r target data <<<"$line"
;;
esac
# remove colons
src=${src#:}
data=${data#:}
target=${target#:}
# set the raw data now
data_export="- $data"
# if the source doesn't contain something that resembles "nick@host", this is most likely a server message
[[ "$src" = *"!"* ]] || [[ "$src" = *"@"* ]] || srv=true
# respond to people saying things
if [[ "$cmd" = "PRIVMSG" ]]; then
# update export data with correct cmd
data_export="$cmd $data"
# CTCP support (rudimentary)
if [[ "$data" = $'\x01'*$'\x01' ]]; then
cmd="CTCP"
data=${data#$'\x01'}
data=${data%$'\x01'}
data_export="$cmd $data"
# someone is messaging us privately
elif [[ "$target" = "$nick" ]]; then
reply=$(src_nick)
if ! admin_has "$(src_host)" && ! floodcheck "$(src_nick)"; then
reply=""
elif data_address_size >/dev/null; then
if [[ -n "$PRIVADDRESS" ]]; then
tx "PRIVMSG $(src_nick) :$PRIVADDRESS"
reply=""
elif ! cutdata; then
reply=""
fi
fi
# someone is saying something prefixed by our address character or nick in a channel we're in
elif data_address_size >/dev/null; then
if cutdata; then
reply=$target
admin_has "$(src_host)" || floodcheck "$(src_nick)" || reply=""
fi
fi
fi
# data array
read -r -a data_array <<<"$data"
read -r -a data_larray <<<"${data,,}"
data_count=${#data_array[*]}
# print what we parsed
sf_stdoutv "src: $src"
sf_stdoutv "cmd: $cmd"
sf_stdoutv "target: $target"
sf_stdoutv "data: $data"
sf_stdoutv "srv: $srv"
sf_stdoutv "reply: $reply"
# respond to commands
case "${cmd^^}" in
PING)
tx "PONG $target"
ping_target=$target
;;
CTCP)
case "$data" in
PING|"PING "*)
tx "NOTICE $(src_nick) :"$'\x01'"$data"$'\x01'
;;
VERSION)
if [[ -n "${CUSTOMVERSION:-}" ]]; then
tx "NOTICE $(src_nick) :"$'\x01'"VERSION $CUSTOMVERSION"$'\x01'
else
tx "NOTICE $(src_nick) :"$'\x01'"VERSION $(IFS=":"; echo -n "${VERSION[*]}"):Bash ${BASH_VERSION}"$'\x01'
fi
;;
TIME)
if [[ -n "${CUSTOMTIME:-}" ]]; then
tx "NOTICE $(src_nick) :"$'\x01'"TIME $CUSTOMTIME"$'\x01'
else
tx "NOTICE $(src_nick) :"$'\x01'"TIME $(sf_timestamp)"$'\x01'
fi
;;
esac
;;
NOTICE)
data=${data#$'\x01'}
data=${data%$'\x01'}
sf_stdoutv "We received a notice"
;;
NICK)
if [[ "$(src_nick)" = "$nick" ]]; then
nick=${target#:}
sf_stdoutv "This bot is now known as $nick"
else
sf_stdoutv "$(src_nick) is now known as ${target#:}"
fi
;;
ERROR)
if ((state == STATE_SHUTDOWN)); then
sf_stdoutv "IRC server closed the connection in response to our QUIT message. Exiting."
exit 0
else
sf_stdout "IRC server reported an error. Exiting."
exit 1
fi
;;
esac
if sf_integer -- "$cmd"; then
case "$((cmd))" in
$RPL_WELCOME)
nick=$target
;;
$RPL_HOSTHIDDEN)
hidden=true
;;
$ERR_NICKNAMEINUSE)
guestnick
if ! network_error; then
sf_error "Nickname is already in use."
exit 1
fi
;;
$ERR_UNAVAILRESOURCE)
guestnick
if ! network_error; then
sf_error "Nickname is temporarily unavailable."
exit 1
fi
;;
$RPL_ENDOFMOTD|$ERR_NOMOTD)
if ((state == STATE_CONNECTED)); then
state=$STATE_RUNNING
sf_stdout "State: running"
fi
;;
esac
fi
# state machine
case "$state" in
$STATE_INIT)
state=$STATE_CONNECTED
sf_stdout "State: connected"
tx "PASS $PASS"
tx "NICK $NICK"
tx "USER ${USER} ${MODE} * :${NAME}"
;;
$STATE_RUNNING)
# keep track of the mods we've run - this allows overriding global modules with local ones
declare -a modules=()
# iterator
declare -i bircbot_i
# fallback nicks, replies and actions - will respond with these, by priority, if nothing else replies directly
declare -A bircbot_freplies=()
declare -A bircbot_factions=()
declare -A bircbot_freplynicks=()
# run loginputs
log_input