Merge pull request #78 from topkecleon/develop

Sync 0.60 dev branch with master
This commit is contained in:
Kay Marquardt 2019-04-18 10:37:44 +02:00 committed by GitHub
commit 8028d2b0eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 843 additions and 321 deletions

108
README.md
View File

@ -1,78 +1,102 @@
# bashbot
A Telegram bot written in bash.
Depends on [tmux](http://github.com/tmux/tmux).
Uses [JSON.sh](http://github.com/dominictarr/JSON.sh).
Written by Drew (@topkecleon), Daniil Gentili (@danogentili), and Kay M (@gnadelwartz).
Contributions by JuanPotato, BigNerd95, TiagoDanin, and iicc1.
[Download latest release from github](https://github.com/topkecleon/telegram-bot-bash/releases)
Released to the public domain wherever applicable.
Elsewhere, consider it released under the [WTFPLv2](http://www.wtfpl.net/txt/copying/).
## Prerequisites
Depends on [tmux](http://github.com/tmux/tmux).
Uses [JSON.sh](http://github.com/dominictarr/JSON.sh).
Most complete [UTF-8 support for bashbot](doc/4_expert.md#Bashbot-UTF-8-Support) is availible if phyton is installed (optional).
Bashbot [Documentation](https://github.com/topkecleon/telegram-bot-bash) and [Downloads](https://github.com/topkecleon/telegram-bot-bash/releases) are availible on www.github.com
## Install bashbot
1. Go to the directory you want to install bashbot, e.g.
- your $HOME directory (install and run with your user-ID)
- /usr/local if you want to run as service
* your $HOME directory (install and run with your user-ID)
* /usr/local if you want to run as service
2. Clone the repository:
```
git clone --recursive https://github.com/topkecleon/telegram-bot-bash
```
3. Change to directory ```telegram-bot.bash```, run ```./bashbot.sh init``` and follow the instructions. At this stage you are asked for your Bots token given by botfather.
```
git clone --recursive https://github.com/topkecleon/telegram-bot-bash
```
3. Change to directory ```telegram-bot-bash```, run ```./bashbot.sh init``` and follow the instructions. At this stage you are asked for your Bots token given by botfather.
## Update bashbot
[Download latest update zip from github](https://github.com/topkecleon/telegram-bot-bash/releases) and copy all files to bashbot dir. run ```sudo ./bashbot.sh init```.
1. [Download latest update zip from github](https://github.com/topkecleon/telegram-bot-bash/releases)
2. Extract all files and copy them to your bashbot dir
3. Run ```sudo ./bashbot.sh init``` to setup your environment after the update
## Getting started
- [Create your first telegram bot](doc/1_firstbot.md)
- [Make your own Bot](doc/2_usage.md)
- Managing your own Bot
- Recieve data
- Send Messages
- Send files, location etc.
- [Advanced Features](doc/3_advanced.md)
- Access Control
- Interactive Chats
- Background Jobs
- Inline queries
- [Expert Use](doc/4_expert.md)
- Handling UTF-8
- Run as other user or system service
- Scedule bashbot from Cron
- [Best Practices](doc/5_practice.md)
- Customizing commands.sh
- Seperate Bot logic from command
- Test your Bot with shellcheck
## Documentation
* [Create a new Telegram Bot with botfather](doc/1_firstbot.md)
* [Getting Started](doc/2_usage.md)
* Managing your Bot
* Recieve data
* Send messages
* Send files, locations, keyboards
* [Advanced Features](doc/3_advanced.md)
* Access Control
* Interactive Chats
* Background Jobs
* Inline queries
* [Expert Use](doc/4_expert.md)
* Handling UTF-8 character sets
* Run as other user or system service
* Scedule bashbot from Cron
* [Best Practices](doc/5_practice.md)
* Customize commands.sh
* Seperate logic from commands
* Test your Bot with shellcheck
* [Bashbot function reference](doc/6_reference.md)
## Note on Keyboards
From Version 0.60 on keybord format for ```send_keyboard``` and ```send_message "mykeyboardstartshere ..."``` was changed.
Keybords are now defined in JSON Array notation e.g. "[ \\"yes\\" , \\"no\\" ]".
This has the advantage that you can create any type of keyboard supported by Telegram.
The old format is supported for backward compatibility, but may fail for corner cases.
*Example Keyboards*:
- yes no in two rows:
- OLD format: 'yes' 'no' (two strings)
- NEW format: '[ "yes" ] , [ "no" ]' (two arrays with a string)
- new layouts made easy with NEW format:
- Yes No in one row: '[ "yes" , "no" ]'
- Yes No plus Maybe in 2.row: '[ "yes" , "no" ] , [ "maybe" ]'
- numpad style keyboard: '[ "1" , "2" , "3" ] , [ "4" , "5" , "6" ] , [ "7" , "8" , "9" ] , [ "0" ]'
## Security Considerations
Running a Telegram Bot means you are conneted to the public, you never know whats send to your Bot.
Running a Telegram Bot means it is connected to the public and you never know whats send to your Bot.
Bash scripts in general are not designed to be bullet proof, so consider this Bot as a proof of concept. More concret examples of security problems is bash's 'quoting hell' and globbing. [Implications of wrong quoting](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells)
Bash scripts in general are not designed to be bullet proof, so consider this Bot as a proof of concept. More concret examples of security problems are: bash's 'quoting hell' and globbing. [Implications of wrong quoting](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells)
Whenever you are processing input from outside your bot you should disable globbing (set -f) and carefully quote everthing.
Whenever you are processing input from from untrusted sources (messages, files, network) you must be as carefull as possible, e.g. set IFS appropriate, disable globbing (set -f) and quote everthing. In addition disable not used Bot commands and delete unused scripts from your Bot, e.g. example scripts 'notify', 'calc', 'question',
To improve you scripts we recommend to lint them with [shellcheck](https://www.shellcheck.net/). This can be done online or you can [install shellcheck locally](https://github.com/koalaman/shellcheck#installing). bashbot itself is also linted by shellcheck.
A powerful tool to improve your scripts robustness is ```shellcheck```. You can [use it online](https://www.shellcheck.net/) or [install shellcheck locally](https://github.com/koalaman/shellcheck#installing). All bashbot scripts are checked by shellcheck.
### Run your Bot as a restricted user
Every file your bot can write is in danger to be overwritten/deleted, In case of bad handling of user input every file your Bot can read is in danger of being disclosed.
**I recommend to run your bot as a user, with almost no access rights.**
All files your Bot have write access to are in danger to be overwritten/deleted if your bot is hacked.
For the same reason ervery file your Bot can read is in danger to be disclosed. Restict your Bots access rigths to the absolute minimum.
Never run your Bot as root, this is the most dangerous you can do! Usually the user 'nobody' has almost no rigths on Unix/Linux systems. See Expert use on how to run your Bot as an other user.
**Never run your Bot as root, this is the most dangerous you can do!** Usually the user 'nobody' has almost no rights on Unix/Linux systems. See [Expert use](doc/4_expert.md) on how to run your Bot as an other user.
### Secure your Bot installation
Everyone who can read your Bot files can extract your Bots data. Especially your Bot Token in ```token``` must be protected against other users. No one exept you should have write access to the Bot files. The Bot itself need write access to ```count``` and ```tmp-bot-bash``` only, all other files should be write protected.
**Your Bot configuration must no be readable from other users.** Everyone who can read your Bots token can act as your Bot and has access to all chats your Bot is in!
Runing ```./bashbot.sh init``` sets the Bot permissions to reasonable default values as a starting point.
Everyone with read access to your Bot files can extract your Bots data. Especially your Bot Token in ```token``` must be protected against other users. No one exept you must have write access to the Bot files. The Bot must be restricted to have write access to ```count``` and ```tmp-bot-bash``` only, all other files must be write protected.
To set access rights for your bashbot installation to a reasonable default run ```sudo ./bashbot.sh init``` after every update or change to your installation directory.
### Is this Bot insecure?
No - its not less (in)secure as any other Bot written in any other language. But you should know about the implications ...
Bashbot is not more (in)secure as any other Bot written in any other language, we have done our best to make it as secure as possible. But YOU are responsible for the bot commands you wrote and you should know about the risks ...
## That's it!
If you feel that there's something missing or if you found a bug, feel free to submit a pull request!
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2

View File

@ -3,115 +3,157 @@ bashbot
A Telegram bot written in bash.
Depends on http://github.com/tmux/tmux[tmux]. Uses
http://github.com/dominictarr/JSON.sh[JSON.sh].
Written by Drew (@topkecleon), Daniil Gentili (@danogentili), and Kay M
(@gnadelwartz).
Contributions by JuanPotato, BigNerd95, TiagoDanin, and iicc1.
https://github.com/topkecleon/telegram-bot-bash/releases[Download latest
release from github]
Released to the public domain wherever applicable. Elsewhere, consider
it released under the http://www.wtfpl.net/txt/copying/[WTFPLv2].
Prerequisites
~~~~~~~~~~~~~
Depends on http://github.com/tmux/tmux[tmux]. Uses
http://github.com/dominictarr/JSON.sh[JSON.sh].
For full UTF-8 support you need
link:doc/4_expert.md#UTF-8-Support[python on your system] (optional).
Bashbot https://github.com/topkecleon/telegram-bot-bash[Documentation]
and https://github.com/topkecleon/telegram-bot-bash/releases[Downloads]
are availible on www.github.com
Install bashbot
~~~~~~~~~~~~~~~
1. Go to the directory you want to install bashbot, e.g.
* your $HOME directory (install and run with your user-ID)
* /usr/local if you want to run as service
1. Clone the repository:
2. Clone the repository:
+
....
git clone --recursive https://github.com/topkecleon/telegram-bot-bash
....
2. Change to directory `telegram-bot.bash`, run `./bashbot.sh init` and
3. Change to directory `telegram-bot-bash`, run `./bashbot.sh init` and
follow the instructions. At this stage you are asked for your Bots token
given by botfather.
Update bashbot
~~~~~~~~~~~~~~
https://github.com/topkecleon/telegram-bot-bash/releases[Download latest
update zip from github] and copy all files to bashbot dir. run
`sudo ./bashbot.sh init`.
1. https://github.com/topkecleon/telegram-bot-bash/releases[Download
latest update zip from github]
2. Extract all files and copy them to your bashbot dir
3. Run `sudo ./bashbot.sh init` to setup your environment after the
update
Getting started
~~~~~~~~~~~~~~~
Documentation
~~~~~~~~~~~~~
* link:doc/1_firstbot.md[Create your first telegram bot]
* link:doc/2_usage.md[Make your own Bot]
* Managing your own Bot
* Recieve data
* Send Messages
* Send files, location etc.
* link:doc/1_firstbot.md[Create a new Telegram Bot with botfather]
* link:doc/2_usage.md[Getting Started]
** Managing your Bot
** Recieve data
** Send messages
** Send files, locations, keyboards
* link:doc/3_advanced.md[Advanced Features]
* Access Control
* Interactive Chats
* Background Jobs
* Inline queries
** Access Control
** Interactive Chats
** Background Jobs
** Inline queries
* link:doc/4_expert.md[Expert Use]
* Handling UTF-8
* Run as other user or system service
* Scedule bashbot from Cron
** Handling UTF-8 character sets
** Run as other user or system service
** Scedule bashbot from Cron
* link:doc/5_practice.md[Best Practices]
* Customizing commands.sh
* Seperate Bot logic from command
* Test your Bot with shellcheck
** Customize commands.sh
** Seperate logic from commands
** Test your Bot with shellcheck
* link:doc/6_reference.md[Bashbot function reference]
Note on Keyboards
~~~~~~~~~~~~~~~~~
From Version 0.60 on keybord format for `send_keyboard` and
`send_message "mykeyboardstartshere ..."` was changed. Keybords are now
defined in JSON Array notation e.g. "[ \"yes\" , \"no\" ]". This has the
advantage that you can create any type of keyboard supported by
Telegram. The old format is supported for backward compatibility, but
may fail for corner cases.
_Example Keyboards_:
* yes no in two rows:
** OLD format: 'yes' 'no' (two strings)
** NEW format: '[ "yes" ] , [ "no" ]' (two arrays with a string)
* new layouts made easy with NEW format:
** Yes No in one row: '[ "yes" , "no" ]'
** Yes No plus Maybe in 2.row: '[ "yes" , "no" ] , [ "maybe" ]'
** numpad style keyboard: '[ "1" , "2" , "3" ] , [ "4" , "5" , "6" ] , [
"7" , "8" , "9" ] , [ "0" ]'
Security Considerations
~~~~~~~~~~~~~~~~~~~~~~~
Running a Telegram Bot means you are conneted to the public, you never
Running a Telegram Bot means it is connected to the public and you never
know whats send to your Bot.
Bash scripts in general are not designed to be bullet proof, so consider
this Bot as a proof of concept. More concret examples of security
problems is bash's 'quoting hell' and globbing.
problems are: bash's 'quoting hell' and globbing.
https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells[Implications
of wrong quoting]
Whenever you are processing input from outside your bot you should
disable globbing (set -f) and carefully quote everthing.
Whenever you are processing input from from untrusted sources (messages,
files, network) you must be as carefull as possible, e.g. set IFS
appropriate, disable globbing (set -f) and quote everthing. In addition
disable not used Bot commands and delete unused scripts from your Bot,
e.g. example scripts 'notify', 'calc', 'question',
To improve you scripts we recommend to lint them with
https://www.shellcheck.net/[shellcheck]. This can be done online or you
can https://github.com/koalaman/shellcheck#installing[install shellcheck
locally]. bashbot itself is also linted by shellcheck.
A powerful tool to improve your scripts robustness is `shellcheck`. You
can https://www.shellcheck.net/[use it online] or
https://github.com/koalaman/shellcheck#installing[install shellcheck
locally]. All bashbot scripts are checked by shellcheck.
Run your Bot as a restricted user
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Every file your bot can write is in danger to be overwritten/deleted, In
case of bad handling of user input every file your Bot can read is in
danger of being disclosed.
*I recommend to run your bot as a user, with almost no access rights.*
All files your Bot have write access to are in danger to be
overwritten/deleted if your bot is hacked. For the same reason ervery
file your Bot can read is in danger to be disclosed. Restict your Bots
access rigths to the absolute minimum.
Never run your Bot as root, this is the most dangerous you can do!
Usually the user 'nobody' has almost no rigths on Unix/Linux systems.
See Expert use on how to run your Bot as an other user.
*Never run your Bot as root, this is the most dangerous you can do!*
Usually the user 'nobody' has almost no rights on Unix/Linux systems.
See link:doc/4_expert.md[Expert use] on how to run your Bot as an other
user.
Secure your Bot installation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Everyone who can read your Bot files can extract your Bots data.
Especially your Bot Token in `token` must be protected against other
users. No one exept you should have write access to the Bot files. The
Bot itself need write access to `count` and `tmp-bot-bash` only, all
other files should be write protected.
*Your Bot configuration must no be readable from other users.* Everyone
who can read your Bots token can act as your Bot and has access to all
chats your Bot is in!
Runing `./bashbot.sh init` sets the Bot permissions to reasonable
default values as a starting point.
Everyone with read access to your Bot files can extract your Bots data.
Especially your Bot Token in `token` must be protected against other
users. No one exept you must have write access to the Bot files. The Bot
must be restricted to have write access to `count` and `tmp-bot-bash`
only, all other files must be write protected.
To set access rights for your bashbot installation to a reasonable
default run `sudo ./bashbot.sh init` after every update or change to
your installation directory.
Is this Bot insecure?
^^^^^^^^^^^^^^^^^^^^^
No - its not less (in)secure as any other Bot written in any other
language. But you should know about the implications ...
Bashbot is not more (in)secure as any other Bot written in any other
language, we have done our best to make it as secure as possible. But
YOU are responsible for the bot commands you wrote and you should know
about the risks ...
That's it!
~~~~~~~~~~
@ -119,5 +161,5 @@ That's it!
If you feel that there's something missing or if you found a bug, feel
free to submit a pull request!
latexmath:[\[VERSION\]] v0.52-0-gdb7b19f
latexmath:[\[VERSION\]] v0.60-0-gf5162e2
++++++++++++++++++++++++++++++++++++++++

View File

@ -7,7 +7,7 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
SHELL=/bin/sh

View File

@ -1,7 +1,7 @@
#!/bin/sh
# description: Start or stop telegram-bash-bot
#
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
# shellcheck disable=SC2009
# shellcheck disable=SC2181

View File

@ -10,14 +10,15 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
#
# Exit Codes:
# - 0 sucess (hopefully)
# - 1 can't change to dir
# - 2 can't write to tmp, count or token
# - 3 user not found
# - 3 user / command not found
# - 4 unkown command
# - 5 cannot connect to telegram bot
# are we runnig in a terminal?
if [ -t 1 ] && [ "$TERM" != "" ]; then
@ -43,31 +44,31 @@ if [ ! -w "." ]; then
ls -ld .
fi
TOKEN="./token"
if [ ! -f "${TOKEN}" ]; then
if [ "${CLEAR}" = "" ]; then
echo "Running headless, run ${SCRIPT} init first!"
exit 2
else
${CLEAR}
echo -e "${RED}TOKEN MISSING.${NC}"
echo -e "${ORANGE}PLEASE WRITE YOUR TOKEN HERE OR PRESS CTRL+C TO ABORT${NC}"
read -r token
echo "${token}" > "${TOKEN}"
fi
fi
if [ ! -f "JSON.sh/JSON.sh" ]; then
echo "You did not clone recursively! Downloading JSON.sh..."
git clone http://github.com/dominictarr/JSON.sh
echo "JSON.sh has been downloaded. Proceeding."
fi
TOKEN="./token"
if [ ! -f "${TOKEN}" ]; then
if [ "${CLEAR}" == "" ]; then
echo "Running headless, run ${SCRIPT} init first!"
exit 2
else
${CLEAR}
echo -e "${RED}TOKEN MISSING.${NC}"
echo -e "${ORANGE}PLEASE WRITE YOUR TOKEN HERE${NC}"
read -r token
echo "${token}" > "${TOKEN}"
fi
fi
BOTADMIN="./botadmin"
if [ ! -f "${BOTADMIN}" ]; then
if [ "${CLEAR}" == "" ]; then
if [ "${CLEAR}" = "" ]; then
echo "Running headless, set botadmin to AUTO MODE!"
echo "?" > "${BOTADMIN}"
echo '?' > "${BOTADMIN}"
else
${CLEAR}
echo -e "${RED}BOTADMIN MISSING.${NC}"
@ -104,8 +105,17 @@ elif [ ! -w "${COUNT}" ]; then
exit 2
fi
COMMANDS="./commands.sh"
if [ ! -f "${COMMANDS}" ] || [ ! -r "${COMMANDS}" ]; then
${CLEAR}
echo -e "${RED}ERROR: ${COMMANDS} does not exist or is not readable!.${NC}"
exit 3
ls -l "${COMMANDS}"
fi
# shellcheck source=./commands.sh
source "${COMMANDS}" "source"
source "commands.sh" "source"
URL='https://api.telegram.org/bot'$TOKEN
@ -127,7 +137,6 @@ INLINE_QUERY=$URL'/answerInlineQuery'
ME_URL=$URL'/getMe'
DELETE_URL=$URL'/deleteMessage'
GETMEMBER_URL=$URL'/getChatMember'
ME="$(curl -s "$ME_URL" | ./JSON.sh/JSON.sh -s | grep '\["result","username"\]' | cut -f 2 | cut -d '"' -f 2)"
FILE_URL='https://api.telegram.org/file/bot'$TOKEN'/'
@ -136,9 +145,6 @@ GET_URL=$URL'/getFile'
OFFSET=0
declare -A USER MESSAGE URLS CONTACT LOCATION CHAT FORWARD REPLYTO
urlencode() {
echo "$*" | sed 's:%:%25:g;s: :%20:g;s:<:%3C:g;s:>:%3E:g;s:#:%23:g;s:{:%7B:g;s:}:%7D:g;s:|:%7C:g;s:\\:%5C:g;s:\^:%5E:g;s:~:%7E:g;s:\[:%5B:g;s:\]:%5D:g;s:`:%60:g;s:;:%3B:g;s:/:%2F:g;s:?:%3F:g;s^:^%3A^g;s:@:%40:g;s:=:%3D:g;s:&:%26:g;s:\$:%24:g;s:\!:%21:g;s:\*:%2A:g'
}
send_message() {
@ -148,7 +154,6 @@ send_message() {
text="$(echo "$2" | sed 's/ mykeyboardstartshere.*//g;s/ myfilelocationstartshere.*//g;s/ mylatstartshere.*//g;s/ mylongstartshere.*//g;s/ mytitlestartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
arg="$3"
[ "$arg" != "safe" ] && {
#text="$(echo "$text" | sed 's/ mynewlinestartshere /\r\n/g')" # hack for linebreaks in startproc scripts
text="${text// mynewlinestartshere /$'\r\n'}"
no_keyboard="$(echo "$2" | sed '/mykeyboardendshere/!d;s/.*mykeyboardendshere.*/mykeyboardendshere/')"
@ -171,6 +176,9 @@ send_message() {
sent=y
fi
if [ "$keyboard" != "" ]; then
if [[ "$keyboard" != *"["* ]]; then # pre 0.60 style
keyboard="[ ${keyboard//\" \"/\" \] , \[ \"} ]"
fi
send_keyboard "$chat" "$text" "$keyboard"
sent=y
fi
@ -252,27 +260,27 @@ leave_chat() {
}
user_is_creator() {
if [ "${1:--}" == "${2:-+}" ] || [ "$(get_chat_member_status "$1" "$2")" == "creator" ]; then return 0; fi
if [ "${1:--}" = "${2:-+}" ] || [ "$(get_chat_member_status "$1" "$2")" = "creator" ]; then return 0; fi
return 1
}
user_is_admin() {
local me; me="$(get_chat_member_status "$1" "$2")"
if [ "${me}" == "creator" ] || [ "${me}" == "administrator" ]; then return 0; fi
if [ "${me}" = "creator" ] || [ "${me}" = "administrator" ]; then return 0; fi
return 1
}
user_is_botadmin() {
local admin; admin="$(head -n 1 "${BOTADMIN}")"
[ "${admin}" == "${1}" ] && return 0
[[ "${admin}" == "@*" ]] && [[ "${admin}" == "${2}" ]] && return 0
if [ "${admin}" == "?" ]; then echo "${1:-?}" >"${BOTADMIN}"; return 0; fi
[ "${admin}" = "${1}" ] && return 0
[[ "${admin}" = "@*" ]] && [[ "${admin}" = "${2}" ]] && return 0
if [ "${admin}" = "?" ]; then echo "${1:-?}" >"${BOTADMIN}"; return 0; fi
return 1
}
user_is_allowed() {
local acl; acl="$1"
[ "$1" == "" ] && return 1
local acl="$1"
[ "$1" = "" ] && return 1
grep -F -xq "${acl}:*:*" <"${BOTACL}" && return 0
[ "$2" != "" ] && acl="${acl}:$2"
grep -F -xq "${acl}:*" <"${BOTACL}" && return 0
@ -349,7 +357,8 @@ answer_inline_query() {
}
send_keyboard() {
old_send_keyboard() {
local chat="$1"
local text="$2"
shift 2
@ -362,6 +371,14 @@ send_keyboard() {
res="$(curl -s "$MSG_URL" --header "content-type: multipart/form-data" -F "chat_id=$chat" -F "text=$text" -F "reply_markup={\"keyboard\": [$keyboard],\"one_time_keyboard\": true}")"
}
send_keyboard() {
if [[ "$3" != *'['* ]]; then old_send_keyboard "$@"; return; fi
local chat="$1"
local text="$2"
local keyboard="$3"
res="$(curl -s "$MSG_URL" --header "content-type: multipart/form-data" -F "chat_id=$chat" -F "text=$text" -F "reply_markup={\"keyboard\": [${keyboard}],\"one_time_keyboard\": true}")"
}
remove_keyboard() {
local chat="$1"
local text="$2"
@ -370,7 +387,7 @@ remove_keyboard() {
}
get_file() {
[ "$1" != "" ] && echo "$FILE_URL$(curl -s "$GET_URL" -F "file_id=$1" | ./JSON.sh/JSON.sh -s | grep '\["result","file_path"\]' | cut -f 2 | cut -d '"' -f 2)"
[ "$1" != "" ] && echo "$FILE_URL$(curl -s "$GET_URL" -F "file_id=$1" | ./JSON.sh/JSON.sh -s | JsonGetString '"result","file_path"')"
}
send_file() {
@ -440,11 +457,13 @@ send_venue() {
}
forward() {
forward_message() {
[ "$3" = "" ] && return
res="$(curl -s "$FORWARD_URL" -F "chat_id=$1" -F "from_chat_id=$2" -F "message_id=$3")"
}
forward() { # backward compatibility
forward_message "$@" || return
}
background() {
echo "${CHAT[ID]}:$2:$1" >"${TMPDIR:-.}/${copname}$2-back.cmd"
@ -453,7 +472,7 @@ background() {
startproc() {
killproc "$2"
local fifo="$2${copname}" # add $1 to copname, so we can have more than one running script per chat
local fifo="$2${copname}"
mkfifo "${TMPDIR:-.}/${fifo}"
tmux new-session -d -s "${fifo}" "$1 &>${TMPDIR:-.}/${fifo}; echo imprettydarnsuredatdisisdaendofdacmd>${TMPDIR:-.}/${fifo}"
tmux new-session -d -s "sendprocess_${fifo}" "bash $SCRIPT outproc ${CHAT[ID]} ${fifo}"
@ -465,7 +484,7 @@ checkback() {
}
checkproc() {
tmux ls | grep -q "$1${copname}"; res=$?
tmux ls | grep -q "$1${copname}"; res=$?; return $?
}
killback() {
@ -485,79 +504,85 @@ inproc() {
process_updates() {
MAX_PROCESS_NUMBER=$(echo "$UPDATE" | sed '/\["result",[0-9]*\]/!d' | tail -1 | sed 's/\["result",//g;s/\].*//g')
for ((PROCESS_NUMBER=0; PROCESS_NUMBER<=MAX_PROCESS_NUMBER; PROCESS_NUMBER++)); do
if [ "$1" == "test" ]; then
if [ "$1" = "test" ]; then
process_client "$1"
else
process_client "$1" &
fi
done
}
JsonGetString() {
sed -n -e '/\['"$1"'\]/ s/.*\][ \t]"\(.*\)"$/\1/p'
}
JsonGetValue() {
sed -n -e '/\['"$1"'\]/ s/.*\][ \t]//p'
}
process_client() {
local TMP="${TMPDIR:-.}/$RANDOM$RANDOM-MESSAGE"
echo "$UPDATE" >"$TMP"
# Message
MESSAGE[0]="$(echo -e "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","text"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")" | sed 's#\\/#/#g')"
MESSAGE[ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","message_id"\]/ s/.*\][ \t]//p' <"$TMP" )"
MESSAGE[0]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","text"' <"$TMP")" | sed 's#\\/#/#g')"
MESSAGE[ID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","message_id"' <"$TMP" )"
# Chat
CHAT[ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","id"\]/ s/.*\][ \t]//p' <"$TMP" )"
CHAT[FIRST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","first_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[LAST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","last_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[USERNAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","username"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[TITLE]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","title"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[TYPE]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","type"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[ALL_MEMBERS_ARE_ADMINISTRATORS]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","chat","all_members_are_administrators"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CHAT[ID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","chat","id"' <"$TMP" )"
CHAT[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","first_name"' <"$TMP")")"
CHAT[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","last_name"' <"$TMP")")"
CHAT[USERNAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","username"' <"$TMP")")"
CHAT[TITLE]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","title"' <"$TMP")")"
CHAT[TYPE]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","type"' <"$TMP")")"
CHAT[ALL_MEMBERS_ARE_ADMINISTRATORS]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","chat","all_members_are_administrators"' <"$TMP")")"
# User
USER[ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","from","id"\]/ s/.*\][ \t]//p' <"$TMP" )"
USER[FIRST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","from","first_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
USER[LAST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","from","last_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
USER[USERNAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","from","username"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
USER[ID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","from","id"' <"$TMP" )"
USER[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","from","first_name"' <"$TMP")")"
USER[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","from","last_name"' <"$TMP")")"
USER[USERNAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","from","username"' <"$TMP")")"
# in reply to message from
REPLYTO[UID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","from","id"\]/ s/.*\][ \t]//p' <"$TMP" )"
REPLYTO[UID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","reply_to_message","from","id"' <"$TMP" )"
if [ "${REPLYTO[UID]}" != "" ]; then
REPLYTO[0]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","text"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
REPLYTO[ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","message_id"\/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
REPLYTO[FIRST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","from","first_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
REPLYTO[LAST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","from","last_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
REPLYTO[USERNAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","reply_to_message","from","username"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
REPLYTO[0]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","reply_to_message","text"' <"$TMP")")"
REPLYTO[ID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","reply_to_message","message_id"' <"$TMP")"
REPLYTO[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","reply_to_message","from","first_name"' <"$TMP")")"
REPLYTO[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","reply_to_message","from","last_name"' <"$TMP")")"
REPLYTO[USERNAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","reply_to_message","from","username"' <"$TMP")")"
fi
# forwarded message from
FORWARD[UID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","forward_from","id"\]/ s/.*\][ \t]//p' <"$TMP" )"
FORWARD[UID]="$(JsonGetValue '"result",'$PROCESS_NUMBER',"message","forward_from","id"' <"$TMP" )"
if [ "${FORWARD[UID]}" != "" ]; then
FORWARD[ID]="${MESSAGE[ID]}" # same as message ID
FORWARD[FIRST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","forward_from","first_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
FORWARD[LAST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","forward_from","last_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
FORWARD[USERNAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","forward_from","username"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
FORWARD[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","forward_from","first_name"' <"$TMP")")"
FORWARD[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","forward_from","last_name"' <"$TMP")")"
FORWARD[USERNAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","forward_from","username"' <"$TMP")")"
fi
# Audio
URLS[AUDIO]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","audio","file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[AUDIO]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","audio","file_id"' <"$TMP")")")"
# Document
URLS[DOCUMENT]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","document","file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[DOCUMENT]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","document","file_id"' <"$TMP")")")"
# Photo
URLS[PHOTO]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","photo",.*,"file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[PHOTO]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","photo",.*,"file_id"' <"$TMP")")")"
# Sticker
URLS[STICKER]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","sticker","file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[STICKER]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","sticker","file_id"' <"$TMP")")")"
# Video
URLS[VIDEO]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","video","file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[VIDEO]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","video","file_id"' <"$TMP")")")"
# Voice
URLS[VOICE]="$(get_file "$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","voice","file_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")")"
URLS[VOICE]="$(get_file "$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","voice","file_id"' <"$TMP")")")"
# Contact
CONTACT[NUMBER]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","contact","phone_number"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CONTACT[FIRST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","contact","first_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CONTACT[LAST_NAME]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","contact","last_name"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CONTACT[USER_ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","contact","user_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CONTACT[NUMBER]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","contact","phone_number"' <"$TMP")")"
CONTACT[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","contact","first_name"' <"$TMP")")"
CONTACT[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","contact","last_name"' <"$TMP")")"
CONTACT[USER_ID]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","contact","user_id"' <"$TMP")")"
# Caption
CAPTION="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","caption"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
CAPTION="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","caption"' <"$TMP")")"
# Location
LOCATION[LONGITUDE]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","location","longitude"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
LOCATION[LATITUDE]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","location","latitude"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
LOCATION[LONGITUDE]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","location","longitude"' <"$TMP")")"
LOCATION[LATITUDE]="$(JsonDecode "$(JsonGetString '"result",'$PROCESS_NUMBER',"message","location","latitude"' <"$TMP")")"
NAME="$(echo "${URLS[*]}" | sed 's/.*\///g')"
rm "$TMP"
@ -570,18 +595,53 @@ process_client() {
grep -q "$tmpcount" <"${COUNT}" >/dev/null 2>&1 || echo "$tmpcount">>${COUNT}
# To get user count execute bash bashbot.sh count
}
# get bot name
getBotName() {
res="$(curl -s "$ME_URL")"
echo "$res" | ./JSON.sh/JSON.sh -s | JsonGetString '"result","username"'
}
ME="$(getBotName)"
if [ "$ME" = "" ]; then
echo -e "${RED}ERROR: Can't connect to Telegram Bot! May be your TOKEN is invalid ...${NC}"
exit 1
fi
# use phyton JSON to decode JSON UFT-8, provide bash implementaion as fallback
if which python >/dev/null 2>&1 || which phyton2 >/dev/null 2>&1; then
JsonDecode() {
printf '"%s\\n"' "${1//\"/\\\"}" | python -c 'import json, sys; sys.stdout.write(json.load(sys.stdin).encode("utf-8"))'
}
else
# pure bash implementaion, done by KayM (@gnadelwartz)
# see https://stackoverflow.com/a/55666449/9381171
JsonDecode() {
local out="$1"
local remain=""
local regexp='(.*)\\u[dD]([0-9a-fA-F]{3})\\u[dD]([0-9a-fA-F]{3})(.*)'
while [[ "${out}" =~ $regexp ]] ; do
# match 2 \udxxx hex values, calculate new U, then split and replace
local W1="$(( ( 0xd${BASH_REMATCH[2]} & 0x3ff) <<10 ))"
local W2="$(( 0xd${BASH_REMATCH[3]} & 0x3ff ))"
U="$(( ( W1 | W2 ) + 0x10000 ))"
remain="$(printf '\\U%8.8x' "${U}")${BASH_REMATCH[4]}${remain}"
out="${BASH_REMATCH[1]}"
done
echo -e "${out}${remain}"
}
fi
# source the script with source as param to use functions in other scripts
while [ "$1" == "startbot" ]; do {
while [ "$1" = "startbot" ]; do {
UPDATE="$(curl -s "$UPD_URL$OFFSET" | ./JSON.sh/JSON.sh)"
# Offset
OFFSET="$(echo "$UPDATE" | grep '\["result",[0-9]*,"update_id"\]' | tail -1 | cut -f 2)"
OFFSET="$(echo "$UPDATE" | JsonGetValue '"result",[0-9]*,"update_id"')"
OFFSET=$((OFFSET+1))
if [ "$OFFSET" != "1" ]; then
if [ "$2" == "test" ]; then
if [ "$2" = "test" ]; then
process_updates "$2"
else
process_updates "$2" &
@ -643,7 +703,7 @@ case "$1" in
${CLEAR}
echo -e "${GREEN}Restart background processes ...${NC}"
for FILE in "${TMPDIR:-.}/"*-back.cmd; do
if [ "${FILE}" == "${TMPDIR:-.}/*-back.cmd" ]; then
if [ "${FILE}" = "${TMPDIR:-.}/*-back.cmd" ]; then
echo -e "${RED}No background processes to start.${NC}"; break
else
RESTART="$(< "${FILE}")"
@ -670,14 +730,14 @@ case "$1" in
${CLEAR}
echo -e "${GREEN}Stopping background processes ...${NC}"
for FILE in "${TMPDIR:-.}/"*-back.cmd; do
if [ "${FILE}" == "${TMPDIR:-.}/*-back.cmd" ]; then
if [ "${FILE}" = "${TMPDIR:-.}/*-back.cmd" ]; then
echo -e "${RED}No background processes.${NC}"; break
else
REMOVE="$(< "${FILE}")"
JOB="${REMOVE#*:}"
fifo="back-${JOB%:*}-${ME}_${REMOVE%%:*}"
echo "killbackground ${fifo}"
[ "$1" == "killback" ] && rm -f "${FILE}" # remove job
[ "$1" = "killback" ] && rm -f "${FILE}" # remove job
( tmux kill-session -t "${fifo}"; tmux kill-session -t "sendprocess_${fifo}"; rm -f -r "${TMPDIR:-.}/${fifo}") 2>/dev/null
fi
done
@ -695,7 +755,7 @@ case "$1" in
exit
;;
*)
echo -e "${RED}BAD REQUEST${NC}"
echo -e "${RED}${ME}: BAD REQUEST${NC}"
echo -e "${RED}Available arguments: outproc, count, broadcast, start, suspendback, resumeback, kill, killback, help, attach${NC}"
exit 4
;;

34
calc Executable file
View File

@ -0,0 +1,34 @@
#!/bin/bash
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.60-0-gf5162e2
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment
export 'LC_ALL=C.UTF-8'
export 'LANG=C.UTF-8'
export 'LANGUAGE=C.UTF-8'
unset IFS
# set -f # if you are paranoid use set -f to disable globbing
echo 'Starting Calculator ...'
echo 'Enter first number.'
read -r A
echo 'Enter second number.'
read -r B
echo 'Select Operation: mykeyboardstartshere [ "Addition" , "Subtraction" , "Multiplication" , "Division" , "Cancel" ]'
read -r opt
echo -n 'Result: '
case $opt in
'add'* | 'Add'* ) res="$(( A + B ))" ;;
'sub'* | 'Sub'* ) res="$(( A - B ))" ;;
'mul'* | 'Mul'* ) res="$(( A * B ))" ;;
'div'* | 'Div'* ) res="$(( A / B ))" ;;
'can'* | 'Can'* ) res="abort!" ;;
* ) echo "unknown operator!";;
esac
echo "$res"
echo "Bye .."

View File

@ -4,7 +4,7 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.52-1-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
#
# shellcheck disable=SC2154
# shellcheck disable=SC2034
@ -71,7 +71,7 @@ else
[ ! -z "${LOCATION[*]}" ] && send_location "${CHAT[ID]}" "${LOCATION[LATITUDE]}" "${LOCATION[LONGITUDE]}"
# Inline
if [ $INLINE == 1 ]; then
if [ "$INLINE" = 1 ]; then
# inline query data
iUSER[FIRST_NAME]="$(echo "$res" | sed 's/^.*\(first_name.*\)/\1/g' | cut -d '"' -f3 | tail -1)"
iUSER[LAST_NAME]="$(echo "$res" | sed 's/^.*\(last_name.*\)/\1/g' | cut -d '"' -f3)"
@ -80,18 +80,18 @@ else
iQUERY_MSG="$(echo "$res" | sed 's/^.*\(inline_query.*\)/\1/g' | cut -d '"' -f5 | tail -6 | head -1)"
# Inline examples
if [[ "$iQUERY_MSG" == "photo" ]]; then
if [[ "$iQUERY_MSG" = "photo" ]]; then
answer_inline_query "$iQUERY_ID" "photo" "http://blog.techhysahil.com/wp-content/uploads/2016/01/Bash_Scripting.jpeg" "http://blog.techhysahil.com/wp-content/uploads/2016/01/Bash_Scripting.jpeg"
fi
if [[ "$iQUERY_MSG" == "sticker" ]]; then
if [[ "$iQUERY_MSG" = "sticker" ]]; then
answer_inline_query "$iQUERY_ID" "cached_sticker" "BQADBAAD_QEAAiSFLwABWSYyiuj-g4AC"
fi
if [[ "$iQUERY_MSG" == "gif" ]]; then
if [[ "$iQUERY_MSG" = "gif" ]]; then
answer_inline_query "$iQUERY_ID" "cached_gif" "BQADBAADIwYAAmwsDAABlIia56QGP0YC"
fi
if [[ "$iQUERY_MSG" == "web" ]]; then
if [[ "$iQUERY_MSG" = "web" ]]; then
answer_inline_query "$iQUERY_ID" "article" "GitHub" "http://github.com/topkecleon/telegram-bot-bash"
fi
fi &
@ -131,8 +131,8 @@ else
;;
'/start')
send_action "${CHAT[ID]}" "typing"
user_is_botadmin "${USER[ID]}" && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
if user_is_allowed "${USER[ID]}" "start" "${CHAT[ID]}" ; then
_is_botadmin && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
if _is_allowed "start" ; then
bot_help "${CHAT[ID]}"
else
send_normal_message "${CHAT[ID]}" "You are not allowed to start Bot."
@ -140,7 +140,7 @@ else
;;
'/leavechat') # bot leave chat if user is admin in chat
if user_is_admin "${CHAT[ID]}" "${USER[ID]}"; then
if _is_admin ; then
send_markdown_message "${CHAT[ID]}" "*LEAVING CHAT...*"
leave_chat "${CHAT[ID]}"
fi
@ -155,8 +155,8 @@ else
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
*) # forward input to interactive chat if running
if tmux ls | grep -v send | grep -q "$copname"; then inproc; fi
;;
esac
fi

View File

@ -1,5 +1,5 @@
## Create your first telegram bot
#### [Home](../README.md)
## Create a Telegram Bot with botfather
1. Message @botfather https://telegram.me/botfather with the following
text: `/newbot`
@ -58,17 +58,8 @@ group. This step is up to you actually.
13. @botfather replies with `Success! The new status is: DISABLED. /help`
### Install bashbot
1. Go to the directory you want to install bashbot, e.g.
- your $HOME directory (install and run with your user-ID)
- /usr/local if you want to run as service
#### [Next Getting started](2_usage.md)
2. Clone the repository:
```
git clone --recursive https://github.com/topkecleon/telegram-bot-bash
```
3. Change to directory ```telegram-bot.bash```, run ```./bashbot.sh init``` and follow the instructions. At this stage you are asked for your Bots token given by botfather.
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2

View File

@ -1,4 +1,5 @@
## Make your own Bot
#### [Home](../README.md)
## Gettting Started
All Commands for the Bot are in the ```commands.sh``` file (this should ease upgrades of the bot core). Here you find some examples how to process messages and send out text.
@ -36,55 +37,84 @@ To send a broadcast to all of users that ever used the bot run the following com
## Recieve data
Evertime a Message is recieved, you can read incoming data using the following variables:
* ```$MESSAGE```: Incoming messages
* ```${MESSAGE[ID]}```: ID of incoming message
* ```${MESSAGE}```: Current incoming messages
* ```${MESSAGE[ID]}```: ID of current message
* ```$CAPTION```: Captions
* ```$REPLYTO```: Original message wich was replied to
* ```$USER```: This array contains the First name, last name, username and user id of the sender of the current message.
- ```${USER[ID]}```: User id
- ```${USER[FIRST_NAME]}```: User's first name
- ```${USER[LAST_NAME]}```: User's last name
- ```${USER[USERNAME]}```: Username
* ```${USER[ID]}```: User id
* ```${USER[FIRST_NAME]}```: User's first name
* ```${USER[LAST_NAME]}```: User's last name
* ```${USER[USERNAME]}```: Username
* ```$CHAT```: This array contains the First name, last name, username, title and user id of the chat of the current message.
- ```${CHAT[ID]}```: Chat id
- ```${CHAT[FIRST_NAME]}```: Chat's first name
- ```${CHAT[LAST_NAME]}```: Chat's last name
- ```${CHAT[USERNAME]}```: Username
- ```${CHAT[TITLE]}```: Title
- ```${CHAT[TYPE]}```: Type
- ```${CHAT[ALL_MEMBERS_ARE_ADMINISTRATORS]}```: All members are administrators (true if true)
* ```${CHAT[ID]}```: Chat id
* ```${CHAT[FIRST_NAME]}```: Chat's first name
* ```${CHAT[LAST_NAME]}```: Chat's last name
* ```${CHAT[USERNAME]}```: Username
* ```${CHAT[TITLE]}```: Title
* ```${CHAT[TYPE]}```: Type
* ```${CHAT[ALL_MEMBERS_ARE_ADMINISTRATORS]}```: All members are administrators (true if true)
* ```$REPLYTO```: This array contains the First name, last name, username and user id of the ORIGINAL sender of the message REPLIED to.
- ```${REPLYTO[ID]}```: ID of message wich was replied to
- ```${REPLYTO[UID]}```: Original user's id
- ```${REPLYTO[FIRST_NAME]}```: Original user's first name
- ```${REPLYTO[LAST_NAME]}```: Original user's' last name
- ```${REPLYTO[USERNAME]}```: Original user's username
* ```${REPLYTO[ID]}```: ID of message wich was replied to
* ```${REPLYTO[UID]}```: Original user's id
* ```${REPLYTO[FIRST_NAME]}```: Original user's first name
* ```${REPLYTO[LAST_NAME]}```: Original user's' last name
* ```${REPLYTO[USERNAME]}```: Original user's username
* ```$FORWARD```: This array contains the First name, last name, username and user id of the ORIGINAL sender of the FORWARDED message.
- ```${FORWARD[ID]}```: Same as MESSAGE[ID] if message is forwarded
- ```${FORWARD[UID]}```: Original user's id
- ```${FORWARD[FIRST_NAME]}```: Original user's first name
- ```${FORWARD[LAST_NAME]}```: Original user's' last name
- ```${FORWARD[USERNAME]}```: Original user's username
* ```${FORWARD[ID]}```: Same as MESSAGE[ID] if message is forwarded
* ```${FORWARD[UID]}```: Original user's id
* ```${FORWARD[FIRST_NAME]}```: Original user's first name
* ```${FORWARD[LAST_NAME]}```: Original user's' last name
* ```${FORWARD[USERNAME]}```: Original user's username
* ```$URLS```: This array contains documents, audio files, stickers, voice recordings and stickers stored in the form of URLs.
- ```${URLS[AUDIO]}```: Audio files
- ```${URLS[VIDEO]}```: Videos
- ```${URLS[PHOTO]}```: Photos (maximum quality)
- ```${URLS[VOICE]}```: Voice recordings
- ```${URLS[STICKER]}```: Stickers
- ```${URLS[DOCUMENT]}```: Any other file
* ```${URLS[AUDIO]}```: Audio files
* ```${URLS[VIDEO]}```: Videos
* ```${URLS[PHOTO]}```: Photos (maximum quality)
* ```${URLS[VOICE]}```: Voice recordings
* ```${URLS[STICKER]}```: Stickers
* ```${URLS[DOCUMENT]}```: Any other file
* ```$CONTACT```: This array contains info about contacts sent in a chat.
- ```${CONTACT[NUMBER]}```: Phone number
- ```${CONTACT[FIRST_NAME]}```: First name
- ```${CONTACT[LAST_NAME]}```: Last name
- ```${CONTACT[ID]}```: User id
* ```${CONTACT[NUMBER]}```: Phone number
* ```${CONTACT[FIRST_NAME]}```: First name
* ```${CONTACT[LAST_NAME]}```: Last name
* ```${CONTACT[ID]}```: User id
* ```$LOCATION```: This array contains info about locations sent in a chat.
- ```${LOCATION[LONGITUDE]}```: Longitude
- ```${LOCATION[LATITUDE]}```: Latitude
* ```${LOCATION[LONGITUDE]}```: Longitude
* ```${LOCATION[LATITUDE]}```: Latitude
## Usage of bashbot functions
#### sending messages
To send messages use the ```send_xxx_message``` functions.
To send regular text without any markdown use:
```bash
send_text_message "${CHAT[ID]}" "lol"
```
To send text with markdown:
```bash
send_markdown_message "${CHAT[ID]}" "lol *bold*"
```
To send text with html:
```bash
send_html_message "${CHAT[ID]}" "lol <b>bold</b>"
```
To forward messages use the ```forward``` function:
```bash
forward "${CHAT[ID]}" "from_chat_id" "message_id"
```
If your Bot is Admin in a Chat you can delete every message, if not you can delete only your messages.
To delete a message with a known ${MESSAGE[ID]} you can simple use:
```bash
delete_message "${CHAT[ID]}" "${MESSAGE[ID]}"
```
#### send_message
To send messages use the ```send_message``` function:
In addition there is a universal send_massage function which can output any type of message.
This function is used to process output from external scrips like interactive chats or background jobs.
**For safety and performance reasons I recommend to use send_xxxx_message functions above for sending messages**
```bash
send_message "${CHAT[ID]}" "lol"
```
@ -99,39 +129,18 @@ This function also allows a third parameter that disables additional function pa
```bash
send_message "${CHAT[ID]}" "lol" "safe"
```
To forward messages use the ```forward``` function:
```bash
forward "${CHAT[ID]}" "from_chat_id" "message_id"
```
More examples boutsend_message strings can be found in [Advanced Usage](3_advanced.md#Interactive-Chats)
#### For safety and performance reasoms I recommend to use send_xxxx_message direct and not the universal send_message function.
To send regular text without any markdown use:
```bash
send_text_message "${CHAT[ID]}" "lol"
```
To send text with markdown:
```bash
send_markdown_message "${CHAT[ID]}" "lol *bold*"
```
To send text with html:
```bash
send_html_message "${CHAT[ID]}" "lol <b>bold</b>"
```
If your Bot is Admin in a Chat you can delete every message, if not you can delete only your messages.
To delete a message with a known ${MESSAGE[ID]} you can simple use:
```bash
delete_message "${CHAT[ID]}" "${MESSAGE[ID]}"
```
#### Send files, location etc.
#### Send files, locations, keyboards.
To send images, videos, voice files, photos etc. use the ```send_photo``` function (remember to change the safety Regex @ line 14 of command.sh to allow sending files only from certain directories):
```bash
send_file "${CHAT[ID]}" "/home/user/doge.jpg" "Lool"
```
To send custom keyboards use the ```send_keyboard``` function:
```bash
send_keyboard "${CHAT[ID]}" "Text that will appear in chat?" "Yep" "No"
send_keyboard "${CHAT[ID]}" "Text that will appear in chat?" '[ "Yep" , "No" ]' # note the simgle quotes!
send_keyboard "${CHAT[ID]}" "Text that will appear in chat?" "[ \\"Yep\\" , \\"No\\" ]" # within double quotes you must excape the inside double quots
```
To send locations use the ```send_location``` function:
```bash
@ -147,6 +156,8 @@ Allowed values: typing for text messages, upload_photo for photos, record_video
send_action "${CHAT[ID]}" "action"
```
#### $$VERSION$$ v0.52-0-gdb7b19f
#### [Prev Create Bot](1_firstbot.md)
#### [Next Advanced Usage](3_advanced.md)
#### $$VERSION$$ v0.60-0-gf5162e2

View File

@ -1,7 +1,9 @@
#### [Home](../README.md)
## Advanced Features
### Access control
Bashbot offers functions to check if a has Telegram capabilities like chat admin or chat creator:
Bashbot offers functions to check what Telegram capabilities like chat admin or chat creator the given user has:
```bash
# return true if user is admin/owner of the bot
# -> botadmin is stored in file './botadmin'
@ -19,10 +21,10 @@ user_is_botadmin "${USER[ID]}" && send_markdown_message "${CHAT[ID]}" "You are *
user_is_admin "${CHAT[ID]}" "${USER[ID]}" && send_markdown_message "${CHAT[ID]}" "You are *CHATADMIN*."
```
In addtion you can configure individual capabilities for users in the file ```./botacl```:
In addition you can check individual capabilities of users as defined in the ```./botacl``` file:
```bash
# botacl
# if a user is not listed here, function 'user_is_allowed' will always return false
# file: botacl
# a user not listed here, will return false from 'user_is_allowed'
#
# Format:
# user:ressource:chat
@ -42,8 +44,7 @@ In addtion you can configure individual capabilities for users in the file ```./
*:start:*
*:*:98979695
```
you have to check yourself if a user is allowed to to something by calling function ```user_is_allowed```.
example to check if a user is allowed to start bot:
you have to use the function ```user_is_allowed``` to check if a user has the capability to do something. Example check if user has capability to start bot:
```bash
case "$MESSAGE" in
'/start')
@ -61,7 +62,7 @@ To create interactive chats, write (or edit the question script) a normal bash (
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:
```bash
echo "Text that will appear in chat? mykeyboardstartshere \"Yep, sure\" \"No, highly unlikely\""
echo "Text that will appear in chat? mykeyboardstartshere [ \"Yep, sure\" , \"No, highly unlikely\" ]"
```
Same goes for files:
```bash
@ -77,7 +78,7 @@ echo "Text that will appear in chat. mylatstartshere 45 mylongstartshere 45 myti
```
You can combine them:
```bash
echo "Text that will appear in chat? mykeyboardstartshere \"Yep, sure\" \"No, highly unlikely\" myfilelocationstartshere /home/user/doge.jpg mylatstartshere 45 mylongstartshere 45"
echo "Text that will appear in chat? mykeyboardstartshere [ \"Yep, sure\" , \"No, highly unlikely\" ] myfilelocationstartshere /home/user/doge.jpg mylatstartshere 45 mylongstartshere 45"
```
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.
@ -152,6 +153,8 @@ To send stickers through an *inline query*:
```bash
answer_inline_query "$iQUERY_ID" "cached_sticker" "identifier for the sticker"
```
#### [Prev Advanced Usage](3_advanced.md)
#### [Next Expert Use](4_expert.md)
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2

View File

@ -1,8 +1,15 @@
#### [Home](../README.md)
## Expert Use
### Handling UTF-8 character sets
UTF-8 is a variable length encoding of Unicode. UTF-8 is recommended as the default encoding in JSON, XML and HTML, also Telegram make use of it.
The first 128 characters are regular ASCII, so it's a superset of and compatible with ASCII environments. The next 1,920 characters need
two bytes for encoding and covers almost all ```Latin``` alphabets, also ```Greek```, ```Cyrillic```,
```Hebrew```, ```Arabic``` and more. See [Wikipedia](https://en.wikipedia.org/wiki/UTF-8) for more details.
#### Setting up your Environment
In general ```bash``` and ```GNU``` utitities are UTF-8 aware, but you have to setup your environment
In general ```bash``` and ```GNU``` utitities are UTF-8 aware if you to setup your environment
and your scripts accordingly:
1. Your Terminal and Editor must support UTF-8:
@ -30,28 +37,21 @@ export 'LANGUAGE=den_US.UTF-8'
To display all availible locales on your system run ```locale -a | more```. [Gentoo Wiki](https://wiki.gentoo.org/wiki/UTF-8)
#### UTF-8 in Telegram
```UTF-8``` is a variable length encoding of Unicode. UTF-8 is recommended as the default encoding in JSON, XML and HTML, also Telegram make use of it.
#### Bashbot UTF-8 Support
Bashbot handles all messages transparently, regardless of the charset in use. The only exception is when converting from JSON data to strings.
The first 128 characters are regular ASCII, so it's a superset of and compatible with ASCII environments. The next 1,920 characters need
two bytes for encoding and covers almost all ```Latin``` alphabets, also ```Greek```, ```Cyrillic```,
```Hebrew```, ```Arabic``` and more. See [Wikipedia](https://en.wikipedia.org/wiki/UTF-8) for more deatils.
Telegram use JSON to send / recieve data. JSON encodes strings as follow: Characters not ASCII *(>127)* are escaped as sequences of ```\uxxxx``` to be regular ASCII. In addition multibyte characters, *e.g. Emoticons or Arabic characters*, are send in double byte UTF-16 notation.
The Emoticons ``` 😁 😘 ❤️ 😊 👍 ``` are encoded as: ``` \uD83D\uDE01 \uD83D\uDE18 \u2764\uFE0F \uD83D\uDE0A \uD83D\uDC4D ```
Telegram send Messages with all characters not fitting in one byte (256 bit) escaped as sequences of ```\uxxxx``` to be regular one byte ASCII (incl. iso-xxx-x), e.g. Emoticons and Arabic characters.
E.g. the Emoticons ``` 😁 😘 ❤️ 😊 👍 ``` are encoded as:
```
\uD83D\uDE01 \uD83D\uDE18 \u2764\uFE0F \uD83D\uDE0A \uD83D\uDC4D
```
'\uXXXX' and '\UXXXXXXXX' escaped endocings are supported by zsh, bash, ksh93, mksh and FreeBSD sh, GNU 'printf' and GNU 'echo -e', see [this Stackexchange Answer](https://unix.stackexchange.com/questions/252286/how-to-convert-an-emoticon-specified-by-a-uxxxxx-code-to-utf-8/252295#252295) for more information.
**This "mixed" JSON encoding needs special handling and can not decoded from** ```echo -e``` or ```printf '%s\\n'```
Most complete support for decoding of multibyte characters can only be provided if python is installed on your system.
**Without phyton bashbot falls back to an internal, pure bash implementation which may not work for some corner cases**.
### Run as other user or system service
Bashbot is desingned to run manually by the user who installed it. Nevertheless it's possible to run it by an other user-ID, as a system service or sceduled from cron. This is onyl recommended for experiend linux users.
####Running bashbot as an other user is only possible with sudo rigths.
Setup the environment for the user you want to run bashbot and enter desired username, e.g. nobody :
```bash
sudo ./bashbot.sh init
@ -76,13 +76,13 @@ name='' # your bot name as given to botfather, e.g. mysomething_bot
# END Configuration
#######################
```
From now on always use bashbot.rc to start/stop your bot:
From now on use 'bashbot.rc' to manage your bot:
```bash
sudo ./bashbot.rc start
```
Type ```ps -ef | grep bashbot``` to verify your Bot is running as the desired user.
If you started bashbot by bashbot.rc you must use bashbot.rc also to manage your Bot! The following commands are availible:
If your Bot is started by 'bashbot.rc', you must use 'bashbot.rc' also to manage your Bot! The following commands are availible:
```bash
sudo ./bashbot.rc start
sudo ./bashbot.rc stop
@ -101,6 +101,8 @@ An example crontab is provided in ```bashbot.cron```.
- If you are running bashbot with your user-ID, copy the examples lines to your crontab and remove username ```nobody```.
- if you run bashbot as an other user or a system service edit ```bashbot.cron``` to fit your needs and replace username```nobody``` with the username you want to run bashbot. copy the modified file to ```/etc/cron.d/bashbot```
#### [Prev Expert Use](4_expert.md)
#### [Next Best Practice](5_practice.md)
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2

View File

@ -1,9 +1,9 @@
#### [Home](../README.md)
## Best Practices
### Customizing commands.sh
### Customize commands.sh only
To ease Updates never change ```bashbot.sh```, all changes should be done in ```commands.sh``` .
Insert your own Bot commands in the ```case ... esac``` block in commands.sh:
To ease Updates never change ```bashbot.sh```, instead individual commands should go to ```commands.sh``` . Insert your Bot commands in the ```case ... esac``` block:
```bash
case "$MESSAGE" in
'/echo') # my first own command, echo MESSAGE
@ -11,30 +11,27 @@ Insert your own Bot commands in the ```case ... esac``` block in commands.sh:
;;
################################################
# DEFAULT commands start here, edit messages only
# DEFAULT commands start here, do not edit below this!
'/info')
bashbot_info "${CHAT[ID]}"
;;
esac
```
after editing commands.sh restart Bot.
### Seperate Bot logic from command
### Seperate logic from commands
If a Bot command needs more than 2-3 lines of code I recommend to factor it out to a bash function in a seperate file, e.g.
```mybotcommands.inc.sh``` and source the file from bashbot.sh. ```bashbot_info and bashbot_help``` are examples how to use
bash functions to make customisation easy and keep case block small. ```process_message``` is an example for a complex
processing logic as a bash funtcion in a seperate file.
If a command need more than 2-3 lines of code, you should use a function to seperate logic from command. Place your functions in a seperate file, e.g. ```mycommands.inc.sh``` and source it from bashbot.sh. Example:
```bash
source mybotcommands.inc.sh
source "mycommands.inc.sh"
case "$MESSAGE" in
'/report') # report dealz from database and output result
send_normal_message "${CHAT[ID]}" "$(process_message "$MESSAGE")"
'/process') # logic for /process is done in process_message
result="$(process_message "$MESSAGE")"
send_normal_message "${CHAT[ID]}" "$result"
;;
################################################
# DEFAULT commands start here, edit messages only
# DEFAULT commands start here, do not edit below this!
'/info')
bashbot_info "${CHAT[ID]}"
;;
@ -44,15 +41,15 @@ processing logic as a bash funtcion in a seperate file.
;;
esac
```
Example ```mybotcommands.inc.sh```:
```bash
#!/bin/bash
#
# file: mycommands.inc.sh
process_message() {
local ARGS="${1#/* }" # remove command /*
local ARGS="${1#/* }" # remove command
local TEXT OUTPUT=""
# process every word in MESSAGE, avoid globbing from MESSAGE
# process every word in MESSAGE, avoid globbing
set -f
for WORD in $ARGS
do
@ -76,7 +73,6 @@ process_message() {
}
```
Doing it this way keeps commands.sh small and clean, while allowing complex tasks to be done in the included function.
### Test your Bot with shellcheck
Shellcheck is a static linter for shell scripts providing excellent tips and hints for shell coding pittfalls. You can [use it online](https://www.shellcheck.net/) or [install it on your system](https://github.com/koalaman/shellcheck#installing).
@ -91,6 +87,7 @@ Line 17:
^-- SC2116: Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'.
```
As you can see my ```mybotcommands.inc.sh``` contains an useless echo command in 'TEXT=' assigment and can be replaced by ```TEXT="${TEXT}${WORD}"```
```bash
$ shellcheck -x notify
OK
@ -109,7 +106,11 @@ In bashbot.sh line 490:
CONTACT[USER_ID]="$(sed -n -e '/\["result",'$PROCESS_NUMBER',"message","contact","user_id"\]/ s/.*\][ \t]"\(.*\)"$/\1/p' <"$TMP")"
^-- SC2034: CONTACT appears unused. Verify it or export it.
```
As you can see there are only two warnings in bashbots scripts. The first is a hint you may use shell substitions instead of sed, but this is only possible for simple cases. The second warning is about an unused variable, this is true because in our examples CONTACT is not used but assigned in case you want to use it :-)
The example show two warnings in bashbots scripts. The first is a hint you may use shell substitions instead of sed, this is fixed and much faster as the "echo | sed" solution.
The second warning is about an unused variable, this is true because in our examples CONTACT is not used but assigned in case you want to use it :-)
#### $$VERSION$$ v0.52-0-gdb7b19f
#### [Prev Best Practice](5_practice.md)
#### [Next Functions Reference](6_reference.md)
#### $$VERSION$$ v0.60-0-gf5162e2

351
doc/6_reference.md Normal file
View File

@ -0,0 +1,351 @@
#### [Home](../README.md)
## Bashbot function reference
### Send, forward, delete messages
##### send_action
```send_action``` shows users what your bot is currently doing.
*usage:* send_action "${CHAT[ID]}" "action"
*"action":* ```typing```, ```upload_photo```, ```record_video```, ```upload_video```, ```record_audio```, ```upload_audio```, ```upload_document```, ```find_location```.
*example:*
```bash
send_action "${CHAT[ID]}" "typing"
send_action "${CHAT[ID]}" "record_audio"
```
##### send_normal_message
```send_normal_message``` sends text only messages to the given chat.
*usage:* send_normal_message "${CHAT[ID]}" "message"
*example:*
```bash
send_normal_message "${CHAT[ID]}" "this is a text message"
```
##### send_markdown_message
```send_markdown_message``` sends markdown style messages to the given chat.
Telegram supports a [reduced set of Markdown](https://core.telegram.org/bots/api#markdown-style) only
*usage:* send_markdown_message "${CHAT[ID]}" "markdown message"
*example:*
```bash
send_normal_message "${CHAT[ID]}" "this is a markdown message, next word is *bold*"
send_normal_message "${CHAT[ID]}" "*bold* _italic_ [text](link)"
```
##### send_html_message
```send_html_message``` sends HTML style messages to the given chat.
Telegram supports a [reduced set of HTML](https://core.telegram.org/bots/api#html-style) only
*usage:* send_html_message "${CHAT[ID]}" "html message"
*example:*
```bash
send_normal_message "${CHAT[ID]}" "this is a markdown message, next word is <b>bold</b>"
send_normal_message "${CHAT[ID]}" "<b>bold</b> <i>italic><i> <em>italic>/em> <a href="link">Text</a>"
```
##### forward_message
```forward_mesage``` forwards a messsage to the given chat.
*usage:* forward_message "chat_to" "chat_from" "${MESSAGE[ID]}"
*alias:* forward "${CHAT[ID]}" "$FROMCHAT" "${MESSAGE[ID]}"
----
##### send_message
```send_message``` sends any type of message to the given chat. Type of output is steered by keywords within the message.
The main use case for send_message is to process the output of interactive chats and background jobs. **For regular Bot commands I recommend using of the dedicated send_xxx_message() functions from above.**
*usage:* send_message "${CHAT[ID]}" "message"
*example:* - see [Usage](2_usage.md#send_message) and [Advanced Usage](3_advanced.md#Interactive-Chats)
----
##### delete_message
If your Bot is admin of a Chat he can delete every message, if not he can delete only his messages.
*usage:* delete_message "${CHAT[ID]}" "${MESSAGE[ID]}"
----
##### answer_inline_query
Inline Queries allows users to interact with your bot directly without sending extra commands.
answer_inline_query provide the result to a users Inline Query
*usage:* answer_inline_query "$iQUERY_ID" "type" "type arg 1" ... "type arg n"
*example:* - see [Advanced Usage](3_advanced.md#Inline-queries)
----
### File, Location, Venue, Keyboard
##### send_file
send_file allows you to send different type's of files, e.g. photos, stickers, audio, media, etc. [see more](https://core.telegram.org/bots/api#sending-files)
*usage:* send_file "${CHAT[ID]}" "file" "caption"
*example:*
```bash
send_file "${CHAT[ID]}" "/home/user/doge.jpg" "Lool"
send_file "${CHAT[ID]}" "https://www.domain,com/something.gif" "Something"
```
##### send_location
*usage:* send_location "${CHAT[ID]}" "Latitude" "Longitude"
##### send_venue
*usage:* send_venue "${CHAT[ID]}" "Latitude" "Longitude" "Title" "Address" "foursquare id (optional)"
----
##### send_keyboard
Note: since version 0.6 send_keyboard was changed to use native "JSON Array" notation as used from Telegram. Example Keybord Array definitions:
- yes no in two rows:
- OLD format: 'yes' 'no' (two strings)
- NEW format: '[ "yes" ] , [ "no" ]' (two arrays with a string)
- new layouts made easy with NEW format:
- Yes No in one row: '[ "yes" , "no" ]'
- Yes No plus Maybe in 2.row: '[ "yes" , "no" ] , [ "maybe" ]'
- numpad style keyboard: '[ "1" , "2" , "3" ] , [ "4" , "5" , "6" ] , [ "7" , "8" , "9" ] , [ "0" ]'
*usage:* send_keyboard "chat-id" "message" "keyboard"
*example:*
```bash
send_keyboard "${CHAT[ID]}" "Say yes or no" "[ \\"yes\" , \\"no\" ]""
send_keyboard "${CHAT[ID]}" "Say yes or no" "[ \\"yes\\" ] , [ \\"no\\" ]"
send_keyboard "${CHAT[ID]}" "Enter digit" "[ \\"1\\" , \\"2\\" , \\"3\\" ] , [ \\"4\\" , \\"5\\" , \\"6\\" ] , [ \\"7\\" , \\"8\\" , \\"9\\" ] , [ \\"0\\" ]"
```
##### remove_keyboard
*usage:* remove_keybord "$CHAT[ID]" "message"
### Manage users
##### kick_chat_member
If your Bot is Admin of a chat he can kick and ban a user.
*usage:* kick_chat_member "${CHAT[ID]}" "${USER[ID]}"
##### unban_chat_member
If your Bot is Admin of a chat he can unban a kicked user.
*usage:* unban_chat_member "${CHAT[ID]}" "${USER[ID]}"
##### leave_chat
Bot will leave given chat.
*usage:* leave_chat "${CHAT[ID]}"
```bash
if _is_admin ; then
send_markdown_message "${CHAT[ID]}" "*LEAVING CHAT...*"
leave_chat "${CHAT[ID]}"
fi
```
----
##### user_is_creator
Return true (0) if user is creator of given chat or chat is a private chat.
*usage:* user_is_creator "${CHAT[ID]}" "${USER[ID]}"
*alias:* _is_creator
##### user_is_admin
Return true (0) if user is admin or creator of given chat.
*usage:* user_is_admin "${CHAT[ID]}" "${USER[ID]}"
*alias:* _is_creator
*example:*
```bash
if _is_admin ; then
send_markdown_message "${CHAT[ID]}" "*LEAVING CHAT...*"
leave_chat "${CHAT[ID]}"
fi
```
##### user_is_botadmin
Return true (0) if user is owner / admin of bot.
Name or ID botadmin must be placed in './botadmin' file.
*usage:* user_is_botadmin "${CHAT[ID]}" "${USER[ID]}"
*alias:* _is_botadmin
*example:*
```bash
_is_botadmin && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
```
##### user_is_allowed
Bahsbot supports User Access Control, see [Advanced Usage](4_advanced.ma)
*usage:* user_is_allowed "${USER[ID]}" "what" "${CHAT[ID]}"
*example:*
```bash
if ! user_is_allowed "${USER[ID]}" "start" "${CHAT[ID]}" ; then
send_normal_message "${CHAT[ID]}" "You are not allowed to start Bot."
fi
```
### Interactive and backgound jobs
##### startproc
```startproc``` starts a script (or C or python program etc.) running in parallel to your Bot. The text that the script outputs is sent to the user or chat, user input will be sent back to the script. see [Advanced Usage](3_advanced.md#Interactive-Chats)
*usage:* startproc "./script"
*example:*
```bash
startproc './calc'
```
##### checkproc
Return true (0) if an interactive script active in the given chat.
*usage:* checkprog
*example:*
```bash
checkproc
if [ "$res" -gt 0 ] ; then
startproc "./calc"
else
send_normal_message "${CHAT[ID]}" "Calc already running ..."
fi
```
##### killproc
*usage:* killproc
*example:*
```bash
checkprog
if [ "$res" -eq 0 ]; then
killproc && send_message "${CHAT[ID]}" "Command canceled."
else
send_message "${CHAT[ID]}" "Command is not running."
fi
```
----
##### background
```background``` starts a script / programm as a background job and attaches a jobname to it. All output from a background job is sent to the associated chat.
In contrast to interactive chats, background jobs do not recieve user input and can run forever. In addition you can suspend and restart running jobs, e.g. after reboot.
*usage:* background "./script" "jobname"
*example:*
```bash
background "./notify" "notify"
```
##### checkback
Return true (0) if an background job is active in the given chat.
*usage:* checkback "jobname"
*example:*
```bash
checkback "notify"
if [ "$res" -gt 0 ] ; then
send_normal_message "${CHAT[ID]}" "Start notify"
background "./notify" "notify"
else
send_normal_message "${CHAT[ID]}" "Process notify already running."
fi
```
##### killback
*usage:* killback "jobname"
*example:*
```bash
checkback "notify"
if [ "$res" -eq 0 ] ; then
send_normal_message "${CHAT[ID]}" "Kill notify"
killback "notify"
else
send_normal_message "${CHAT[ID]}" "Process notify not run."
fi
```
### Bashbot internal functions
These functions are for internal use only and must not used in your bot commands.
##### get_file
*usage:* url="$(get_file "${CHAT[ID]}" "message")"
----
##### send_text
*usage:* send_text "${CHAT[ID]}" "message"
----
##### JsonDecode
Outputs decoded string to STDOUT
*usage:* JsonDecode "string"
##### JsonGetString
Reads JSON fro STDIN and Outputs found String to STDOUT
*usage:* JsonGetString `"path","to","string"`
##### JsonGetValue
Reads JSON fro STDIN and Outputs found Value to STDOUT
*usage:* JsonGetValue `"path","to","value"`
----
##### get_chat_member_status
*usage:* get_chat_member_status "${CHAT[ID]}" "${USER[ID]}"
----
##### process_client
Every Message sent to your Bot is processd by this function. It parse the send JSON and assign the found Values to bash variables.
##### process_updates
If new updates are availible, this functions gets the JSON from Telegram and dispatch it.
----
##### getBotName
The name of your bot is availible as bash variable "$ME", there is no need to call this function if Bot is running.
*usage:* ME="$(getBotNiname)"
##### inproc
Send Input from Telegram to waiting Interactive Chat.
#### [Prev Best Practice](5_practice.md)
#### $$VERSION$$ v0.60-0-gf5162e2

2
notify
View File

@ -2,7 +2,7 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment

View File

@ -3,7 +3,7 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment
@ -19,7 +19,7 @@ Would you like some tea (y/n)?"
read -r answer
[[ $answer =~ ^([yY][eE][sS]|[yY])$ ]] && echo "OK then, here you go: http://www.rivertea.com/blog/wp-content/uploads/2013/12/Green-Tea.jpg" || echo "OK then."
until [ "$SUCCESS" = "y" ] ;do
echo 'Do you like Music? mykeyboardstartshere "Yass!" "No"'
echo 'Do you like Music? mykeyboardstartshere "Yass!" , "No"'
read -r answer
case $answer in
'Yass!') echo "Goody! mykeyboardendshere";SUCCESS=y;;

View File

@ -1,6 +1,6 @@
#!/bin/bash
#
#### $$VERSION$$ v0.52-0-gdb7b19f
#### $$VERSION$$ v0.60-0-gf5162e2
# shellcheck disable=SC2016
#
# Easy Versioning in git:
@ -40,7 +40,10 @@ unset IFS
VERSION="$(git describe --tags --long)"
echo "Update files to version $VERSION ..."
for file in * doc/*
FILES="* doc/*"
[ "$1" != "" ] && FILES="$*"
for file in $FILES
do
[ ! -f "$file" ] && continue
#[ "$file" == "version" ] && continue