Merge pull request #55 from gnadelwarty/master

extend start/killproc to allow multiple background jobs
This commit is contained in:
Drew 2019-03-22 09:31:28 -04:00 committed by GitHub
commit 2eebe67e32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 136 additions and 11 deletions

View File

@ -154,6 +154,7 @@ Allowed values: typing for text messages, upload_photo for photos, record_video
send_action "${CHAT[ID]}" "action" send_action "${CHAT[ID]}" "action"
``` ```
#### Interactice Chats and background jobs
To create interactive chats, write (or edit the question script) a normal bash (or C or python) script, chmod +x it and then change the argument of the startproc function to match the command you usually use to start the script. To create interactive chats, write (or edit the question script) a normal bash (or C or python) script, chmod +x it and then change the argument of the startproc function to match the command you usually use to start the script.
The text that the script will output will be sent in real time to the user, and all user input will be sent to the script (as long as it's running or until the user kills it with /cancel). The text that the script will output will be sent in real time to the user, and all user input will be sent to the script (as long as it's running or until the user kills it with /cancel).
To open up a keyboard in an interactive script, print out the keyboard layout in the following way: To open up a keyboard in an interactive script, print out the keyboard layout in the following way:
@ -178,6 +179,20 @@ echo "Text that will appear in chat? mykeyboardstartshere \"Yep, sure\" \"No, hi
``` ```
Please note that you can either send a location or a venue, not both. To send a venue add the mytitlestartshere and the myaddressstartshere keywords. Please note that you can either send a location or a venue, not both. To send a venue add the mytitlestartshere and the myaddressstartshere keywords.
A background job is similar to an interactive chat, but runs in the background and does only output massages instead of processing input from the user. In contrast to interactive chats it's possible to run multiple background jobs. To create a background job write a script or edit the notify script and use the funtion background to start it:
```
background "./notify" "jobname"
```
All output of the script will be sent to the user or chat. To stop a background job use:
```
killback "jobname"
```
You can restart the last running background jobs, e.g. after a reboot, with the command:
```
./bashbot.sh background
```
#### Inline queries
The following commands allows users to interact with your bot via *inline queries*. The following commands allows users to interact with your bot via *inline queries*.
In order to enable **inline mode**, send `/setinline` command to [@BotFather](https://telegram.me/botfather) and provide the placeholder text that the user will see in the input field after typing your bots name. In order to enable **inline mode**, send `/setinline` command to [@BotFather](https://telegram.me/botfather) and provide the placeholder text that the user will see in the input field after typing your bots name.
Also, edit line 12 from `commands.sh` putting a "1". Also, edit line 12 from `commands.sh` putting a "1".

View File

@ -10,6 +10,8 @@
# This file is public domain in the USA and all free countries. # This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying) # Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
TMPDIR="./tmp-bot-bash"
if [ ! -f "JSON.sh/JSON.sh" ]; then if [ ! -f "JSON.sh/JSON.sh" ]; then
echo "You did not clone recursively! Downloading JSON.sh..." echo "You did not clone recursively! Downloading JSON.sh..."
git clone http://github.com/dominictarr/JSON.sh git clone http://github.com/dominictarr/JSON.sh
@ -24,6 +26,10 @@ if [ ! -f "token" ]; then
echo "$token" >> token echo "$token" >> token
fi fi
if [ ! -d "$TMPDIR" ]; then
mkdir "$TMPDIR"
fi
source commands.sh source source commands.sh source
URL='https://api.telegram.org/bot'$TOKEN URL='https://api.telegram.org/bot'$TOKEN
@ -45,6 +51,7 @@ ACTION_URL=$URL'/sendChatAction'
FORWARD_URL=$URL'/forwardMessage' FORWARD_URL=$URL'/forwardMessage'
INLINE_QUERY=$URL'/answerInlineQuery' INLINE_QUERY=$URL'/answerInlineQuery'
ME_URL=$URL'/getMe' ME_URL=$URL'/getMe'
DELETE_URL=$URL'/deleteMessage'
ME=$(curl -s $ME_URL | ./JSON.sh/JSON.sh -s | egrep '\["result","username"\]' | cut -f 2 | cut -d '"' -f 2) ME=$(curl -s $ME_URL | ./JSON.sh/JSON.sh -s | egrep '\["result","username"\]' | cut -f 2 | cut -d '"' -f 2)
@ -81,7 +88,7 @@ send_message() {
} }
if [ "$no_keyboard" != "" ]; then if [ "$no_keyboard" != "" ]; then
echo "remove_keyboard $chat $text" > /tmp/prova echo "remove_keyboard $chat $text" > $TMPDIR/prova
remove_keyboard "$chat" "$text" remove_keyboard "$chat" "$text"
local sent=y local sent=y
fi fi
@ -321,15 +328,37 @@ forward() {
res=$(curl -s "$FORWARD_URL" -F "chat_id=$1" -F "from_chat_id=$2" -F "message_id=$3") res=$(curl -s "$FORWARD_URL" -F "chat_id=$1" -F "from_chat_id=$2" -F "message_id=$3")
} }
background() {
echo "${CHAT[ID]}:$2:$1" >"$TMPDIR/${copname}$2-back.cmd"
startproc "$1" "back-$2-"
}
startproc() { startproc() {
killproc killproc "$2"
mkfifo /tmp/$copname local fifo="$2${copname}" # add $1 to copname, so we can have more than one running script per chat
TMUX= tmux new-session -d -s $copname "$* &>/tmp/$copname; echo imprettydarnsuredatdisisdaendofdacmd>/tmp/$copname" mkfifo "$TMPDIR/${fifo}"
TMUX= tmux new-session -d -s sendprocess_$copname "bash $SCRIPT outproc ${CHAT[ID]} $copname" TMUX= tmux new-session -d -s "${fifo}" "$1 &>$TMPDIR/${fifo}; echo imprettydarnsuredatdisisdaendofdacmd>$TMPDIR/${fifo}"
TMUX= tmux new-session -d -s sendprocess_${fifo} "bash $SCRIPT outproc ${CHAT[ID]} ${fifo}"
}
checkback() {
checkproc "back-$1-"
}
checkproc() {
tmux ls | grep -q "$1${copname}"; res=$?
}
killback() {
killproc "back-$1-"
rm "$TMPDIR/${copname}$1-back.cmd"
} }
killproc() { killproc() {
(tmux kill-session -t $copname; echo imprettydarnsuredatdisisdaendofdacmd>/tmp/$copname; tmux kill-session -t sendprocess_$copname; rm -r /tmp/$copname)2>/dev/null local fifo="$1${copname}"
(tmux kill-session -t "${fifo}"; echo imprettydarnsuredatdisisdaendofdacmd>$TMPDIR/${fifo}; tmux kill-session -t sendprocess_${fifo}; rm -r $TMPDIR/${fifo})2>/dev/null
} }
inproc() { inproc() {
@ -429,8 +458,8 @@ case "$1" in
line= line=
read -t 10 line read -t 10 line
[ "$line" != "" -a "$line" != "imprettydarnsuredatdisisdaendofdacmd" ] && send_message "$2" "$line" [ "$line" != "" -a "$line" != "imprettydarnsuredatdisisdaendofdacmd" ] && send_message "$2" "$line"
done </tmp/$3 done <$TMPDIR/$3
rm -r /tmp/$3 rm -r $TMPDIR/$3
;; ;;
"count") "count")
echo "A total of $(wc -l count | sed 's/count//g')users used me." echo "A total of $(wc -l count | sed 's/count//g')users used me."
@ -448,12 +477,49 @@ case "$1" in
echo "Tmux session name $ME" || echo -e '\e[0;31mAn error occurred while starting the bot. \e[0m' echo "Tmux session name $ME" || echo -e '\e[0;31mAn error occurred while starting the bot. \e[0m'
send_markdown_message "${CHAT[ID]}" "*Bot started*" send_markdown_message "${CHAT[ID]}" "*Bot started*"
;; ;;
"background")
clear
echo -e '\e[0;32mRestart background processes ...\e[0m'
for FILE in ${TMPDIR}/*-back.cmd; do
if [ "$FILE" == "${TMPDIR}/*-back.cmd" ]; then
echo -e '\e[0;31mNo background processes to start.\e[0m'; break
else
RESTART="$(cat "$FILE")"
CHAT[ID]="${RESTART%%:*}"
JOB="${RESTART#*:}"
PROG="${JOB#*:}"
JOB="${JOB%:*}"
fifo="back-${JOB}-${ME}_${CHAT[ID]}" # compose fifo from jobname, $ME (botname) and CHAT[ID]
echo "restartbackground ${PROG} ${fifo}"
( tmux kill-session -t "${fifo}"; tmux kill-session -t sendprocess_${fifo}; rm -r $TMPDIR/${fifo}) 2>/dev/null
mkfifo "$TMPDIR/${fifo}"
TMUX= tmux new-session -d -s "${fifo}" "${PROG} &>$TMPDIR/${fifo}; echo imprettydarnsuredatdisisdaendofdacmd>$TMPDIR/${fifo}"
TMUX= tmux new-session -d -s sendprocess_${fifo} "bash $SCRIPT outproc ${CHAT[ID]} ${fifo}"
fi
done
;;
"kill") "kill")
clear clear
tmux kill-session -t $ME &>/dev/null tmux kill-session -t $ME &>/dev/null
send_markdown_message "${CHAT[ID]}" "*Bot stopped*" send_markdown_message "${CHAT[ID]}" "*Bot stopped*"
echo -e '\e[0;32mOK. Bot stopped successfully.\e[0m' echo -e '\e[0;32mOK. Bot stopped successfully.\e[0m'
;; ;;
"killback")
clear
echo -e "\e[0;32mRemove background processes ...\e[0m"
for FILE in ${TMPDIR}/*-back.cmd; do
if [ "$FILE" == "${TMPDIR}/*-back.cmd" ]; then
echo -e "\e[0;31mNo background processes.\e[0m"; break
else
REMOVE="$(cat "$FILE")"
JOB="${REMOVE#*:}"
fifo="back-${JOB%:*}-${ME}_${REMOVE%%:*}"
echo "killbackground ${fifo}"
rm $FILE
( tmux kill-session -t "${fifo}"; tmux kill-session -t sendprocess_${fifo}; rm -r $TMPDIR/${fifo}) 2>/dev/null
fi
done
;;
"help") "help")
clear clear
less README.md less README.md
@ -466,7 +532,7 @@ case "$1" in
;; ;;
*) *)
echo -e '\e[0;31mBAD REQUEST\e[0m' echo -e '\e[0;31mBAD REQUEST\e[0m'
echo -e '\e[0;31mAvailable arguments: outproc, count, broadcast, start, kill, help, attach\e[0m' echo -e '\e[0;31mAvailable arguments: outproc, count, broadcast, start, background, kill, killback, help, attach\e[0m'
;; ;;
esac esac

View File

@ -49,8 +49,32 @@ else
fi fi
case "$MESSAGE" in case "$MESSAGE" in
'/question') '/question')
startproc "./question" checkproc
if [ $res -gt 0 ] ; then
startproc "./question"
else
send_normal_message "${CHAT[ID]}" "$MESSAGE already running ..."
fi
;; ;;
'/run-notify')
myback="notify"; checkback "$myback"
if [ $res -gt 0 ] ; then
background "./notify 60" "$myback" # notify every 60 seconds
else
send_normal_message "${CHAT[ID]}" "Background command $myback already running ..."
fi
;;
'/stop-notify')
myback="notify"; checkback "$myback"
if [ $res -eq 0 ] ; then
killback "$myback"
send_normal_message "${CHAT[ID]}" "Background command $myback canceled."
else
send_normal_message "${CHAT[ID]}" "No background command $myback is currently running.."
fi
;;
'/info') '/info')
send_markdown_message "${CHAT[ID]}" "This is bashbot, the *Telegram* bot written entirely in *bash*." send_markdown_message "${CHAT[ID]}" "This is bashbot, the *Telegram* bot written entirely in *bash*."
;; ;;
@ -82,7 +106,8 @@ Get the code in my [GitHub](http://github.com/topkecleon/telegram-bot-bash)
;; ;;
'/cancel') '/cancel')
if tmux ls | grep -q $copname; then killproc && send_message "${CHAT[ID]}" "Command canceled.";else send_message "${CHAT[ID]}" "No command is currently running.";fi checkprog
if [ $res -eq 0 ] ; then killproc && send_message "${CHAT[ID]}" "Command canceled.";else send_message "${CHAT[ID]}" "No command is currently running.";fi
;; ;;
*) *)
if tmux ls | grep -v send | grep -q $copname;then inproc; else send_message "${CHAT[ID]}" "$MESSAGE" "safe";fi if tmux ls | grep -v send | grep -q $copname;then inproc; else send_message "${CHAT[ID]}" "$MESSAGE" "safe";fi

19
notify Executable file
View File

@ -0,0 +1,19 @@
#!/bin/bash
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
# check if $1 is a number
re='^[0-9]+$'
if [[ $1 =~ $re ]] ; then
SLEEP="$1"
else
SLEEP=10 # time between time notifications
fi
# output current time every $1 seconds
while sleep $SLEEP
do
date "+* It's %k:%M:%S o' clock ..."
done