Merge pull request #90 from topkecleon/develop

Prepare for Version 0.7 Release
This commit is contained in:
Kay Marquardt 2019-04-30 15:51:40 +02:00 committed by GitHub
commit 8883cc9028
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 2255 additions and 663 deletions

4
.gitignore vendored
View File

@ -1,7 +1,9 @@
*~
/.github/
/count
/token
*.save
*.log
/JSON.sh/*
/JSON.sh/
/tmp-bot-bash/
/dist/

102
README.html Normal file
View File

@ -0,0 +1,102 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<title>Bashbot README</title>
<style type="text/css">code{white-space: pre;}</style>
</head>
<body>
<div id="header">
<h1 class="title">Bashbot README</h1>
</div>
<h1 id="bashbot">bashbot</h1>
<p>A Telegram bot written in bash.</p>
<p>Written by Drew (<span class="citation">@topkecleon</span>), Daniil Gentili (<span class="citation">@danogentili</span>), and Kay M (<span class="citation">@gnadelwartz</span>).</p>
<p>Contributions by JuanPotato, BigNerd95, TiagoDanin, and iicc1.</p>
<p>Released to the public domain wherever applicable. Elsewhere, consider it released under the <a href="http://www.wtfpl.net/txt/copying/">WTFPLv2</a>.</p>
<h2 id="prerequisites">Prerequisites</h2>
<p>Depends on <a href="http://github.com/tmux/tmux">tmux</a>. Uses <a href="http://github.com/dominictarr/JSON.sh">JSON.sh</a>.</p>
<p>Most complete <a href="doc/4_expert.md#Bashbot-UTF-8-Support">UTF-8 support for bashbot</a> is availible if phyton is installed (optional).</p>
<p>Bashbot <a href="https://github.com/topkecleon/telegram-bot-bash">Documentation</a> and <a href="https://github.com/topkecleon/telegram-bot-bash/releases">Downloads</a> are availible on www.github.com</p>
<h2 id="documentation">Documentation</h2>
<ul>
<li><a href="https://core.telegram.org/bots">Introdution to Telegram Bots</a>
<ul>
<li><a href="https://core.telegram.org/bots#3-how-do-i-create-a-bot">One Bot to rule them all</a></li>
<li><a href="https://core.telegram.org/bots#commands">Bot commands</a></li>
</ul></li>
<li><a href="doc/0_install.md">Install Bashbot</a>
<ul>
<li>Install release</li>
<li>Install from githup</li>
<li>Update Bashbot</li>
<li>Notes on Updates</li>
</ul></li>
<li><a href="doc/1_firstbot.md">Create a new Telegram Bot with botfather</a></li>
<li><a href="doc/2_usage.md">Getting Started</a>
<ul>
<li>Managing your Bot</li>
<li>Recieve data</li>
<li>Send messages</li>
<li>Send files, locations, keyboards</li>
</ul></li>
<li><a href="doc/3_advanced.md">Advanced Features</a>
<ul>
<li>Access Control</li>
<li>Interactive Chats</li>
<li>Background Jobs</li>
<li>Inline queries</li>
</ul></li>
<li><a href="doc/4_expert.md">Expert Use</a>
<ul>
<li>Handling UTF-8 character sets</li>
<li>Run as other user or system service</li>
<li>Scedule bashbot from Cron</li>
</ul></li>
<li><a href="doc/5_practice.md">Best Practices</a>
<ul>
<li>Customize commands.sh</li>
<li>Seperate logic from commands</li>
<li>Test your Bot with shellcheck</li>
</ul></li>
<li><a href="doc/6_reference.md">Bashbot function reference</a></li>
<li><a href="doc/7_develop.md">Deveoper Notess</a>
<ul>
<li>Setup your environment</li>
<li>Test, Add, Push changes</li>
<li>Prepare a new version</li>
<li>Bashbot testsuite</li>
</ul></li>
<li><a href="doc/8_custom.md">Customize bashbot environment</a></li>
<li><a href="examples/README.md">Examples</a></li>
</ul>
<h2 id="security-considerations">Security Considerations</h2>
<p>Running a Telegram Bot means it is connected to the public and you never know whats send to your Bot.</p>
<p>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: bashs quoting hell and globbing. <a href="https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells">Implications of wrong quoting</a></p>
<p>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,</p>
<p>A powerful tool to improve your scripts robustness is <code>shellcheck</code>. You can <a href="https://www.shellcheck.net/">use it online</a> or <a href="https://github.com/koalaman/shellcheck#installing">install shellcheck locally</a>. All bashbot scripts are checked by shellcheck.</p>
<h3 id="run-your-bot-as-a-restricted-user">Run your Bot as a restricted user</h3>
<p><strong>I recommend to run your bot as a user, with almost no access rights.</strong> 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.</p>
<p><strong>Never run your Bot as root, this is the most dangerous you can do!</strong> Usually the user nobody has almost no rights on Unix/Linux systems. See <a href="doc/4_expert.md">Expert use</a> on how to run your Bot as an other user.</p>
<h3 id="secure-your-bot-installation">Secure your Bot installation</h3>
<p><strong>Your Bot configuration must no be readable from other users.</strong> Everyone who can read your Bots token can act as your Bot and has access to all chats your Bot is in!</p>
<p>Everyone with read access to your Bot files can extract your Bots data. Especially your Bot Token in <code>token</code> 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 <code>count</code> and <code>tmp-bot-bash</code> only, all other files must be write protected.</p>
<p>To set access rights for your bashbot installation to a reasonable default run <code>sudo ./bashbot.sh init</code> after every update or change to your installation directory.</p>
<h3 id="is-this-bot-insecure">Is this Bot insecure?</h3>
<p>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 …</p>
<h3 id="why-bash-and-not-the-much-better-xyz">Why Bash and not the much better xyz?</h3>
<p>Well, thats a damn good question … may be because Im an Unix/Linux admin from stone age. Nevertheless there are more reasons from my side:</p>
<ul>
<li>bashbot will run everywhere where bash is availible, from ebedded linux to mainframe</li>
<li>easy to integrate with other shell script, e.g. for sending system message / health status</li>
<li>no need to install or learn a new programming language, library or framework</li>
<li>no database, not event driven, not OO …</li>
</ul>
<p><span class="citation">@Gnadelwartz</span></p>
<h2 id="thats-it">Thats it!</h2>
<p>If you feel that theres something missing or if you found a bug, feel free to submit a pull request!</p>
<h4 id="version-v0.7-rc1-0-g8279bdb"><br /><span class="math display"><em>V</em><em>E</em><em>R</em><em>S</em><em>I</em><em>O</em><em>N</em></span><br /> v0.7-rc1-0-g8279bdb</h4>
</body>
</html>

View File

@ -16,24 +16,15 @@ Most complete [UTF-8 support for bashbot](doc/4_expert.md#Bashbot-UTF-8-Support)
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
2. [Download latest release](https://github.com/topkecleon/telegram-bot-bash/releases) archive from github and extract all files.
As an alternative you can clone the github repository to get the latest, but possible unstable improvements.
```
git clone https://github.com/topkecleon/telegram-bot-bash
```
3. Go to directory ```telegram-bot-bash```, run ```./bashbot.sh init``` and follow the instructions. At this point you are asked for your Bots token given by botfather.
## Update bashbot
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
## Documentation
* [Introdution to Telegram Bots](https://core.telegram.org/bots)
* [One Bot to rule them all](https://core.telegram.org/bots#3-how-do-i-create-a-bot)
* [Bot commands](https://core.telegram.org/bots#commands)
* [Install Bashbot](doc/0_install.md)
* Install release
* Install from githup
* Update Bashbot
* Notes on Updates
* [Create a new Telegram Bot with botfather](doc/1_firstbot.md)
* [Getting Started](doc/2_usage.md)
* Managing your Bot
@ -54,23 +45,13 @@ Bashbot [Documentation](https://github.com/topkecleon/telegram-bot-bash) and [Do
* Seperate logic from commands
* Test your Bot with shellcheck
* [Bashbot function reference](doc/6_reference.md)
* [Notes for bashbot developers](doc/7_develop.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" ]'
* [Deveoper Notess](doc/7_develop.md)
* Setup your environment
* Test, Add, Push changes
* Prepare a new version
* Bashbot testsuite
* [Customize bashbot environment](doc/8_custom.md)
* [Examples](examples/README.md)
## Security Considerations
Running a Telegram Bot means it is connected to the public and you never know whats send to your Bot.
@ -98,8 +79,18 @@ To set access rights for your bashbot installation to a reasonable default run `
### Is this Bot insecure?
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 ...
### Why Bash and not the much better xyz?
Well, thats a damn good question ... may be because I'm an Unix/Linux admin from stone age. Nevertheless there are more reasons from my side:
- bashbot will run everywhere where bash is availible, from ebedded linux to mainframe
- easy to integrate with other shell script, e.g. for sending system message / health status
- no need to install or learn a new programming language, library or framework
- no database, not event driven, not OO ...
@Gnadelwartz
## 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.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,170 +1,133 @@
bashbot
-------
# bashbot
A Telegram bot written in bash.
Written by Drew (@topkecleon), Daniil Gentili (@danogentili), and Kay M
Written by Drew (@topkecleon), Daniil Gentili (@danogentili), and Kay M
(@gnadelwartz).
Contributions by JuanPotato, BigNerd95, TiagoDanin, and iicc1.
Released to the public domain wherever applicable. Elsewhere, consider
it released under the http://www.wtfpl.net/txt/copying/[WTFPLv2].
Released to the public domain wherever applicable.
Elsewhere, consider it released under the
[WTFPLv2](http://www.wtfpl.net/txt/copying/).
Prerequisites
~~~~~~~~~~~~~
## Prerequisites
Depends on [tmux](http://github.com/tmux/tmux).
Uses [JSON.sh](http://github.com/dominictarr/JSON.sh).
Depends on http://github.com/tmux/tmux[tmux]. Uses
http://github.com/dominictarr/JSON.sh[JSON.sh].
Most complete [UTF-8 support for
bashbot](doc/4_expert.md#Bashbot-UTF-8-Support) is availible if phyton is
installed (optional).
Most complete link:doc/4_expert.md#Bashbot-UTF-8-Support[UTF-8 support
for bashbot] 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
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
## Documentation
* [Introdution to Telegram Bots](https://core.telegram.org/bots)
* [One Bot to rule them
all](https://core.telegram.org/bots#3-how-do-i-create-a-bot)
* [Bot commands](https://core.telegram.org/bots#commands)
* [Install Bashbot](doc/0_install.md)
* Install release
* Install from githup
* Update Bashbot
* Notes on Updates
* [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)
* [Deveoper Notess](doc/7_develop.md)
* Setup your environment
* Test, Add, Push changes
* Prepare a new version
* Bashbot testsuite
* [Customize bashbot environment](doc/8_custom.md)
* [Examples](examples/README.md)
Install bashbot
~~~~~~~~~~~~~~~
## Security Considerations
Running a Telegram Bot means it is connected to the public and you never know
whats send to your Bot.
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
2. https://github.com/topkecleon/telegram-bot-bash/releases[Download
latest release] archive from github and extract all files.
+
As an alternative you can clone the github repository to get the latest,
but possible unstable improvements.
+
....
git clone https://github.com/topkecleon/telegram-bot-bash
....
3. Go to directory `telegram-bot-bash`, run `./bashbot.sh init` and
follow the instructions. At this point you are asked for your Bots token
given by botfather.
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-o
f-forgetting-to-quote-a-variable-in-bash-posix-shells)
Update bashbot
~~~~~~~~~~~~~~
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',
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
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.
Documentation
~~~~~~~~~~~~~
### Run your Bot as a restricted user
**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.
* 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
* link:doc/4_expert.md[Expert Use]
** Handling UTF-8 character sets
** Run as other user or system service
** Scedule bashbot from Cron
* link:doc/5_practice.md[Best Practices]
** Customize commands.sh
** Seperate logic from commands
** Test your Bot with shellcheck
* link:doc/6_reference.md[Bashbot function reference]
* link:doc/7_develop.md[Notes for bashbot developers]
**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.
Note on Keyboards
~~~~~~~~~~~~~~~~~
### Secure your Bot installation
**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!
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.
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.
_Example Keyboards_:
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.
* 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" ]'
### Is this Bot insecure?
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 ...
Security Considerations
~~~~~~~~~~~~~~~~~~~~~~~
### Why Bash and not the much better xyz?
Well, thats a damn good question ... may be because I'm an Unix/Linux admin
from stone age. Nevertheless there are more reasons from my side:
Running a Telegram Bot means it is connected to the public and you never
know whats send to your Bot.
- bashbot will run everywhere where bash is availible, from ebedded linux to
mainframe
- easy to integrate with other shell script, e.g. for sending system message /
health status
- no need to install or learn a new programming language, library or framework
- no database, not event driven, not OO ...
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.
https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells[Implications
of wrong quoting]
@Gnadelwartz
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',
## That's it!
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.
If you feel that there's something missing or if you found a bug, feel free to
submit a pull request!
Run your Bot as a restricted user
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*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 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
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*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!
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?
^^^^^^^^^^^^^^^^^^^^^
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!
latexmath:[\[VERSION\]] v0.62-0-g5d5dbae
++++++++++++++++++++++++++++++++++++++++
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,7 +1,7 @@
#!/bin/sh
# description: Start or stop telegram-bash-bot
#
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# shellcheck disable=SC2009
# shellcheck disable=SC2181
@ -69,12 +69,16 @@ case "$1" in
$0 stop; $0 start
RETVAL=$?
;;
'restartback')
$0 suspendback; $0 resumeback
RETVAL=$?
;;
'suspendback'|'resumeback'|'killback')
$runcmd "$start $1"
RETVAL=$?
;;
*)
echo "Usage: $0 { start | stop | restart | reload | suspendback | resumeback | killback }"
echo "Usage: $0 { start | stop | restart | reload | restartback | suspendback | resumeback | killback }"
RETVAL=1
;;
esac

View File

@ -1,4 +1,6 @@
#!/bin/bash
# file: bashbot.sh
# do not edit, this file will be overwritten on update
# bashbot, the Telegram bot written in bash.
# Written by Drew (@topkecleon) and Daniil Gentili (@danogentili), KayM (@gnadelwartz).
@ -10,13 +12,13 @@
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
#
# Exit Codes:
# - 0 sucess (hopefully)
# - 1 can't change to dir
# - 2 can't write to tmp, count or token
# - 3 user / command not found
# - 3 user / command / file not found
# - 4 unkown command
# - 5 cannot connect to telegram bot
@ -29,22 +31,27 @@ if [ -t 1 ] && [ "$TERM" != "" ]; then
NC='\e[0m'
fi
# get location of bashbot.sh an change to bashbot dir
SCRIPT="./$(basename "$0")"
# get location and name of bashbot.sh
SCRIPT="$0"
SCRIPTDIR="$(dirname "$0")"
RUNUSER="${USER}" # USER is overwritten by bashbot array, $USER may not work later on...
MODULEDIR="${SCRIPTDIR}/modules"
if [ "$1" != "source" ] && ! cd "${SCRIPTDIR}" ; then
echo -e "${RED}ERROR: Can't change to ${SCRIPTDIR} ...${NC}"
RUNDIR="${SCRIPTDIR}"
[ "${RUNDIR}" = "${SCRIPTDIR}" ] && SCRIPT="./$(basename "${SCRIPT}")"
RUNUSER="${USER}" # USER is overwritten by bashbot array
if [ "$1" != "source" ] && ! cd "${RUNDIR}" ; then
echo -e "${RED}ERROR: Can't change to ${RUNDIR} ...${NC}"
exit 1
fi
if [ ! -w "." ]; then
echo -e "${ORANGE}WARNING: ${SCRIPTDIR} is not writeable!${NC}"
echo -e "${ORANGE}WARNING: ${RUNDIR} is not writeable!${NC}"
ls -ld .
fi
TOKENFILE="./token"
TOKENFILE="${BASHBOT_ETC:-.}/token"
if [ ! -f "${TOKENFILE}" ]; then
if [ "${CLEAR}" = "" ] && [ "$1" != "init" ]; then
echo "Running headless, run ${SCRIPT} init first!"
@ -58,7 +65,9 @@ if [ ! -f "${TOKENFILE}" ]; then
fi
fi
JSONSHFILE="JSON.sh/JSON.sh"
JSONSHFILE="${BASHBOT_JSONSH:-${RUNDIR}/JSON.sh/JSON.sh}"
[[ "${JSONSHFILE}" != *"/JSON.sh" ]] && echo -e "${RED}ERROR: \"${JSONSHFILE}\" ends not with \"JSONS.sh\".${NC}" && exit 3
if [ ! -f "${JSONSHFILE}" ]; then
echo "Seems to be first run, Downloading ${JSONSHFILE}..."
mkdir "JSON.sh" 2>/dev/null;
@ -66,7 +75,7 @@ if [ ! -f "${JSONSHFILE}" ]; then
chmod +x "${JSONSHFILE}"
fi
BOTADMIN="./botadmin"
BOTADMIN="${BASHBOT_ETC:-.}/botadmin"
if [ ! -f "${BOTADMIN}" ]; then
if [ "${CLEAR}" = "" ]; then
echo "Running headless, set botadmin to AUTO MODE!"
@ -81,13 +90,13 @@ if [ ! -f "${BOTADMIN}" ]; then
fi
fi
BOTACL="./botacl"
BOTACL="${BASHBOT_ETC:-.}/botacl"
if [ ! -f "${BOTACL}" ]; then
echo -e "${ORANGE}Create empty ${BOTACL} file.${NC}"
echo "" >"${BOTACL}"
fi
TMPDIR="./tmp-bot-bash"
TMPDIR="${BASHBOT_VAR:-.}/data-bot-bash"
if [ ! -d "${TMPDIR}" ]; then
mkdir "${TMPDIR}"
elif [ ! -w "${TMPDIR}" ]; then
@ -97,7 +106,7 @@ elif [ ! -w "${TMPDIR}" ]; then
exit 2
fi
COUNTFILE="./count"
COUNTFILE="${BASHBOT_VAR:-.}/count"
if [ ! -f "${COUNTFILE}" ]; then
echo "" >"${COUNTFILE}"
elif [ ! -w "${COUNTFILE}" ]; then
@ -107,7 +116,7 @@ elif [ ! -w "${COUNTFILE}" ]; then
exit 2
fi
COMMANDS="./commands.sh"
COMMANDS="${BASHBOT_ETC:-.}/commands.sh"
if [ "$1" != "source" ]; then
if [ ! -f "${COMMANDS}" ] || [ ! -r "${COMMANDS}" ]; then
${CLEAR}
@ -123,7 +132,6 @@ fi
BOTTOKEN="$(cat "${TOKENFILE}")"
URL='https://api.telegram.org/bot'$BOTTOKEN
MSG_URL=$URL'/sendMessage'
LEAVE_URL=$URL'/leaveChat'
KICK_URL=$URL'/kickChatMember'
@ -143,125 +151,58 @@ ME_URL=$URL'/getMe'
DELETE_URL=$URL'/deleteMessage'
GETMEMBER_URL=$URL'/getChatMember'
FILE_URL='https://api.telegram.org/file/bot'$BOTTOKEN'/'
UPD_URL=$URL'/getUpdates?offset='
GET_URL=$URL'/getFile'
OFFSET=0
declare -A USER MESSAGE URLS CONTACT LOCATION CHAT FORWARD REPLYTO
GETFILE_URL=$URL'/getFile'
unset USER
declare -A BOTSENT USER MESSAGE URLS CONTACT LOCATION CHAT FORWARD REPLYTO VENUE
export BOTSENT USER MESSAGE URLS CONTACT LOCATION CHAT FORWARD REPLYTO VENUE
send_message() {
local text arg keyboard file lat long title address sent
[ "$2" = "" ] && return 1
local chat="$1"
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="${text// mynewlinestartshere /$'\r\n'}"
no_keyboard="$(echo "$2" | sed '/mykeyboardendshere/!d;s/.*mykeyboardendshere.*/mykeyboardendshere/')"
keyboard="$(echo "$2" | sed '/mykeyboardstartshere /!d;s/.*mykeyboardstartshere //g;s/ myfilelocationstartshere.*//g;s/ mylatstartshere.*//g;s/ mylongstartshere.*//g;s/ mytitlestartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
file="$(echo "$2" | sed '/myfilelocationstartshere /!d;s/.*myfilelocationstartshere //g;s/ mykeyboardstartshere.*//g;s/ mylatstartshere.*//g;s/ mylongstartshere.*//g;s/ mytitlestartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
lat="$(echo "$2" | sed '/mylatstartshere /!d;s/.*mylatstartshere //g;s/ mykeyboardstartshere.*//g;s/ myfilelocationstartshere.*//g;s/ mylongstartshere.*//g;s/ mytitlestartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
long="$(echo "$2" | sed '/mylongstartshere /!d;s/.*mylongstartshere //g;s/ mykeyboardstartshere.*//g;s/ myfilelocationstartshere.*//g;s/ mylatstartshere.*//g;s/ mytitlestartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
title="$(echo "$2" | sed '/mytitlestartshere /!d;s/.*mylongstartshere //g;s/ mykeyboardstartshere.*//g;s/ myfilelocationstartshere.*//g;s/ mylatstartshere.*//g;s/ myaddressstartshere.*//g;s/ mykeyboardendshere.*//g')"
address="$(echo "$2" | sed '/myaddressstartshere /!d;s/.*mylongstartshere //g;s/ mykeyboardstartshere.*//g;s/ myfilelocationstartshere.*//g;s/ mylatstartshere.*//g;s/ mytitlestartshere.*//g;s/ mykeyboardendshere.*//g')"
}
if [ "$no_keyboard" != "" ]; then
echo "remove_keyboard $chat $text" > ${TMPDIR:-.}/prova
remove_keyboard "$chat" "$text"
sent=y
fi
if [ "$keyboard" != "" ]; then
if [[ "$keyboard" != *"["* ]]; then # pre 0.60 style
keyboard="[ ${keyboard//\" \"/\" \] , \[ \"} ]"
fi
send_keyboard "$chat" "$text" "$keyboard"
sent=y
fi
if [ "$file" != "" ]; then
send_file "$chat" "$file" "$text"
sent=y
fi
if [ "$lat" != "" ] && [ "$long" != "" ] && [ "$address" = "" ] && [ "$title" = "" ]; then
send_location "$chat" "$lat" "$long"
sent=y
fi
if [ "$lat" != "" ] && [ "$long" != "" ] && [ "$address" != "" ] && [ "$title" != "" ]; then
send_venue "$chat" "$lat" "$long" "$title" "$address"
sent=y
fi
if [ "$sent" != "y" ];then
send_text "$chat" "$text"
fi
}
send_text() {
case "$2" in
html_parse_mode*)
send_html_message "$1" "${2//html_parse_mode}"
;;
markdown_parse_mode*)
send_markdown_message "$1" "${2//markdown_parse_mode}"
;;
*)
send_normal_message "$1" "$2"
;;
esac
}
send_normal_message() {
text="$2"
until [ "$(echo -n "$text" | wc -m)" -eq "0" ]; do
res="$(curl -s "$MSG_URL" -d "chat_id=$1" --data-urlencode "text=${text:0:4096}")"
local text="${2}"
until [ -z "${text}" ]; do
sendJson "${1}" '"text":"'"${text:0:4096}"'"' "${MSG_URL}"
text="${text:4096}"
done
}
send_markdown_message() {
text="$2"
until [ "$(echo -n "$text" | wc -m)" -eq "0" ]; do
res="$(curl -s "$MSG_URL" -d "chat_id=$1" --data-urlencode "text=${text:0:4096}" -d "parse_mode=markdown" -d "disable_web_page_preview=true")"
local text="${2}"
until [ -z "${text}" ]; do
sendJson "${1}" '"text":"'"${text:0:4096}"'","parse_mode":"markdown"' "${MSG_URL}"
text="${text:4096}"
done
}
send_html_message() {
text="$2"
until [ "$(echo -n "$text" | wc -m)" -eq "0" ]; do
res="$(curl -s "$MSG_URL" -d "chat_id=$1" --data-urlencode "text=${text:0:4096}" -d "parse_mode=html")"
local text="${2}"
until [ -z "${text}" ]; do
sendJson "${1}" '"text":"'"${text:0:4096}"'","parse_mode":"html"' "${MSG_URL}"
text="${text:4096}"
done
}
delete_message() {
res="$(curl -s "$DELETE_URL" -F "chat_id=$1" -F "message_id=$2")"
sendJson "${1}" 'message_id: '"${2}"'' "${DELETE_URL}"
}
# usage: status="$(get_chat_member_status "chat" "user")"
get_chat_member_status() {
curl -s "$GETMEMBER_URL" -F "chat_id=$1" -F "user_id=$2" | "./${JSONSHFILE}" -s -b -n | sed -n -e '/\["result","status"\]/ s/.*\][ \t]"\(.*\)"$/\1/p'
sendJson "$1" 'user_id: '"$2"'' "$GETMEMBER_URL"
JsonGetString '"result","status"' <<< "$res"
}
kick_chat_member() {
res="$(curl -s "$KICK_URL" -F "chat_id=$1" -F "user_id=$2")"
sendJson "$1" 'user_id: '"$2"'' "$KICK_URL"
}
unban_chat_member() {
res="$(curl -s "$UNBAN_URL" -F "chat_id=$1" -F "user_id=$2")"
sendJson "$1" 'user_id: '"$2"'' "$UNBAN_URL"
}
leave_chat() {
res="$(curl -s "$LEAVE_URL" -F "chat_id=$1")"
sendJson "$1" "" "$LEAVE_URL"
}
user_is_creator() {
@ -294,78 +235,77 @@ user_is_allowed() {
}
answer_inline_query() {
case "$2" in
local JSON
case "${2}" in
"article")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","title":"'$3'","message_text":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","title":"'$3'","message_text":"'$4'"}]'
;;
"photo")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","photo_url":"'$3'","thumb_url":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","photo_url":"'$3'","thumb_url":"'$4'"}]'
;;
"gif")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","gif_url":"'$3'", "thumb_url":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","gif_url":"'$3'", "thumb_url":"'$4'"}]'
;;
"mpeg4_gif")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","mpeg4_url":"'$3'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","mpeg4_url":"'$3'"}]'
;;
"video")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","video_url":"'$3'","mime_type":"'$4'","thumb_url":"'$5'","title":"'$6'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","video_url":"'$3'","mime_type":"'$4'","thumb_url":"'$5'","title":"'$6'"}]'
;;
"audio")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","audio_url":"'$3'","title":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","audio_url":"'$3'","title":"'$4'"}]'
;;
"voice")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","voice_url":"'$3'","title":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","voice_url":"'$3'","title":"'$4'"}]'
;;
"document")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","title":"'$3'","caption":"'$4'","document_url":"'$5'","mime_type":"'$6'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","title":"'$3'","caption":"'$4'","document_url":"'$5'","mime_type":"'$6'"}]'
;;
"location")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","latitude":"'$3'","longitude":"'$4'","title":"'$5'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","latitude":"'$3'","longitude":"'$4'","title":"'$5'"}]'
;;
"venue")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","latitude":"'$3'","longitude":"'$4'","title":"'$5'","address":"'$6'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","latitude":"'$3'","longitude":"'$4'","title":"'$5'","address":"'$6'"}]'
;;
"contact")
InlineQueryResult='[{"type":"'$2'","id":"'$RANDOM'","phone_number":"'$3'","first_name":"'$4'"}]'
JSON='[{"type":"'$2'","id":"'$RANDOM'","phone_number":"'$3'","first_name":"'$4'"}]'
;;
# Cached media stored in Telegram server
"cached_photo")
InlineQueryResult='[{"type":"photo","id":"'$RANDOM'","photo_file_id":"'$3'"}]'
JSON='[{"type":"photo","id":"'$RANDOM'","photo_file_id":"'$3'"}]'
;;
"cached_gif")
InlineQueryResult='[{"type":"gif","id":"'$RANDOM'","gif_file_id":"'$3'"}]'
JSON='[{"type":"gif","id":"'$RANDOM'","gif_file_id":"'$3'"}]'
;;
"cached_mpeg4_gif")
InlineQueryResult='[{"type":"mpeg4_gif","id":"'$RANDOM'","mpeg4_file_id":"'$3'"}]'
JSON='[{"type":"mpeg4_gif","id":"'$RANDOM'","mpeg4_file_id":"'$3'"}]'
;;
"cached_sticker")
InlineQueryResult='[{"type":"sticker","id":"'$RANDOM'","sticker_file_id":"'$3'"}]'
JSON='[{"type":"sticker","id":"'$RANDOM'","sticker_file_id":"'$3'"}]'
;;
"cached_document")
InlineQueryResult='[{"type":"document","id":"'$RANDOM'","title":"'$3'","document_file_id":"'$4'"}]'
JSON='[{"type":"document","id":"'$RANDOM'","title":"'$3'","document_file_id":"'$4'"}]'
;;
"cached_video")
InlineQueryResult='[{"type":"video","id":"'$RANDOM'","video_file_id":"'$3'","title":"'$4'"}]'
JSON='[{"type":"video","id":"'$RANDOM'","video_file_id":"'$3'","title":"'$4'"}]'
;;
"cached_voice")
InlineQueryResult='[{"type":"voice","id":"'$RANDOM'","voice_file_id":"'$3'","title":"'$4'"}]'
JSON='[{"type":"voice","id":"'$RANDOM'","voice_file_id":"'$3'","title":"'$4'"}]'
;;
"cached_audio")
InlineQueryResult='[{"type":"audio","id":"'$RANDOM'","audio_file_id":"'$3'"}]'
JSON='[{"type":"audio","id":"'$RANDOM'","audio_file_id":"'$3'"}]'
;;
esac
res="$(curl -s "$INLINE_QUERY" -F "inline_query_id=$1" -F "results=$InlineQueryResult")"
sendJson "" '"inline_query_id": '"${1}"', "results": '"${JSON}" "${INLINE_QUERY}"
}
old_send_keyboard() {
local chat="$1"
local text="$2"
local text='"text":"'"${2}"'"'
shift 2
local keyboard=init
OLDIFS=$IFS
@ -373,27 +313,48 @@ old_send_keyboard() {
for f in "$@" ;do [ "$f" != " " ] && keyboard="$keyboard, [\"$f\"]";done
IFS=$OLDIFS
keyboard=${keyboard/init, /}
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}")"
sendJson "${1}" "${text}"', "reply_markup": {"keyboard": [ '"${keyboard}"' ],"one_time_keyboard": true}' "$MSG_URL"
}
ISEMPTY="ThisTextIsEmptyAndWillBeDeleted"
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}")"
local text='"text":"'"${2}"'"'; [ "${2}" = "" ] && text='"text":"'"${ISEMPTY}"'"'
local one_time=', "one_time_keyboard":true' && [ "$4" != "" ] && one_time=""
sendJson "${1}" "${text}"', "reply_markup": {"keyboard": [ '"${3}"' ] '"${one_time}"'}' "$MSG_URL"
# '"text":"$2", "reply_markup": {"keyboard": [ ${3} ], "one_time_keyboard": true}'
}
remove_keyboard() {
local chat="$1"
local text="$2"
shift 2
res="$(curl -s "$MSG_URL" --header "content-type: multipart/form-data" -F "chat_id=$chat" -F "text=$text" -F "reply_markup={\"remove_keyboard\": true}")"
local text='"text":"'"${2}"'"'; [ "${2}" = "" ] && text='"text":"'"${ISEMPTY}"'"'
sendJson "${1}" "${text}"', "reply_markup": {"remove_keyboard":true}' "$MSG_URL"
#JSON='"text":"$2", "reply_markup": {"remove_keyboard":true}'
}
send_inline_keyboard() {
local text='"text":"'"${2}"'"'; [ "${2}" = "" ] && text='"text":"'"${ISEMPTY}"'"'
sendJson "${1}" "${text}"', "reply_markup": {"inline_keyboard": [ '"${3}"' ]}' "$MSG_URL"
# JSON='"text":"$2", "reply_markup": {"inline_keyboard": [ $3->[{"text":"text", "url":"url"}]<- ]}'
}
send_button() {
send_inline_keyboard "${1}" "${2}" '[ {"text":"'"${3}"'", "url":"'"${4}"'"}]'
}
# usage: sendJson "chat" "JSON" "URL"
sendJson(){
local chat="";
[ "${1}" != "" ] && chat='"chat_id":'"${1}"','
res="$(curl -s -d '{'"${chat} $2"'}' -X POST "${3}" \
-H "Content-Type: application/json" | "${JSONSHFILE}" -s -b -n )"
BOTSENT[OK]="$(JsonGetLine '"ok"' <<< "$res")"
BOTSENT[ID]="$(JsonGetValue '"result","message_id"' <<< "$res")"
[[ "${2}" = *"${ISEMPTY}"* ]] && delete_message "${1}" "${BOTSENT[ID]}"
}
get_file() {
[ "$1" = "" ] && return
echo "${FILE_URL}$(curl -s "${GET_URL}" -F "file_id=$1" | "./${JSONSHFILE}" -s -b -n | grep '\["result","file_path"\]' | cut -f 2 | cut -d '"' -f 2)"
local JSON='"file_id": '"${1}"
sendJson "" "${JSON}" "${GETFILE_URL}"
echo "${URL}/$(echo "${res}" | jsonGetString '"result","file_path"')"
}
send_file() {
@ -448,64 +409,34 @@ send_file() {
send_action() {
[ "$2" = "" ] && return
res="$(curl -s "$ACTION_URL" -F "chat_id=$1" -F "action=$2")"
sendJson "${1}" '"action": "'"${2}"'"' "$ACTION_URL"
}
send_location() {
[ "$3" = "" ] && return
res="$(curl -s "$LOCATION_URL" -F "chat_id=$1" -F "latitude=$2" -F "longitude=$3")"
sendJson "${1}" '"latitude": '"${2}"', "longitude": '"${3}"'' "$LOCATION_URL"
}
send_venue() {
local add=""
[ "$5" = "" ] && return
[ "$6" != "" ] add="-F \"foursquare_id=$6\""
res="$(curl -s "$VENUE_URL" -F "chat_id=$1" -F "latitude=$2" -F "longitude=$3" -F "title=$4" -F "address=$5")"
[ "$6" != "" ] && add=', "foursquare_id": '"$6"''
sendJson "${1}" '"latitude": '"${2}"', "longitude": '"${3}"', "address": "'"${5}"'", "title": "'"${4}"'"'"${add}" "$VENUE_URL"
}
forward_message() {
[ "$3" = "" ] && return
res="$(curl -s "$FORWARD_URL" -F "chat_id=$1" -F "from_chat_id=$2" -F "message_id=$3")"
sendJson "${1}" '"from_chat_id": '"${2}"', "message_id": '"${3}"'' "$FORWARD_URL"
}
forward() { # backward compatibility
forward_message "$@" || return
}
background() {
echo "${CHAT[ID]}:$2:$1" >"${TMPDIR:-.}/${copname}$2-back.cmd"
startproc "$1" "back-$2-"
}
startproc() {
killproc "$2"
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}"
}
checkback() {
checkproc "back-$1-"
}
checkproc() {
tmux ls | grep -q "$1${copname}"; res=$?; return $?
}
killback() {
killproc "back-$1-"
rm -f "${TMPDIR:-.}/${copname}$1-back.cmd"
}
killproc() {
local fifo="$1${copname}"
(tmux kill-session -t "${fifo}"; echo imprettydarnsuredatdisisdaendofdacmd>"${TMPDIR:-.}/${fifo}"; tmux kill-session -t "sendprocess_${fifo}"; rm -f -r "${TMPDIR:-.}/${fifo}")2>/dev/null
}
inproc() {
tmux send-keys -t "$copname" "${MESSAGE[0]} ${URLS[*]}
"
# returns true if function exist
_is_function()
{
[ "$(LC_ALL=C type -t "$1")" = "function" ]
}
process_updates() {
MAX_PROCESS_NUMBER=$(echo "$UPDATE" | sed '/\["result",[0-9]*\]/!d' | tail -1 | sed 's/\["result",//g;s/\].*//g')
@ -523,14 +454,14 @@ process_client() {
copname="$ME"_"${CHAT[ID]}"
source commands.sh
tmpcount="COUNT${CHAT[ID]}"
grep -q "$tmpcount" <"${COUNTFILE}" >/dev/null 2>&1 || echo "$tmpcount">>${COUNTFILE}
grep -q "$tmpcount" <"${COUNTFILE}" >/dev/null 2>&1 || echo "$tmpcount">>"${COUNTFILE}"
# To get user count execute bash bashbot.sh count
}
JsonGetString() {
sed -n -e '0,/\['"$1"'\]/ s/\['"$1"'\][ \t]"\(.*\)"$/\1/p'
}
JsonGetLine() {
sed -n -e '0,/\['"$1"'\]/ s/\['"$1"'\]\][ \t]//p'
sed -n -e '0,/\['"$1"'\]/ s/\['"$1"'\][ \t]//p'
}
JsonGetValue() {
sed -n -e '0,/\['"$1"'\]/ s/\['"$1"'\][ \t]\([0-9.,]*\).*/\1/p'
@ -591,10 +522,18 @@ process_message() {
URLS[VOICE]="$(get_file "$(JsonGetString '"result",'"${num}"',"message","voice","file_id"' <"$TMP")")"
# Contact
CONTACT[NUMBER]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","contact","phone_number"' <"$TMP")")"
CONTACT[USER_ID]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","contact","user_id"' <"$TMP")")"
CONTACT[FIRST_NAME]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","contact","first_name"' <"$TMP")")"
CONTACT[LAST_NAME]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","contact","last_name"' <"$TMP")")"
CONTACT[USER_ID]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","contact","user_id"' <"$TMP")")"
CONTACT[NUMBER]="$(JsonGetString '"result",'"${num}"',"message","contact","phone_number"' <"$TMP")"
CONTACT[VCARD]="$(JsonGetString '"result",'"${num}"',"message","contact","vcard"' <"$TMP")"
# vunue
VENUE[TITLE]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","venue","title"' <"$TMP")")"
VENUE[ADDRESS]="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","venue","address"' <"$TMP")")"
VENUE[LONGITUDE]="$(JsonGetValue '"result",'"${num}"',"message","venue","location","longitude"' <"$TMP")"
VENUE[LATITUDE]="$(JsonGetValue '"result",'"${num}"',"message","venue","location","latitude"' <"$TMP")"
VENUE[FOURSQUARE]="$(JsonGetString '"result",'"${num}"',"message","venue","foursquare_id"' <"$TMP")"
# Caption
CAPTION="$(JsonDecode "$(JsonGetString '"result",'"${num}"',"message","caption"' <"$TMP")")"
@ -605,10 +544,63 @@ process_message() {
NAME="$(echo "${URLS[*]}" | sed 's/.*\///g')"
rm "$TMP"
}
# main get updates loop, should never terminate
start_bot() {
local OFFSET=0
local mysleep="100" # ms
local addsleep="100"
local maxsleep="$(( ${BASHBOT_SLEEP:-5000} + 100 ))"
while true; do {
UPDATE="$(curl -s "$UPD_URL$OFFSET" | "${JSONSHFILE}")"
# Offset
OFFSET="$(echo "$UPDATE" | grep '\["result",[0-9]*,"update_id"\]' | tail -1 | cut -f 2)"
OFFSET=$((OFFSET+1))
if [ "$OFFSET" != "1" ]; then
mysleep="100"
if [ "$1" = "test" ]; then
process_updates "$1"
else
process_updates "$1" &
fi
fi
# adaptive sleep in ms rounded to next lower second
sleep "${mysleep%???}"; mysleep=$((mysleep+addsleep)); [ "${mysleep}" -gt "${maxsleep}" ] && mysleep="${maxsleep}"
}
done
}
# initialize bot environment, user and permissions
bot_init() {
# move tmpdir to datadir
local OLDTMP="${BASHBOT_VAR:-.}/tmp-bot-bash"
[ -d "${OLDTMP}" ] && { mv -n "${OLDTMP}/"* "${TMPDIR}"; rmdir "${OLDTMP}"; }
[[ "$(id -u)" -eq "0" ]] && RUNUSER="nobody"
echo -n "Enter User to run basbot [$RUNUSER]: "
read -r TOUSER
[ "$TOUSER" = "" ] && TOUSER="$RUNUSER"
if ! compgen -u "$TOUSER" >/dev/null 2>&1; then
echo -e "${RED}User \"$TOUSER\" not found!${NC}"
exit 3
else
echo "Adjusting user \"${TOUSER}\" files and permissions ..."
sed -i '/^[# ]*runas=/ s/runas=.*$/runas="'$TOUSER'"/' bashbot.rc
chown -R "$TOUSER" . ./*
chmod 711 .
chmod -R a-w ./*
chmod -R u+w "${COUNTFILE}" "${TMPDIR}" "${BOTADMIN}" ./*.log 2>/dev/null
chmod -R o-r,o-w "${COUNTFILE}" "${TMPDIR}" "${TOKENFILE}" "${BOTADMIN}" "${BOTACL}" 2>/dev/null
ls -la
fi
}
# get bot name
getBotName() {
res="$(curl -s "$ME_URL")"
echo "$res" | "./${JSONSHFILE}" -s -b -n | JsonGetString '"result","username"'
sendJson "" "" "$ME_URL"
JsonGetString '"result","username"' <<< "$res"
}
ME="$(getBotName)"
@ -622,7 +614,7 @@ if [ "$ME" = "" ]; then
fi
# use phyton JSON to decode JSON UFT-8, provide bash implementaion as fallback
if [ "${BASHDECODE}" != "yes" ] && which python >/dev/null 2>&1 ; then
if [ "${BASHBOT_DECODE}" != "" ] && which python >/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"))'
}
@ -635,9 +627,9 @@ else
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 ))"
local W1=$(( ( 0xd${BASH_REMATCH[2]} & 0x3ff) <<10 ))
local W2=$(( 0xd${BASH_REMATCH[3]} & 0x3ff ))
local U=$(( ( W1 | W2 ) + 0x10000 ))
remain="$(printf '\\U%8.8x' "${U}")${BASH_REMATCH[4]}${remain}"
out="${BASH_REMATCH[1]}"
done
@ -649,34 +641,40 @@ fi
# do not execute if read from other scripts
if [ "$1" != "source" ]; then
while [ "$1" = "startbot" ]; do {
UPDATE="$(curl -s "$UPD_URL$OFFSET" | ./${JSONSHFILE})"
# Offset
OFFSET="$(echo "$UPDATE" | grep '\["result",[0-9]*,"update_id"\]' | tail -1 | cut -f 2)"
OFFSET=$((OFFSET+1))
if [ "$OFFSET" != "1" ]; then
if [ "$2" = "test" ]; then
process_updates "$2"
else
process_updates "$2" &
fi
fi
}; done
##############
# internal options only for use from bashbot and developers
case "$1" in
"outproc")
"outproc") # forward output from interactive and jobs to chat
until [ "$line" = "imprettydarnsuredatdisisdaendofdacmd" ];do
line=""
read -r -t 10 line
[ "$line" != "" ] && [ "$line" != "imprettydarnsuredatdisisdaendofdacmd" ] && send_message "$2" "$line"
done <"${TMPDIR:-.}/$3"
rm -f -r "${TMPDIR:-.}/$3"
exit
;;
"startbot" )
start_bot "$2"
exit
;;
"source") # this should never arrive here
exit
;;
"init") # adjust users and permissions
bot_init
exit
;;
"attach")
tmux attach -t "$ME"
exit
;;
esac
###############
# "official" arguments as shown to users
case "$1" in
"count")
echo "A total of $(wc -l <"${COUNTFILE}") users used me."
exit
@ -686,7 +684,7 @@ if [ "$1" != "source" ]; then
echo "Sending the broadcast $* to $NUMCOUNT users."
[ "$NUMCOUNT" -gt "300" ] && sleep="sleep 0.5"
shift
while read -r f; do send_message "${f//COUNT}" "$*"; $sleep; done <"${COUNTFILE}"
while read -r f; do send_markdown_message "${f//COUNT}" "$*"; $sleep; done <"${COUNTFILE}"
;;
"start")
${CLEAR}
@ -695,25 +693,11 @@ if [ "$1" != "source" ]; then
echo "Tmux session name $ME" || echo -e "${RED}An error occurred while starting the bot. ${NC}"
send_markdown_message "${CHAT[ID]}" "*Bot started*"
;;
"init") # adjust users and permissions
[[ "$(id -u)" -eq "0" ]] && RUNUSER="nobody"
echo -n "Enter User to run basbot [$RUNUSER]: "
read -r TOUSER
[ "$TOUSER" = "" ] && TOUSER="$RUNUSER"
if ! compgen -u "$TOUSER" >/dev/null 2>&1; then
echo -e "${RED}User \"$TOUSER\" not found!${NC}"
exit 3
else
echo "Adjusting user \"${TOUSER}\" files and permissions ..."
sed -i '/^[# ]*runas=/ s/runas=.*$/runas="'$TOUSER'"/' bashbot.rc
chown -R "$TOUSER" . ./*
chmod 711 .
chmod -R a-w ./*
chmod -R u+w "${COUNTFILE}" "${TMPDIR}" "${BOTADMIN}" ./*.log 2>/dev/null
chmod -R o-r,o-w "${COUNTFILE}" "${TMPDIR}" "${TOKENFILE}" "${BOTADMIN}" "${BOTACL}" 2>/dev/null
ls -la
exit
fi
"kill")
${CLEAR}
tmux kill-session -t "$ME" &>/dev/null
send_markdown_message "${CHAT[ID]}" "*Bot stopped*"
echo -e "${GREEN}OK. Bot stopped successfully.${NC}"
;;
"background" | "resumeback")
${CLEAR}
@ -736,12 +720,6 @@ if [ "$1" != "source" ]; then
fi
done
;;
"kill")
${CLEAR}
tmux kill-session -t "$ME" &>/dev/null
send_markdown_message "${CHAT[ID]}" "*Bot stopped*"
echo -e "${GREEN}OK. Bot stopped successfully.${NC}"
;;
"killback" | "suspendback")
${CLEAR}
echo -e "${GREEN}Stopping background processes ...${NC}"
@ -763,16 +741,9 @@ if [ "$1" != "source" ]; then
less "README.txt"
exit
;;
"attach")
tmux attach -t "$ME"
;;
"source")
# this should never happen
echo "OK"
;;
*)
echo -e "${RED}${ME}: BAD REQUEST${NC}"
echo -e "${RED}Available arguments: outproc, count, broadcast, start, suspendback, resumeback, kill, killback, help, attach${NC}"
echo -e "${RED}Available arguments: start, kill, count, broadcast, help, suspendback, resumeback, killback${NC}"
exit 4
;;
esac

108
commands.sh Executable file → Normal file
View File

@ -1,14 +1,14 @@
#!/bin/bash
# Edit your commands in this file.
# file: commands.sh
# do not edit this file, instead place all your commands in mycommands.sh
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
#
# shellcheck disable=SC2154
# shellcheck disable=SC2034
SC2034="$CONTACT" # mute CONTACT not used ;-)
# adjust your language setting here, e.g.when run from other user or cron.
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment
@ -20,18 +20,18 @@ unset IFS
# set -f # if you are paranoid use set -f to disable globbing
if [ "$1" != "source" ]; then
# change Info anf Help to fit your needs
bashbot_info() {
send_markdown_message "${1}" 'This is bashbot, the Telegram bot written entirely in bash.
# to change the default info message overwrite bashbot_info in mycommands.sh
bashbot_info='This is bashbot, the Telegram bot written entirely in bash.
It features background tasks and interactive chats, and can serve as an interface for CLI programs.
It currently can send, recieve and forward messages, custom keyboards, photos, audio, voice, documents, locations and video files.
'
}
bashbot_help() {
send_markdown_message "${1}" '*Available commands*:
# to change the default help messages overwrite in mycommands.sh
bashbot_help='*Available commands*:
*• /start*: _Start bot and get this message_.
*• /help*: _Get this message_.
*• /info*: _Get shorter info message about this bot_.
*• /question*: _Start interactive chat_.
*• /cancel*: _Cancel any currently running interactive chats_.
@ -40,18 +40,18 @@ It currently can send, recieve and forward messages, custom keyboards, photos, a
Written by Drew (@topkecleon), Daniil Gentili (@danogentili) and KayM(@gnadelwartz).
Get the code in my [GitHub](http://github.com/topkecleon/telegram-bot-bash)
'
}
# some handy shortcuts, e.g.:
_is_botadmin() {
user_is_botadmin "${USER[ID]}"
}
_is_admin() {
user_is_admin "${CHAT[ID]}" "${USER[ID]}"
}
_is_allowed() { # $1 = resource
user_is_allowed "${USER[ID]}" "$1" "${CHAT[ID]}"
}
# load modules
# shellcheck source=./modules/aliases.sh
[ -r "${MODULEDIR:-.}/aliases.sh" ] && source "${MODULEDIR:-.}/aliases.sh"
# shellcheck source=./modules/background.sh
[ -r "${MODULEDIR:-.}/background.sh" ] && source "${MODULEDIR:-.}/background.sh"
# ... more modules here ...
# mycommands is the last "module" to source in
# shellcheck source=./commands.sh
[ -r "${BASHBOT_ETC:-.}/mycommands.sh" ] && source "${BASHBOT_ETC:-.}/mycommands.sh"
fi
if [ "$1" = "source" ];then
@ -62,6 +62,7 @@ if [ "$1" = "source" ];then
FILE_REGEX='/home/user/allowed/.*'
else
if ! tmux ls | grep -v send | grep -q "$copname"; then
# interactive running?
[ ! -z "${URLS[*]}" ] && {
curl -s "${URLS[*]}" -o "$NAME"
send_file "${CHAT[ID]}" "$NAME" "$CAPTION"
@ -93,69 +94,46 @@ else
if [[ "$iQUERY_MSG" = "web" ]]; then
answer_inline_query "$iQUERY_ID" "article" "GitHub" "http://github.com/topkecleon/telegram-bot-bash"
fi
fi &
fi & # note the & !
fi
case "$MESSAGE" in
'/question')
checkproc
if [ "$res" -gt 0 ] ; then
startproc "example/question"
else
send_normal_message "${CHAT[ID]}" "$MESSAGE already running ..."
fi
;;
'/run-notify')
myback="notify"; checkback "$myback"
if [ "$res" -gt 0 ] ; then
background "example/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
;;
################################################
# DEFAULT commands start here, edit messages only
'/info')
bashbot_info "${CHAT[ID]}"
# GLOBAL commands start here, edit messages only
'/info'*)
_markdown_message "${bashbot_info}"
;;
'/start')
'/start'*)
send_action "${CHAT[ID]}" "typing"
_is_botadmin && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
_is_botadmin && _markdown_message "You are *BOTADMIN*."
if _is_allowed "start" ; then
bot_help "${CHAT[ID]}"
_markdown_message "${bot_help}"
else
send_normal_message "${CHAT[ID]}" "You are not allowed to start Bot."
_message "You are not allowed to start Bot."
fi
;;
'/leavechat') # bot leave chat if user is admin in chat
'/help'*)
_markdown_message "${bot_help}"
;;
'/leavechat'*) # bot leave chat if user is admin in chat
if _is_admin ; then
send_markdown_message "${CHAT[ID]}" "*LEAVING CHAT...*"
leave_chat "${CHAT[ID]}"
_markdown_message "*LEAVING CHAT...*"
_leave
fi
;;
'/kickme')
kick_chat_member "${CHAT[ID]}" "${USER[ID]}"
unban_chat_member "${CHAT[ID]}" "${USER[ID]}"
'/kickme'*)
_kick_user "${USER[ID]}"
_unban_user "${USER[ID]}"
;;
'/cancel')
'/cancel'*)
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 [ "$res" -eq 0 ] ; then killproc && _message "Command canceled.";else _message "No command is currently running.";fi
;;
*) # forward input to interactive chat if running
if tmux ls | grep -v send | grep -q "$copname"; then inproc; fi
*) # forward other messages to optional dispatcher
_is_function startproc && if tmux ls | grep -v send | grep -q "$copname"; then inproc; fi # interactive running
_is_function mycommands && mycommands
;;
esac
fi

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bash
# this has to run once atfer git clone
# and every time we create new hooks
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
@ -11,7 +11,7 @@ cd "${GIT_DIR}/.." || exit 1
# create test environment
TESTENV="/tmp/bashbot.test$$"
mkdir "${TESTENV}"
cp -r * "${TESTENV}"
cp -r ./* "${TESTENV}"
cd "test" || exit 1
#set -e
@ -20,7 +20,7 @@ tests=0
passed=0
#all_tests=${__dirname:}
#echo PLAN ${#all_tests}
for test in $(find ./${pass}*-test.sh | sort -u) ;
for test in $(find ./*-test.sh | sort -u) ;
do
[ "${test}" = "test/all-tests.sh" ] && continue
[ ! -x "${test}" ] && continue
@ -49,6 +49,9 @@ else
find "${TESTENV}/"* ! -name '[a-z]-*' -delete
fi
echo "${passed} / ${tests}"
echo -e "${passed} / ${tests}\\n"
[ -d "${TESTENV}" ] && echo "Logfiles from run are in ${TESTENV}"
ls -ld /tmp/bashbot.test* 2>/dev/null && echo "Don not forget to deleted bashbot test files in /tmp!!"
exit ${exitcode}

28
dev/git-add.sh Executable file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env bash
# file: git-add.sh
#
# works together with git pre-push.sh and ADD all changed files since last push
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
GIT_DIR=$(git rev-parse --git-dir)
cd "$GIT_DIR/.." || exit 1
FILES="$(find ./* -newer .git/.lastpush)"
[ "${FILES}" = "" ] && echo "Noting changed since last push!" && exit
# run pre_commit on files
dev/hooks/pre-commit.sh
echo -n "Add files to repo: "
# shellcheck disable=SC2086
for file in ${FILES}
do
[ -d "${file}" ] && continue
echo -n "${file} "
done
git add .
echo "done."

View File

@ -1,5 +1,8 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
############
# NOTE: you MUST run install-hooks.sh again when updating this file!
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
@ -7,21 +10,19 @@ GIT_DIR=$(git rev-parse --git-dir)
cd "$GIT_DIR/.." || exit 1
export HOOKDIR="dev/hooks"
echo "Running pre-commit hook"
LASTPUSH='.git/.lastpush'
# if any command inside script returns error, exit and return that error
set -e
# let's fake failing test for now
echo "Running tests"
echo "Running pre-commit hook"
echo "............................"
unset IFS; set -f
# check for shellcheck
if which shellcheck >/dev/null 2>&1; then
echo "Test all scripts with shellcheck ..."
echo " Test all scripts with shellcheck ..."
else
echo "Error: shellcheck is not installed. Install shellcheck or delete $0"
exit 1
@ -29,14 +30,35 @@ fi
# run shellcheck before commit
set +f
FILES="$(find ./* -name '*.sh')"
FILES="$(find ./* -name '*.sh' | grep -v 'dist\/' )"
set -f
FILES="${FILES} $(sed '/^#/d' <"dev/shellcheck.files")"
if [ "$FILES" != "" ]; then
# shellcheck disable=SC2086
shellcheck -x ${FILES} || exit 1
echo "OK"
echo " OK"
else
# something went wrong
exit 1
fi
REMOTEVER="$(git ls-remote -t --refs 2>/dev/null | tail -1 | sed 's/.*\/v//')"
VERSION="$(git describe --tags | sed -e 's/-.*//' -e 's/v//')"
# LOCAL version must greater than latest REMOTE release version
if (( $(echo "${VERSION} > ${REMOTEVER}" | bc -l) )); then
# update version in bashbot files on push
set +f
[ -f "${LASTPUSH}" ] && LASTFILES="$(find ./* -newer "${LASTPUSH}")"
[ "${LASTFILES}" = "" ] && exit
echo -n " "
# shellcheck disable=SC2086
dev/version.sh ${LASTFILES} 2>/dev/null || exit 1
echo " OK"
else
echo "Error: local version ${VERSION} must be greater than latest release version."
echo "use \"git tag ...\" to create a local version greater than ${REMOTEVER}"
exit 1
fi

View File

@ -1,5 +1,8 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
############
# NOTE: you MUST run install-hooks.sh again when updating this file!
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
@ -7,28 +10,15 @@ GIT_DIR=$(git rev-parse --git-dir)
cd "$GIT_DIR/.." || exit 1
export HOOKDIR="dev/hooks"
REMOTEVER="$(git ls-remote -t --refs 2>/dev/null | tail -1 | sed 's/.*\/v//')"
VERSION="$(git describe --tags | sed -e 's/-.*//' -e 's/v//')"
echo "Running pre-push hook"
LASTPUSH='.git/.lastpush'
# if any command inside script returns error, exit and return that error
set -e
# let's fake failing test for now
echo "Running tests"
echo "Running pre-push hook"
echo "............................"
unset IFS; set -f
# LOCAL version must greater than latest REMOTE release version
if (( $(echo "${VERSION} > ${REMOTEVER}" | bc -l) )); then
# update version in bashbot files on push
dev/version.sh 2>/dev/null
else
echo "Error: local version ${VERSION} must be greater than latest release version."
echo "use \"git tag ...\" to create a local version greater than ${REMOTEVER}"
exit 1
fi
# note date of last push for version
touch "${LASTPUSH}"

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bash
# this has to run once atfer git clone
# and every time we create new hooks
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script

60
dev/make-dist.sh Executable file
View File

@ -0,0 +1,60 @@
#!/usr/bin/env bash
# this has to run once atfer git clone
# and every time we create new hooks
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
GIT_DIR=$(git rev-parse --git-dir)
cd "$GIT_DIR/.." || exit 1
VERSION="$(git describe --tags | sed -e 's/-[0-9].*//' -e 's/v//')"
DISTNAME="telegram-bot-bash"
DISTDIR="./dist/${DISTNAME}"
DISTFILES="bashbot.rc bashbot.sh commands.sh mycommands.sh doc examples modules LICENSE README.md README.txt README.html"
# run tests first!
for test in "dev/all-tests.sh"
do
if ! "${test}" ; then
echo "Test ${test} failed, can't create dist!"
exit 1
fi
done
# create dir for distribution and copy files
mkdir -p "${DISTDIR}" 2>/dev/null
# shellcheck disable=SC2086
cp -r ${DISTFILES} "${DISTDIR}"
cd "${DISTDIR}" || exit 1
# additional stuff
mv "commands.sh" "commands.sh.dist"
mv "mycommands.sh" "mycommands.sh.dist"
JSONSHFILE="JSON.sh/JSON.sh"
if [ ! -f "${JSONSHFILE}" ]; then
mkdir "JSON.sh" 2>/dev/null
curl -sL -o "${JSONSHFILE}" "https://cdn.jsdelivr.net/gh/dominictarr/JSON.sh/JSON.sh"
chmod +x "${JSONSHFILE}"
fi
# make html doc
mkdir html 2>/dev/null
cp README.html html/index.html
find doc -iname "*.md" -type f -exec sh -c 'pandoc -s -S -M "title=Bashobot Documentation - ${0%.md}.html" "${0}" -o "./html/$(basename ${0%.md}.html)"' {} \;
find examples -iname "*.md" -type f -exec sh -c 'pandoc -s -S -M "title=Bashobot Documentation - ${0%.md}.html" "${0}" -o "${0%.md}.html"' {} \;
find README.html html examples -iname "*.html" -type f -exec sh -c 'sed -i -E "s/href=\"(\.\.\/)*doc\//href=\"\1html\//g;s/href=\"(.*).md(#.*)*\"/href=\"\1.html\"/g" ${0}' {} \;
# create archive
cd .. || exit 1
zip -rq "${DISTNAME}-${VERSION}.zip" "${DISTNAME}"
tar -czf "${DISTNAME}-${VERSION}.tar.gz" "${DISTNAME}"
# shellcheck disable=SC2086
ls -ld ${DISTNAME}-${VERSION}.*

View File

@ -1,3 +1,3 @@
# list of additional files to check from shellcheck
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
bashbot.rc

View File

@ -1,6 +1,6 @@
#!/bin/bash
#
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# shellcheck disable=SC2016
#
# Easy Versioning in git:
@ -57,6 +57,7 @@ do
done
# try to compile README.txt
echo -n " README.txt" >&2
pandoc -f markdown -t asciidoc README.md | sed '/^\[\[/d' >README.txt
type -f pandoc >/dev/null && pandoc -s -S -M "title=Bashbot README" README.md >README.html
fold -s README.md >README.txt
echo " done."

67
doc/0_install.md Normal file
View File

@ -0,0 +1,67 @@
#### [Home](../README.md)
## 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
2. [Download latest release zip from github](https://github.com/topkecleon/telegram-bot-bash/releases) and extract all files.
3. Change into the directory ```telegram-bot-bash```
4. Create default commands with ```cp commands.sh.dist commands.sh; cp mycommands.sh.dist mycommands.sh```
5. Run ```./bashbot.sh init``` to setup the environment and enter your Bots token given by botfather.
Now your Bot is ready to start ...
**If you are new to Bot development read [Bots: An introduction for developers](https://core.telegram.org/bots)**
### Install from Github
As an alternative to download the zip files, you can clone the github repository to get the latest improvements/fixes.
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
2. Run ```git clone https://github.com/topkecleon/telegram-bot-bash.git```
3. Change into the directory ```telegram-bot-bash```
4. Run ``` test/ALL-tests.sh``` and if everthing finish OK ...
5. Run ```sudo ./bashbot.sh init``` to setup the environment and enter your Bots token given by botfather.
### Update bashbot
1. Go to the directory where you had installed bashbot, e.g.
* your $HOME directory
* /usr/local
2. [Download latest release zip from github](https://github.com/topkecleon/telegram-bot-bash/releases)
3. Extract all files to your existing bashbot dir
**Note: all files execpt 'mycommands.sh' and 'commands.sh' may overwritten!**
4. Run ```sudo ./bashbot.sh init``` to setup your environment after the update
### Notes on Updates
#### Location of tmp / data dir
From version 0.70 on the tmp dir is renamed to 'data-bot-bash' to reflect the fact that not only temporary files are stored. an existing 'tmp-bot-bash' will be automatically renamed after update.
From version 0.50 on the temporary files are no more placed in '/tmp'. instead a dedicated tmp dir is used.
#### Changes to send_keyboard in v0.6
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" ]'
#### [Next Create Bot](1_firstbot.md)
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,5 +1,8 @@
#### [Home](../README.md)
## Create a Telegram Bot with botfather
**[BotFather is the one bot to rule them all](https://core.telegram.org/bots#3-how-do-i-create-a-bot). It will help you create new bots and change settings for existing ones.** [Commands known by Botfather](https://core.telegram.org/bots#generating-an-authorization-token)
### Creating a new Bot
1. Message @botfather https://telegram.me/botfather with the following
text: `/newbot`
@ -59,7 +62,8 @@ group. This step is up to you actually.
13. @botfather replies with `Success! The new status is: DISABLED. /help`
#### [Prev Installation](0_install.md)
#### [Next Getting started](2_usage.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,9 +1,9 @@
#### [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.
The Bots standard commands are in ```commands.sh``` file. You must not add your commands to 'commands.sh', instead place them in ```mycommands.sh```, there you also find examples how to process messages and send out text. See [Best practices](5_practice.md) for more information.
Once you're done editing start the Bot with ```./bashbot.sh start```.
Once you're done with editing 'mycommands.sh' start the Bot with ```./bashbot.sh start```.
If some thing doesn't work as it should, debug with ```bash -x bashbot.sh```. To stop the Bot run ```./bashbot.sh kill```
To use the functions provided in this script in other scripts simply source bashbot: ```source bashbot.sh```
@ -37,7 +37,7 @@ 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}```: Current incoming messages
* ```${MESSAGE}```: Current message
* ```${MESSAGE[ID]}```: ID of current message
* ```$CAPTION```: Captions
* ```$REPLYTO```: Original message wich was replied to
@ -66,7 +66,7 @@ Evertime a Message is recieved, you can read incoming data using the following v
* ```${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```: This array contains documents, audio files, voice recordings and stickers as URL.
* ```${URLS[AUDIO]}```: Audio files
* ```${URLS[VIDEO]}```: Videos
* ```${URLS[PHOTO]}```: Photos (maximum quality)
@ -74,13 +74,20 @@ Evertime a Message is recieved, you can read incoming data using the following v
* ```${URLS[STICKER]}```: Stickers
* ```${URLS[DOCUMENT]}```: Any other file
* ```$CONTACT```: This array contains info about contacts sent in a chat.
* ```${CONTACT[ID]}```: User id
* ```${CONTACT[NUMBER]}```: Phone number
* ```${CONTACT[FIRST_NAME]}```: First name
* ```${CONTACT[LAST_NAME]}```: Last name
* ```${CONTACT[ID]}```: User id
* ```${CONTACT[VCARD]}```: User's complete Vcard
* ```$LOCATION```: This array contains info about locations sent in a chat.
* ```${LOCATION[LONGITUDE]}```: Longitude
* ```${LOCATION[LATITUDE]}```: Latitude
* ```$VENUE```: This array contains info about venue (a place) sent in a chat.
* ```${VENUE[TITLE]}```: Name of the place
* ```${VENUE[ADDRESS]}```: Address of the place
* ```${VENUE[LONGITUDE]}```: Longitude
* ```${VENUE[LATITUDE]}```: Latitude
* ```${VENUE[FOURSQUARE]}```: Fouresquare ID
## Usage of bashbot functions
@ -129,7 +136,7 @@ This function also allows a third parameter that disables additional function pa
```bash
send_message "${CHAT[ID]}" "lol" "safe"
```
More examples boutsend_message strings can be found in [Advanced Usage](3_advanced.md#Interactive-Chats)
**See also [Interactive chats](3_advanced.md#Interactive-Chats)**
#### Send files, locations, keyboards.
@ -155,9 +162,10 @@ Allowed values: typing for text messages, upload_photo for photos, record_video
```bash
send_action "${CHAT[ID]}" "action"
```
**See also [Bashbot function reference](6_reference.md#Interactive_Chats)**
#### [Prev Create Bot](1_firstbot.md)
#### [Next Advanced Usage](3_advanced.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -2,7 +2,7 @@
## Advanced Features
### Access control
Bashbot offers functions to check what Telegram capabilities like chat admin or chat creator the given user has:
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
@ -21,7 +21,7 @@ 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 addition you can check individual capabilities of users as defined in the ```./botacl``` file:
In addition you can check individual capabilities of users as you must define in the file ```./botacl```:
```bash
# file: botacl
# a user not listed here, will return false from 'user_is_allowed'
@ -44,10 +44,12 @@ In addition you can check individual capabilities of users as defined in the ```
*:start:*
*:*:98979695
```
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:
You must 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')
################################################
# GLOBAL commands start here, only edit messages
'/start'*)
user_is_botadmin "${USER[ID]}" && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
if user_is_allowed "${USER[ID]}" "start" "${CHAT[ID]}" ; then
bot_help "${CHAT[ID]}"
@ -56,10 +58,17 @@ you have to use the function ```user_is_allowed``` to check if a user has the ca
;;
esac
```
**See also [Bashbot User Access Control functions](6_reference.md#User-Access-Control)**
### Interactive Chats
To create interactive chats, write (or edit the exmaples/question.sh 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).
To create interactive chats, write *(or edit the 'exmaples/question.sh' script)* a bash *(or C or python)* script, make it executable
and then use the 'startproc' function to start the script.
The output of the script will be sent to the user and user input will be sent to the script.
To stop the script use the function 'killprog'
The output of the script will be processed by 'send_messages' to enable you to not only send text, but also keyboards, files, locations and more.
Each newline in the output will start an new message to the user, to have line breaks in your message you can use 'mynewlinestartshere'.
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\" ]"
@ -68,6 +77,10 @@ Same goes for files:
```bash
echo "Text that will appear in chat? myfilelocationstartshere /home/user/doge.jpg"
```
And buttons:
```bash
echo "Text that will appear in chat. mybtextstartshere Klick me myburlstartshere https://dealz.rrr.de"
```
And locations:
```bash
echo "Text that will appear in chat. mylatstartshere 45 mylongstartshere 45"
@ -82,19 +95,27 @@ echo "Text that will appear in chat? mykeyboardstartshere [ \"Yep, sure\" , \"No
```
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.
To insert a linebreak in your message you can insert ```mynewlinestartshere``` in your echo command:
New in v0.6: To insert a linebreak in your message you can insert ```mynewlinestartshere``` in your echo command:
```bash
echo "Text that will appear in one message mynewlinestartshere with this text on a new line"
```
New in v0.7: In case you must extend a message already containing a location, a file, a keyboard etc.,
with additionial text simply add ``` mytextstartshere additional text``` at the end of the string:
```bash
out="Text that will appear mylatstartshere 45 mylongstartshere 45"
[[ "$out" != *'in chat'* ]] && out="$out mytextstartshere in chat."
echo "$out"
```
Note: Interactive Chats run independent from main bot and continue running until your script exits or you /cancel if from your Bot.
### Background Jobs
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 examples/notify.sh script and use the funtion ```background``` to start it:
A background job is similar to an interactive chat, but runs in the background and does only output massages and does not get user input. In contrast to interactive chats it's possible to run multiple background jobs. To create a background job write a script or edit 'examples/notify.sh' script and use the funtion ```background``` to start it:
```bash
background "examples/notify.sh" "jobname"
```
All output of the script will be sent to the user or chat. To stop a background job use:
All output of the script will be sent to the user, to stop a background job use:
```bash
killback "jobname"
```
@ -109,7 +130,7 @@ If you want to kill all background jobs permantly run:
./bashbot.sh killback
```
Note: Background Jobs run independent from main bot and continue running until your script exits or you stop if from your Bot. Backgound Jobs will continue running if your Bot is stoped (kill)!.
Note: Background Jobs run independent from main bot and continue running until your script exits or you stop if from your Bot. Backgound Jobs will continue running if your Bot is stopeda and must be terminated, e.g. by ```bashbot.sh killback```
### Inline queries
The following commands allows users to interact with your bot via *inline queries*.
@ -153,8 +174,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)
#### [Prev Getting started](2_usage.md)
#### [Next Expert Use](4_expert.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -104,5 +104,5 @@ An example crontab is provided in ```examples/bashbot.cron```.
#### [Prev Expert Use](4_expert.md)
#### [Next Best Practice](5_practice.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,49 +1,92 @@
#### [Home](../README.md)
## Best Practices
### Customize commands.sh only
### New to bot development?
To ease Updates never change ```bashbot.sh```, instead individual commands should go to ```commands.sh``` . Insert your Bot commands in the ```case ... esac``` block:
If you are new to Bot development read [Bots: An introduction for developers](https://core.telegram.org/bots) and consult [Telegram Bot API Documentation](https://core.telegram.org/bots/api/).
In addition you should know about [BotFather, the one bot to rule them all](https://core.telegram.org/bots#3-how-do-i-create-a-bot). It will help you create new bots and change settings for existing ones. [Commands known by Botfather](https://core.telegram.org/bots#generating-an-authorization-token)
If you dont't have a github account, it may time to [sepup a free account now](https://github.com/pricing)
### Add commands to mycommands.sh only
To ease updates never change ```bashbot.sh```, instead your commands and functions must go to ```mycommands.sh``` . Insert your Bot commands in the ```case ... esac``` block of the 'mycommands()' function:
```bash
case "$MESSAGE" in
'/echo') # my first own command, echo MESSAGE
send_normal_message "${CHAT[ID]}" "${MESSAGE}"
;;
# file: mycommands.sh
# your additional bahsbot commands
# uncomment the following lines to overwrite info and help messages
bashbot_info='This is *MY* variant of _bashbot_, the Telegram bot written entirely in bash.
'
bashbot_help='*Available commands*:
/echo message - _echo the given messsage_
'
# NOTE: command can have @botname attached, you must add * in case tests...
mycommands() {
case "$MESSAGE" in
'/echo'*) # example echo command
send_normal_message "${CHAT[ID]}" "$MESSAGE"
;;
# .....
esac
}
```
### Reuse or disable global commands
If you want to disable or reuse a global bashbot command comment it out in 'commands.sh' by placing a '#' in front of
every line from ```'/command')``` to ```;;```.
**Learn more about [Bot commands](https://core.telegram.org/bots#commands).**
**Note: Never disable the catchall command ```*)``` in 'commands.sh'!!**
```bash
# file: commands.sh
case "$MESSAGE" in
################################################
# DEFAULT commands start here, do not edit below this!
'/info')
bashbot_info "${CHAT[ID]}"
# GLOBAL commands start here, edit messages only
#'/start'*)
# send_action "${CHAT[ID]}" "typing"
# _is_botadmin && _markdown_message "You are *BOTADMIN*."
# if _is_allowed "start" ; then
# _markdown_message "${bot_help}"
# else
# _message "You are not allowed to start Bot."
# fi
# ;;
*) # forward other messages to optional dispatcher
_is_function startproc && if tmux ls | grep -v send | grep -q "$copname"; then inproc; fi # interactive running
_is_function mycommands && mycommands
;;
esac
```
### Seperate logic from commands
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:
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 ```mycommands.sh``` and call the from your command. Example:
```bash
source "mycommands.inc.sh"
# file: mycommands.sh
# your additional bahsbot commands
mycommands() {
case "$MESSAGE" in
'/process') # logic for /process is done in process_message
'/process'*) # logic for /process is done in process_message
result="$(process_message "$MESSAGE")"
send_normal_message "${CHAT[ID]}" "$result"
;;
################################################
# DEFAULT commands start here, do not edit below this!
'/info')
bashbot_info "${CHAT[ID]}"
;;
'/start')
send_action "${CHAT[ID]}" "typing"
bashbot_help "${CHAT[ID]}"
;;
esac
```
```bash
#!/bin/bash
# file: mycommands.inc.sh
}
# place your functions here
process_message() {
local ARGS="${1#/* }" # remove command
@ -53,7 +96,6 @@ process_message() {
set -f
for WORD in $ARGS
do
set +f
# process links
if [[ "$WORD" == "https://"* ]]; then
REPORT="$(dosomething_with_link "$WORD")"
@ -68,7 +110,6 @@ process_message() {
done
# return result, reset globbing in case we had no ARGS
set +f
echo "${OUTPUT}${TEXT}"
}
@ -112,5 +153,5 @@ The second warning is about an unused variable, this is true because in our exam
#### [Prev Best Practice](5_practice.md)
#### [Next Functions Reference](6_reference.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -10,7 +10,6 @@
*"action":* ```typing```, ```upload_photo```, ```record_video```, ```upload_video```, ```record_audio```, ```upload_audio```, ```upload_document```, ```find_location```.
*example:*
```bash
send_action "${CHAT[ID]}" "typing"
@ -37,8 +36,8 @@ Telegram supports a [reduced set of Markdown](https://core.telegram.org/bots/api
*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_markdown_message "${CHAT[ID]}" "this is a markdown message, next word is *bold*"
send_markdown_message "${CHAT[ID]}" "*bold* _italic_ [text](link)"
```
##### send_html_message
@ -58,18 +57,9 @@ send_normal_message "${CHAT[ID]}" "<b>bold</b> <i>italic><i> <em>italic>/em> <a
*usage:* forward_message "chat_to" "chat_from" "${MESSAGE[ID]}"
*alias:* forward "${CHAT[ID]}" "$FROMCHAT" "${MESSAGE[ID]}"
*old call:* 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)
See also [Text formating options](https://core.telegram.org/bots/api#formatting-options)
----
@ -78,6 +68,8 @@ If your Bot is admin of a Chat he can delete every message, if not he can delete
*usage:* delete_message "${CHAT[ID]}" "${MESSAGE[ID]}"
See also [deleteMessage limitations](https://core.telegram.org/bots/api#deletemessage)
----
##### answer_inline_query
@ -137,24 +129,65 @@ send_keyboard "${CHAT[ID]}" "Enter digit" "[ \\"1\\" , \\"2\\" , \\"3\\" ] , [ \
##### remove_keyboard
*usage:* remove_keybord "$CHAT[ID]" "message"
*See also: [Keyboard Markup](https://core.telegram.org/bots/api/#replykeyboardmarkup)*
----
##### send_button
*usage:* send_button "chat-id" "message" "text" "URL"
*alias:* _button "text" "URL"
*example:*
```bash
send_button "${CHAT[ID]}" "MAKE MONEY FAST!!!" "Visit my Shop" "https://dealz.rrr.de"
```
##### send_inline_keyboard
This allows to place multiple inline buttons in a row. The inline buttons must specified as a JSON array in the following format:
```[ {"text":"text1", "url":"url1"}, ... {"text":"textN", "url":"urlN"} ]```
Each button consists of a pair of text and URL values, sourrounded by '{ }', multiple buttons are seperated by '**,**' and everthing is wrapped in '[ ]'.
*usage:* send_inline_keyboard "chat-id" "message" "[ {"text":"text", "url":"url"} ...]"
*alias:* _inline_keyboard "[{"text":"text", "url":"url"} ...]"
*example:*
```bash
send_inline_keyboard "${CHAT[ID]}" "MAKE MONEY FAST!!!" '[{"text":"Visit my Shop", url"":"https://dealz.rrr.de"}]'
send_inline_keyboard "${CHAT[ID]}" "" '[{"text":"button 1", url"":"url 1"}, {"text":"button 2", url"":"url 2"} ]'
send_inline_keyboard "${CHAT[ID]}" "" '[{"text":"b 1", url"":"u 1"}, {"text":"b 2", url"":"u 2"}, {"text":"b 2", url"":"u 2"} ]'
```
*See also [Inline keyboard markup](https://core.telegram.org/bots/api/#inlinekeyboardmarkup)*
----
### Manage users
##### kick_chat_member
If your Bot is Admin of a chat he can kick and ban a user.
If your Bot is a chat admin he can kick and ban a user.
*usage:* kick_chat_member "${CHAT[ID]}" "${USER[ID]}"
*usage:* kick_chat_member "${CHAT[ID]}" "${USER[ID]}"
*alias:* _kick_user "${USER[ID]}"
##### unban_chat_member
If your Bot is Admin of a chat he can unban a kicked user.
If your Bot is a chat admine can unban a kicked user.
*usage:* unban_chat_member "${CHAT[ID]}" "${USER[ID]}"
*alias:* _unban "${USER[ID]}"
##### leave_chat
Bot will leave given chat.
Your Bot will leave the chat.
*usage:* leave_chat "${CHAT[ID]}"
*alias:* _leave
```bash
if _is_admin ; then
send_markdown_message "${CHAT[ID]}" "*LEAVING CHAT...*"
@ -162,21 +195,37 @@ if _is_admin ; then
fi
```
'See also [kick Chat Member](https://core.telegram.org/bots/api/#kickchatmember)*
----
### User Access Control
##### user_is_botadmin
Return true (0) if user is admin of bot, user id if botadmin is read from file './botadmin'.
*usage:* user_is_botadmin "${USER[ID]}"
*modules/alias:* _is_botadmin
*example:*
```bash
_is_botadmin && send_markdown_message "${CHAT[ID]}" "You are *BOTADMIN*."
```
##### 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
*modules/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
*modules/alias:* _is_admin
*example:*
```bash
@ -186,21 +235,10 @@ if _is_admin ; then
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*."
```
*See also [Chat Member](https://core.telegram.org/bots/api/#chatmember)*
##### user_is_allowed
Bahsbot supports User Access Control, see [Advanced Usage](4_advanced.ma)
Bahsbot supports User Access Control, see [Advanced Usage](3_advanced.md)
*usage:* user_is_allowed "${USER[ID]}" "what" "${CHAT[ID]}"
@ -211,10 +249,82 @@ if ! user_is_allowed "${USER[ID]}" "start" "${CHAT[ID]}" ; then
fi
```
----
### Aliases - shortcuts for often used funtions
You must not disable ```source modules/aliases.sh``` in 'commands.sh' to have the following functions availible.
##### _is_botadmin
*usage:* _is_botadmin
*alias for:* user_is_botadmin "${USER[ID]}"
##### _is_admin
*usage:* _is_admin
*alias for:* user_is_admin "${CHAT[ID]}" "${USER[ID]}"
##### _is_allowed
*usage:* _is_allowed "what"
*alias for:* user_is_allowed "${USER[ID]}" "what" "${CHAT[ID]}"
----
##### _kick_user
*usage:* _kick_user "${USER[ID]}"
*alias for:* kick_chat_member "${CHAT[ID]}" "${USER[ID]}"
##### _unban
*usage:* _unban "${USER[ID]}"
*alias for:* unban_chat_member "${CHAT[ID]}" "${USER[ID]}"
##### _leave
*usage:* _leave
*alias for:* leave_chat "${CHAT[ID]}"
----
##### _message
*usage:* _message "message"
*alias for:* send_normal_message "${CHAT[ID]}" "message"
##### _normal_message
*usage:* _normal_message "message"
*alias for:* send_normal_message "${CHAT[ID]}" "message"
##### _html_message
*usage:* _html_message "message"
*alias for:* send_html_message "${CHAT[ID]}" "message"
##### _markdown_message
*usage:* _markdown_message "message"
*alias for:* send_markdown_message "${CHAT[ID]}" "message"
----
### Interactive and backgound jobs
You must not disable ```source modules/background.sh``` in 'commands.sh' to have the following functions availible.
##### 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)
```startproc``` starts a script, the output of the script 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"
@ -224,7 +334,7 @@ startproc 'examples/calc.sh'
```
##### checkproc
Return true (0) if an interactive script active in the given chat.
Return true (0) if an interactive script is running in the chat.
*usage:* checkprog
@ -239,6 +349,8 @@ fi
```
##### killproc
Kill the interactive script running in the chat
*usage:* killproc
*example:*
@ -254,7 +366,7 @@ 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.
Starts a script 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.
@ -295,6 +407,33 @@ else
fi
```
----
##### 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)
----
### Helper functions
##### _is_function
Returns true if the given function exist, can be used to check if a module is loaded.
*usage* _is_function function
*example:*
```bash
_is_function "background" && _message "you can run background jobs!"
```
----
### Bashbot internal functions
These functions are for internal use only and must not used in your bot commands.
@ -328,6 +467,8 @@ Reads JSON fro STDIN and Outputs found Value to STDOUT
##### get_chat_member_status
*usage:* get_chat_member_status "${CHAT[ID]}" "${USER[ID]}"
this may get an official function ...
----
##### process_client
@ -346,7 +487,7 @@ The name of your bot is availible as bash variable "$ME", there is no need to ca
Send Input from Telegram to waiting Interactive Chat.
#### [Prev Best Practice](5_practice.md)
#### [Next Developer Rules](7_develop.md)
#### [Next Notes for Developers](7_develop.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -1,6 +1,6 @@
#### [Home](../README.md)
## Notes for bashbot developers
This section is about help and best pratices for new bashbot developers. The main focus on is creating new versions of bashbot, not on develop your individual bot. Nevertheless the rules and tools described here can also help you with your bot development.
This section is about help and best practices for new bashbot developers. The main focus on is creating new versions of bashbot, not on develop your individual bot. Nevertheless the rules and tools described here can also help you with your bot development.
bashbot development is done on github. If you want to provide fixes or new features [fork bashbot on githup](https://help.github.com/en/articles/fork-a-repo) and provide changes as [pull request on github](https://help.github.com/en/articles/creating-a-pull-request).
@ -13,6 +13,27 @@ bashbot development is done on github. If you want to provide fixes or new featu
5. give your (dev) fork a new version tag: ```git tag vx.xx```, version must be higher than current version
6. setup github hooks by running ```dev/install-hooks.sh``` (optional)
### Test, Add, Push changes
A typical bashbot develop loop looks as follow:
1. start developing - *change, copy, edit bashbot files ...*
2. after changing a bash sript: ```shellcheck -x scipt.sh```
3. ```dev/all-tests.sh``` - *in case if errors back to 2.*
4. ```dev/git-add.sh``` - *check for changed files, update version string, run git add*
5. ```git commit' -m "COMMIT MESSAGE"; git push```
**If you setup iyou dev environment with hooks and use the scripts above, versioning, addding and testing is done automatically.**
### Prepare a new version
After some development it may time to create a new version for the users. a new version can be in sub version upgrade, e.g. for fixes and smaller additions or
a new release version for new features. To mark a new version use ```git tag NEWVERSION``` and run ```dev/version.sh``` to update all version strings.
Usually I start with pre versions and when everything looks good I push out a release candidate (rc) and finally the new version.
```
v0.x-devx -> v0.x-prex -> v0.x-rc -> v0.x ... 0.x+1-dev ...
```
### Versioning
Bashbot is tagged with version numbers. If you start a new development cycle you must tag your fork with a version higher than the current version.
@ -22,7 +43,6 @@ To get the current version name of your develepment fork run ```git describe --t
To update the Version Number in your scripts run ```dev/version.sh```, it will update the line '#### $$VERSION$$ ###' in all files to the current version name.
If you actived git hooks in Setup step 6, 'version.sh' updates the version name on every push
### Shellchecking
@ -32,17 +52,18 @@ In addition you can run ```dev/hooks/pre-commit.sh``` every time you want to she
## bashbot tests
Starting with version 0.70 bashbot has a test suite. To start testsuite run ```test/ALL-tests.sh```. ALL-tests.sh will only return 'SUCCESS' if all tests pass.
Starting with version 0.70 bashbot has a test suite. To start testsuite run ```dev/all-tests.sh```. all-tests.sh will return 'SUCCESS' only if all tests pass.
### enabling / disabling tests
All tests are placed in the directory ```test```. To disable a test remove the x flag from the '*-test.sh' test script, to (re)enable
a test make the script executable again.
All tests are placed in the directory ```test```. To disable a test remove the x flag from the '*-test.sh' test script, to (re)enable a test make the script executable again.
### creating new tests
Each test consists of a script script named like ```p-name-test.sh``` *(where p is test pass 'a-z' and name the name of your test)* and
an optional dir ```p-name-test/``` *(script name minus '.sh')* for additional files.
To create a new test run ```test/ADD-test-new.sh``` and answer the questions, afterwards you have the following described files and dirs:
Each test consists of a script script named like ```p-name-test.sh``` *(where p is test pass 'a-z' and name the name
of your test)* and an optional dir ```p-name-test/``` *(script name minus '.sh')* for additional files.
The file ```ALL-tests.inc.sh``` must be included from all tests, do not forget the shellcheck source directive to statisfy shellcheck.
@ -68,7 +89,8 @@ else
fi
```
#### [Prev Function Reference](6_function.md)
#### [Prev Function Reference](6_reference.md)
#### [Next Bashbot Environment](8_custom.md)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

121
doc/8_custom.md Normal file
View File

@ -0,0 +1,121 @@
#### [Home](../README.md)
## Customize bashbots environment
This section describe how you can customize bashbot to your needs by setting environment variables.
### Change file locations
In standard setup bashbot is self containing, this means you can place 'telegram-bot-bash' any location
and run it from there. All files - programm, config, data etc - will reside in 'telegram-bot-bash'.
If you want to have other locations for config, data etc, define and export the following environment variables.
**Note: all specified directories and files must exist or running 'bashbot.sh' will fail.**
#### BASHBOT_ETC
Location of the files ```commands.sh```, ```mycommands.sh```, ```token```, ```botadmin```, ```botacl``` ...
```bash
unset BASHBOT_ETC # keep in telegram-bot-bash (default)
export BASHBOT_ETC "" # keep in telegram-bot-bash
export BASHBOT_ETC "/etc/bashbot" # unix like config location
export BASHBOT_ETC "/etc/bashbot/bot1" # multibot configuration bot 1
export BASHBOT_ETC "/etc/bashbot/bot2" # multibot configuration bot 2
```
e.g. /etc/bashbot
#### BASHBOT_VAR
Location of runtime data ```data-bot-bash```, ```count```
```bash
unset BASHBOT_VAR # keep in telegram-bot-bash (default)
export BASHBOT_VAR "" # keep in telegram-bot-bash
export BASHBOT_VAR "/var/spool/bashbot" # unix like config location
export BASHBOT_VAR "/var/spool/bashbot/bot1" # multibot configuration bot 1
export BASHBOT_VAR "/var/spool/bashbot/bot2" # multibot configuration bot 2
```
#### BASHBOT_JSONSH
Full path to JSON.sh script, default: './JSON.sh/JSON.sh', must end with '/JSON.sh'.
```bash
unset BASHBOT_JSONSH # telegram-bot-bash/JSON.sh/JSON.sh (default)
export BASHBOT_JSONSH "" # telegram-bot-bash/JSON.sh/JSON.sh
export BASHBOT_JSONSH "/usr/local/bin/JSON.sh" # installed in /usr/local/bin
```
### Change config values
#### BASHBOT_DECODE
Bashbot offers two variants for decoding JSON UTF format to UTF-8. By default bashbot uses 'json.encode' if python is installed.
If 'BASHBOT_DECODE' is set to any value (not undefined or not empty) the bash only implementation will be used.
```bash
unset BASHBOT_DECODE # autodetect python (default)
export BASHBOT_DECODE "" # autodetect python
export BASHBOT_DECODE "yes" # force internal
export BASHBOT_DECODE "no" # also force internal!
```
#### BASHBOT_SLEEP
Instead of polling permanently or with a fixed delay, bashbot offers a simple adaptive polling.
If messages are recieved bashbot polls with no dealy. If no messages are availible bashbot add 100ms delay
for every poll until the maximum of BASHBOT_SLEEP ms.
```bash
unset BASHBOT_SLEEP # 5000ms (default)
export BASHBOT_SLEEP "" # 5000ms
export BASHBOT_SLEEP "1000" # 1s maximum sleep
export BASHBOT_SLEEP "10000" # 10s maximum sleep
export BASHBOT_SLEEP "1" # values < 1000 disables sleep (not recommended)
```
### Testet configs as of v.07 release
**Note: Environment variables are not stored, you must setup them before every call to bashbot.sh, e.g. from a script.**
#### simple Unix like config, for one bot. bashbot is installed in '/usr/local/telegram-bot-bash'
```bash
# Note: all dirs and files must exist!
export BASHBOT_ETC "/etc/bashbot"
export BASHBOT_VAR "/var/spool/bashbot"
/usr/local/telegram-bot-bash/bashbot.sh start
```
#### Unix like config for one bot. bashbot.sh is installed in '/usr/bin'
```bash
# Note: all dirs and files must exist!
export BASHBOT_ETC "/etc/bashbot"
export BASHBOT_VAR "/var/spool/bashbot"
export BASHBOT_JSONSH "/var/spool/bashbot"
/usr/local/bin/bashbot.sh start
```
#### simple multibot config, everything is keept inside 'telegram-bot-bash' dir
```bash
# config for running Bot 1
# Note: all dirs and files must exist!
export BASHBOT_ETC "./mybot1"
export BASHBOT_VAR "./mybot1"
/usr/local/telegram-bot-bash/bashbot.sh start
```
```bash
# config for running Bot 2
# Note: all dirs and files must exist!
export BASHBOT_ETC "./mybot2"
export BASHBOT_VAR "./mybot2"
/usr/local/telegram-bot-bash/bashbot.sh start
```
#### [Prev Notes for Developers](7_develop.md)
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

43
examples/README.md Normal file
View File

@ -0,0 +1,43 @@
#### [Home](../README.md)
## Bashbot examples
### bashbot.cron
An example crontab is provided in ```examples/bashbot.cron```, see [Expert use](../doc/4_expert.md#Scedule-bashbot-from-Cron)
### Interactive chats
Two examples for interactive scripts are provided as **calc.sh** and **question.sh**, see [Advanced use](../doc/3_advanced.md#Interactive-Chats)
### Background jobs
Background jobs are an easy way to provide sceduled messages or alerts if something happens.
**notify.sh** is a simple example on how to send a message every x seonds, e.g. current time.
**background-scripts** contains a more concrete example on how to start and stop different scripts plus some example backgound scripts.
```
mycommands.sh - /run_xxx and /kill-xxx wil start any script named run_xxx.sh
run_diskusage.sh - shows disk usage every 100 seconds
run_filename.sh - shown the name of new files in a named dir
run_filecontent.sh - shown the content of new files in a named dir
run_notify.sh - same as notify.sh
```
**Note:** Output of system commands often contains newlines, each newline results in a telegram message, the function 'send_telegram' in
mycommands.sh avoids this by converting each newline to ' mynewlinestartshere ' before output the string.
**system-status** contains an example with commands showing system status. This example is adapted from https://github.com/RG72/telegram-bot-bash
```
mycommands.sh - sommands to show system status
botacl - controls who can show system status
```
### Use bashbot from external scripts
**external-use** will contain some examples on how to send messages from external scripts to Telegram chats or users.
#### $$VERSION$$ v0.7-rc1-0-g8279bdb

View File

@ -0,0 +1,107 @@
#!/bin/bash
# files: mycommands.sh.dist
# copy to mycommands.sh and add all your commands an functions here ...
export res
# your additional bahsbot commands ...
mycommands() {
case "$MESSAGE" in
'/run_'*)
myback="run_${MESSAGE#*_}"
if [ -x "./${myback}.sh" ]; then
checkback "${myback}"
if [ "$res" -gt 0 ] ; then
send_normal_message "${CHAT[ID]}" "Start ${myback}, use /kill${myback} to stop it."
background "./${myback}.sh" "${myback}"
else
send_normal_message "${CHAT[ID]}" "Background job ${myback} already running."
fi
fi
;;
'/kill_'*)
myback="run_${MESSAGE#*_}"
if [ -x "./${myback}.sh" ]; then
checkback "${myback}"
if [ "$res" -eq 0 ] ; then
killback "${myback}"
send_normal_message "${CHAT[ID]}" "Stopping ${myback}, use /run_${myback} to start again."
else
send_normal_message "${CHAT[ID]}" "No background job ${myback}."
fi
fi
;;
esac
}
# place your additional processing functions here ...
# returns true if function exist
_is_function()
{
[ "$(LC_ALL=C type -t "$1")" = "function" ]
}
# inifnite loop for waching a given dir for new files
# $1 dir to wtach for new files
watch_dir_loop() {
local newfile old
[ ! -d "$1" ] && echo "ERROR: no directory $1 found!" >&2 && exit 1
# wait for new files in WATCHDIR
inotifywait -q -m "$1" -e create --format "%f" \
| while true
do
# read in newfile
read -r newfile
#skip if not match or same name as last time
[ "${newfile}" = "${old}" ] && continue
sleep 0.2
# process content and output message
echo "$(date): new file: ${newfile}" >>"$0.log"
# note: loop callback must a function in the calling script!
if _is_function loop_callback ; then
loop_callback "$1/$newfile"
else
echo "ERROR: loop_callback not found!" >&2
exit 1
fi
done
} # 2>>"$0.log"
output_telegram() {
# output to telegram
sed <<< "${1}" -e ':a;N;$!ba;s/\n/ mynewlinestartshere /g'
} # 2>>"$0.log"
# name and localtion of the tml file
# $1 string to output
# $2 file to add file to
output_html_file() {
local date
date="$(date)"
output_file "$(sed <<< "<div class=\"newdeal\">$1 <br>${date}</div>" '
s/ my[a-z]\{3,15}\(start\|ends\)here.*<br>/<br>/g
s/ *mynewlinestartshere */<br>/
s/\n/<br>/
')"
} # >>"$0.log" 2>&1
# $1 string to output
# $2 file to add file to
output_file() {
local publish="${2}"
[ ! -w "${publish}" ] && echo "ERROR: file ${publish} is not writeable or does not exist!" && exit
# output at beginnung of file, add date to message
sed <<< "${1}" '
s/ *mynewlinestartshere */\n/
s/ my[a-z]\{3,15}\(start\|ends\)here.*//g
' >"$publish$$"
cat "$publish" >>"$publish$$"
mv "${publish}$$" "${publish}"
} # >>"$0.log" 2>&1

View File

@ -0,0 +1,42 @@
#!/bin/bash
# file: run_diskcusage.sh
# example for an background job display a system value
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# 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
# discard STDIN for background jobs!
cat >/dev/null &
source "./mycommands.sh"
# check if $1 is a number
re='^[0-9]+$'
if [[ $1 =~ $re ]] ; then
SLEEP="$1"
else
SLEEP=100 # time between time notifications
fi
NEWLINE=$'\n'
# output disk usgae every $1 seconds
WAIT=0
while sleep $WAIT
do
output_telegram "Current Disk usage ${NEWLINE} $(df -h / /tmp /usr /var /home)"
# only for testing, delete echo line for production ...
echo "Current Disk usage ${NEWLINE} $(df -h / /tmp /usr /var /home)"
WAIT="$SLEEP"
done

View File

@ -0,0 +1,35 @@
#!/bin/bash
# file: run_filename
# background job to display content of all new files in WATCHDIR
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# 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
# discard STDIN for background jobs!
cat >/dev/null &
# watch for new files created by a trusted programm
WATCHDIR="/my_trusted/dir_to_watch"
source "./mycommands.sh"
# test your script and the remove ...
WATCHDIR="/tmp/bottest"
NEWLINE='mynewlinestartshere'
# this is called by watch dir loop
# $1 is name of the new file
loop_callback() {
# output content of file, you must trust creator because content is sent as message!
output_telegram "Contents of ${1}: ${NEWLINE} $(cat "${1}")"
}
watch_dir_loop "$WATCHDIR"

View File

@ -0,0 +1,33 @@
#!/bin/bash
# file: run_filename
# background job to display all new files in WATCHDIR
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# 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
# discard STDIN for background jobs!
cat >/dev/null &
# watch for new logfiles
WATCHDIR="/var/log"
source "./mycommands.sh"
# test your script and the remove ...
WATCHDIR="/tmp/bottest"
# this is called by watch dir loop
# $1 is name of the new file
loop_callback() {
# output one simple line ...
echo "New file ${1} created in ${WATCHDIR}!"
}
watch_dir_loop "$WATCHDIR"

View File

@ -0,0 +1,34 @@
#!/bin/bash
# file: notify.sh
# example for an background job, run with startback notify.sh
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# 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
# discard STDIN for background jobs!
cat >/dev/null &
# 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

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.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
SHELL=/bin/sh

View File

@ -1,9 +1,11 @@
#!/bin/bash
# file: calc.sh
# example for an interactive chat, run with startprog calc.sh
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment

View File

@ -1,8 +1,10 @@
#!/bin/bash
# file: notify.sh
# example for an background job, run with startback notify.sh
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment

View File

@ -1,30 +0,0 @@
#!/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.62-0-g5d5dbae
# 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 "Why hello there.
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"'
read -r answer
case $answer in
'Yass!') echo "Goody! mykeyboardendshere";SUCCESS=y;;
'No') echo "Well that's weird. mykeyboardendshere";SUCCESS=y;;
*) SUCCESS=n;;
esac
done
exit

View File

@ -1,9 +1,11 @@
#!/bin/bash
# file: question.sh
# example for an interactive chat, run with startprog question.sh
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# adjust your language setting here
# https://github.com/topkecleon/telegram-bot-bash#setting-up-your-environment

View File

@ -0,0 +1,17 @@
# file: botacl
# a user not listed here, will return false from 'user_is_allowed'
#
# Format:
# user:ressource:chat
# allow user 123456789 access to all resources in all chats
123456789:*:*
# allow user 12131415 to request systemstatus in all chats
12131415:systemstatus:*
# * are only allowed on the right hand side and not for user!
# the following exaples are NOT valid!
*:*:*
*:start:*
*:*:98979695

View File

@ -0,0 +1,84 @@
#!/bin/bash
# files: mycommands.sh
#
# this example is rendered after https://github.com/RG72/telegram-bot-bash
# to show how you can customize bashbot by only editing mycommands.sh
# NOTE: this is not tested, simply copied from original source and reworked!
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
#
# shellcheck disable=SC2154
# shellcheck disable=SC2034
# uncomment the following lines to overwrite info and help messages
#'
# returned messages
bashbot_info='This bot allows you to request status of your system.
To begin using the bot, try with the /help command.
'
bashbot_help='*Availiable commands*:
/s *sensors*
/ss *smbstatus*
/free *memory status*
/md *raid status*
/lvs *lvm status*
/lvsd *Datailed lvm status*
/df *disk space*
/ifconfig *ifconfig output*
/smart *-d sda* _smart status for sda drive_
'
IDMESSAGEPRE="Your chat identifier is"
# your additional bahsbot commands
# NOTE: command can have @botname attached, you must add * in case tests...
mycommands() {
if user_is_allowed "${USER[ID]}" "systemstatus"; then
case "$MESSAGE" in
'/md'|'raid_status') msg="$(cat /proc/mdstat)";;
'/ss'|'smbstatus')
msg=""
smbstatus >/tmp/smbstatus
send_doc "$TARGET" "/tmp/smbstatus"
prevActiveTime=$curTime
;;
'/s'|'sensors'|'/sensors') msg="$(sensors | sed -r 's/\s|\)+//g' | sed -r 's/\(high=|\(min=/\//' | sed -r 's/\,crit=|\,max=/\//')";;
'/free') msg="$(free -h)";;
'/pvs') msg="$(pvs)";;
'/ifconfig') msg="$(ifconfig)";;
'/vgs') msg="$(vgs)";;
'/lvs') msg="$(lvs | sed -r 's/\s+/\n/g')";;
'/lvsd') msg="$(lvs -a -o +devices | sed -r 's/\s+/\n/g')";;
'/smart'|'/smartctl')
if [ "$OPTARG" == "" ]; then
msg="example \`/smart sda\`"
else
drive="$(echo "$OPTARG" | cut -c 1-3)"
echo "smartctl -a /dev/$drive"
msg="$(smartctl -a "/dev/$drive")"
fi
;;
'/df') msg="$(df -h | sed -r 's/^/\n/' | sed -r 's/\s+/\n/g')";;
esac
if [ "$msg" != "" ]; then
send_telegram "${CHAT[ID]}" "$msg"
fi
else
send_normal_message "Sorry, you are not allowed to use this bot!"
fi
}
# place your processing functions here
# converts newlines for telegram and send as one message
# $1 chat
# $2 message
send_telegram() {
# output to telegram
send_message "${1}" "$(sed <<< "${2}" -e ':a;N;$!ba;s/\n/ mynewlinestartshere /g')"
} # 2>>"$0.log"

62
modules/aliases.sh Normal file
View File

@ -0,0 +1,62 @@
#!/bin/bash
# file: modules/alaises.sh
# do not edit, this file will be overwritten on update
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
#
# source from commands.sh to use the aliases
# easy handling of users:
_is_botadmin() {
user_is_botadmin "${USER[ID]}"
}
_is_admin() {
user_is_admin "${CHAT[ID]}" "${USER[ID]}"
}
_is_creator() {
user_is_creator "${CHAT[ID]}" "${USER[ID]}"
}
_is_allowed() {
user_is_allowed "${USER[ID]}" "${1}" "${CHAT[ID]}"
}
_leave() {
leave_chat "${CHAT[ID]}"
}
_kick_user() {
kick_chat_member "${CHAT[ID]}" "${1}"
}
_unban_user() {
unban_chat_member "${CHAT[ID]}" "${1}"
}
# easy sending of messages of messages
_message() {
send_normal_message "${CHAT[ID]}" "${1}"
}
_normal_message() {
send_normal_message "${CHAT[ID]}" "${1}"
}
_html_message() {
send_html_message "${CHAT[ID]}" "${1}"
}
_markdown_message() {
send_markdown_message "${CHAT[ID]}" "${1}"
}
# easy handling of keyboards
_inline_button() {
send_inline_button "${CHAT[ID]}" "" "${1}" "${2}"
}
_inline_keyboard() {
send_inline_keyboard "${CHAT[ID]}" "" "${1}"
}
_keyboard_numpad() {
send_keyboard "${CHAT[ID]}" "" '["1","2","3"],["4","5","6"],["7","8","9"],["-","0","."]' "yes"
}
_keyboard_yesno() {
send_keyboard "${CHAT[ID]}" "" '["yes","no"]'
}
_del_keyboard() {
remove_keyboard "${CHAT[ID]}" ""
}

118
modules/background.sh Normal file
View File

@ -0,0 +1,118 @@
#!/bin/bash
# file: modules/background.sh
# do not edit, this file will be overwritten on update
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# source from commands.sh if you want ro use interactive or background jobs
## to statisfy shellcheck
export res
####
# I placed send_message here because main use case is interactive chats and background jobs
send_message() {
[ "$2" = "" ] && return
local text keyboard btext burl no_keyboard file lat long title address sent
text="$(sed <<< "${2}" 's/ mykeyboardend.*//;s/ *my[kfltab][a-z]\{2,13\}startshere.*//')$(sed <<< "${2}" -n '/mytextstartshere/ s/.*mytextstartshere//p')"
text="$(sed <<< "${text}" 's/ *mynewlinestartshere */\r\n/g')"
[ "$3" != "safe" ] && {
no_keyboard="$(sed <<< "${2}" '/mykeyboardendshere/!d;s/.*mykeyboardendshere.*/mykeyboardendshere/')"
keyboard="$(sed <<< "${2}" '/mykeyboardstartshere /!d;s/.*mykeyboardstartshere *//;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
btext="$(sed <<< "${2}" '/mybtextstartshere /!d;s/.*mybtextstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
burl="$(sed <<< "${2}" '/myburlstartshere /!d;s/.*myburlstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//g;s/ *mykeyboardendshere.*//g')"
file="$(sed <<< "${2}" '/myfilelocationstartshere /!d;s/.*myfilelocationstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
lat="$(sed <<< "${2}" '/mylatstartshere /!d;s/.*mylatstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
long="$(sed <<< "${2}" '/mylongstartshere /!d;s/.*mylongstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
title="$(sed <<< "${2}" '/mytitlestartshere /!d;s/.*mytitlestartshere //;s/ *my[kfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
address="$(sed <<< "${2}" '/myaddressstartshere /!d;s/.*myaddressstartshere //;s/ *my[nkfltab][a-z]\{2,13\}startshere.*//;s/ *mykeyboardendshere.*//')"
}
if [ "$no_keyboard" != "" ]; then
remove_keyboard "$1" "$text"
sent=y
fi
if [ "$keyboard" != "" ]; then
if [[ "$keyboard" != *"["* ]]; then # pre 0.60 style
keyboard="[ ${keyboard//\" \"/\" \] , \[ \"} ]"
fi
send_keyboard "$1" "$text" "$keyboard"
sent=y
fi
if [ "$btext" != "" ] && [ "$burl" != "" ]; then
send_button "$1" "$text" "$btext" "$burl"
sent=y
fi
if [ "$file" != "" ]; then
send_file "$1" "$file" "$text"
sent=y
fi
if [ "$lat" != "" ] && [ "$long" != "" ]; then
if [ "$address" != "" ] && [ "$title" != "" ]; then
send_venue "$1" "$lat" "$long" "$title" "$address"
else
send_location "$1" "$lat" "$long"
fi
sent=y
fi
if [ "$sent" != "y" ];then
send_text "$1" "$text"
fi
}
send_text() {
case "$2" in
html_parse_mode*)
send_html_message "$1" "${2//html_parse_mode}"
;;
markdown_parse_mode*)
send_markdown_message "$1" "${2//markdown_parse_mode}"
;;
*)
send_normal_message "$1" "$2"
;;
esac
}
######
# interactive and background functions
background() {
echo "${CHAT[ID]}:$2:$1" >"${TMPDIR:-.}/${copname:--}$2-back.cmd"
startproc "$1" "back-$2-"
}
startproc() {
killproc "$2"
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}"
}
checkback() {
checkproc "back-$1-"
}
checkproc() {
tmux ls | grep -q "$1${copname}"; res=$?; return $?
}
killback() {
killproc "back-$1-"
rm -f "${TMPDIR:-.}/${copname}$1-back.cmd"
}
killproc() {
local fifo="$1${copname}"
(tmux kill-session -t "${fifo}"; echo imprettydarnsuredatdisisdaendofdacmd>"${TMPDIR:-.}/${fifo}"; tmux kill-session -t "sendprocess_${fifo}"; rm -f -r "${TMPDIR:-.}/${fifo}")2>/dev/null
}
inproc() {
tmux send-keys -t "$copname" "${MESSAGE[0]} ${URLS[*]}
"
}

10
modules/inline.sh Normal file
View File

@ -0,0 +1,10 @@
#!/bin/bash
# file: modules/inline.sh
# do not edit, this file will be overwritten on update
# This file is public domain in the USA and all free countries.
# Elsewhere, consider it to be WTFPLv2. (wtfpl.net/txt/copying)
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# source from commands.sh to use the inline functions

56
mycommands.sh Normal file
View File

@ -0,0 +1,56 @@
#!/bin/bash
# files: mycommands.sh.dist
# copy to mycommands.sh and add all your commands and functions here ...
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
#
# shellcheck disable=SC2154
# shellcheck disable=SC2034
# uncomment the following lines to overwrite info and help messages
# bashbot_info='This is bashbot, the Telegram bot written entirely in bash.
#'
# bashbot_help='*Available commands*:
#'
# your additional bahsbot commands
# NOTE: command can have @botname attached, you must add * in case tests...
mycommands() {
case "$MESSAGE" in
'/echo'*) # example echo command
send_normal_message "${CHAT[ID]}" "$MESSAGE"
;;
'/question'*) # start interactive questions
checkproc
if [ "$res" -gt 0 ] ; then
startproc "example/question"
else
send_normal_message "${CHAT[ID]}" "$MESSAGE already running ..."
fi
;;
'/run-notify'*) # start notify background job
myback="notify"; checkback "$myback"
if [ "$res" -gt 0 ] ; then
background "example/notify 60" "$myback" # notify every 60 seconds
else
send_normal_message "${CHAT[ID]}" "Background command $myback already running ..."
fi
;;
'/stop-notify'*) # kill notify background job
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
;;
esac
}
# place your processing functions here

79
test/ADD-test-new.sh Executable file
View File

@ -0,0 +1,79 @@
#!/usr/bin/env bash
#
# ADD a new test skeleton to test dir, but does not activate test
#
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# magic to ensure that we're always inside the root of our application,
# no matter from which directory we'll run script
GIT_DIR=$(git rev-parse --git-dir)
cd "${GIT_DIR}/.." || exit 1
echo -ne "\\nDo your really want to create an new test for bashbot test suite? (y/N) N\\b"
read -r REALLY
[ "${REALLY}" != "y" ] && echo "Aborting ..." && exit 1
# enter name
echo -ne "\\nEnter Name for the the new test, 6+ chars, no :space: (empty to abort) abort\\b\\b\\b\\b\\b"
read -r NAME
if [ "${NAME}" = "" ] || [ "${NAME}" = "" ]; then echo "Aborting ..."; exit 1; fi
# enter pass a-z
echo -ne "\\nEnter PASS \"a\" to \"z\" to execute the new test, d\\b"
read -r PASS
# pass to lower, default pass d
PASS="${PASS,,}"
[ "${PASS}" = "" ] && PASS="d"
[ "${#PASS}" != '1' ] && echo "Sorry, PASS must exactly one charater from a to z, aborting ..." && exit 1
TEST="${PASS}-${NAME}-test"
echo -e " OK! You entered name \"${NAME}\" and pass \"${PASS}\".\\n"
# check if already exist
if [ -f "test/${TEST}.sh" ] || [ -d "test/${TEST}" ]; then
echo "TEST EXIST ALREADY! Aborting ..."
exit 1
fi
echo "The following files will be created for test \"${TEST}.sh\":"
echo -e " test/${TEST}.sh\\n test/${TEST}/${TEST}.input\\n test/${TEST}/${TEST}.result"
echo -ne "\\nCreate the new test for bashbot test suite? (y/N) N\\b"
read -r REALLY
[ "${REALLY}" != "y" ] && echo "Aborting ..." && exit 1
echo -e " OK!\\n"
# create files
cat >"test/${TEST}.sh" <<EOF
#!/usr/bin/env bash
#### \$\$VERSION\$\$
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh
source "./ALL-tests.inc.sh"
set -e
cd "\${TESTDIR}" || exit 1
# source bashbot.sh function, uncomment if you want to test functions
# shellcheck source=./bashbot.sh
# source "\\${TESTDIR}/bashbot.sh" source
# start writing your tests here ...
EOF
mkdir "test/${TEST}"
touch "test/${TEST}/${TEST}.input" "test/${TEST}/${TEST}.result"
set +f
ls -l test/"${PASS}"-"${NAME}"-*
echo "Done."

5
test/ALL-tests.inc.sh Executable file → Normal file
View File

@ -1,5 +1,5 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# common variables
export TESTME DIRME TESTDIR LOGFILE REFDIR TESTNAME
@ -23,6 +23,7 @@ export SUCCESS NOSUCCESS
NOSUCCESS=" FAILED!"
# default input, reference and output files
export INPUTFILE REFFILE OUTPUTFILE
INPUTFILE="${DIRME}/${REFDIR}/${REFDIR}.input"
REFFILE="${DIRME}/${REFDIR}/${REFDIR}.result"
OUTPUTFILE="${TESTDIR}/${REFDIR}.out"
@ -34,7 +35,7 @@ print_array() {
for idx in "${arrays[@]}"; do
declare -n temp="$idx"
for t in "${!temp[@]}"; do
printf "%s:\t%s\t%s\n" "$idx" "$t" "${temp[$t]}"
printf '%s:\t%s\t%s\n' "$idx" "$t" "${temp[$t]}"
done | sort
done | grep -v '^USER: 0'
}

2
test/a-commit-test.sh Normal file → Executable file
View File

@ -1,5 +1,5 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
../dev/hooks/pre-commit.sh

View File

@ -1,4 +0,0 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
../dev/hooks/pre-push.sh

View File

@ -1,5 +1,5 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh

35
test/d-JSON.sh-test.sh Executable file
View File

@ -0,0 +1,35 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh
source "./ALL-tests.inc.sh"
set -e
# source bashbot.sh functionw
cd "${TESTDIR}" || exit 1
# run JSON.sh with and without options
cd "test" || exit 1
echo "Check JSON.sh ..."
JSON="../JSON.sh/JSON.sh"
for i in 1 2
do
[ "${i}" = "1" ] && echo " ... JSON.sh -s -b -n"
[ "${i}" = "2" ] && echo " ... JSON.sh"
set +f
for jsonfile in ${REFDIR}/*.log
do
set -f
[ "${i}" = "1" ] && "${JSON}" -s -b -n <"${jsonfile}" >"${jsonfile}.out-${i}"
[ "${i}" = "2" ] && "${JSON}" <"${jsonfile}" >"${jsonfile}.out-${i}"
# output processed input
diff -c "${jsonfile}.result-${i}" "${jsonfile}.out-${i}" || exit 1
done
echo "${SUCCESS}"
done
cd "${DIRME}" || exit 1

View File

@ -0,0 +1,22 @@
["ok"] true
["result",0,"update_id"] 146860898
["result",0,"message","message_id"] 6620
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","chat","id"] 123456789
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","date"] 1555934213
["result",0,"message","location","latitude"] 49.630443
["result",0,"message","location","longitude"] 8.361698
["result",0,"message","venue","location","latitude"] 49.630443
["result",0,"message","venue","location","longitude"] 8.361698
["result",0,"message","venue","title"] "Vannini"
["result",0,"message","venue","address"] "K\u00e4mmererstr. 3"
["result",0,"message","venue","foursquare_id"] "4bf94ec05ec320a115f889d3"

View File

@ -0,0 +1,31 @@
["ok"] true
["result",0,"update_id"] 146860898
["result",0,"message","message_id"] 6620
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","from"] {"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"}
["result",0,"message","chat","id"] 123456789
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","chat"] {"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"}
["result",0,"message","date"] 1555934213
["result",0,"message","location","latitude"] 49.630443
["result",0,"message","location","longitude"] 8.361698
["result",0,"message","location"] {"latitude":49.630443,"longitude":8.361698}
["result",0,"message","venue","location","latitude"] 49.630443
["result",0,"message","venue","location","longitude"] 8.361698
["result",0,"message","venue","location"] {"latitude":49.630443,"longitude":8.361698}
["result",0,"message","venue","title"] "Vannini"
["result",0,"message","venue","address"] "K\u00e4mmererstr. 3"
["result",0,"message","venue","foursquare_id"] "4bf94ec05ec320a115f889d3"
["result",0,"message","venue"] {"location":{"latitude":49.630443,"longitude":8.361698},"title":"Vannini","address":"K\u00e4mmererstr. 3","foursquare_id":"4bf94ec05ec320a115f889d3"}
["result",0,"message"] {"message_id":6620,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934213,"location":{"latitude":49.630443,"longitude":8.361698},"venue":{"location":{"latitude":49.630443,"longitude":8.361698},"title":"Vannini","address":"K\u00e4mmererstr. 3","foursquare_id":"4bf94ec05ec320a115f889d3"}}
["result",0] {"update_id":146860898,"message":{"message_id":6620,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934213,"location":{"latitude":49.630443,"longitude":8.361698},"venue":{"location":{"latitude":49.630443,"longitude":8.361698},"title":"Vannini","address":"K\u00e4mmererstr. 3","foursquare_id":"4bf94ec05ec320a115f889d3"}}}
["result"] [{"update_id":146860898,"message":{"message_id":6620,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934213,"location":{"latitude":49.630443,"longitude":8.361698},"venue":{"location":{"latitude":49.630443,"longitude":8.361698},"title":"Vannini","address":"K\u00e4mmererstr. 3","foursquare_id":"4bf94ec05ec320a115f889d3"}}}]
[] {"ok":true,"result":[{"update_id":146860898,"message":{"message_id":6620,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934213,"location":{"latitude":49.630443,"longitude":8.361698},"venue":{"location":{"latitude":49.630443,"longitude":8.361698},"title":"Vannini","address":"K\u00e4mmererstr. 3","foursquare_id":"4bf94ec05ec320a115f889d3"}}}]}

View File

@ -0,0 +1,19 @@
["ok"] true
["result",0,"update_id"] 146860896
["result",0,"message","message_id"] 6618
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","chat","id"] 123456789
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","date"] 1555934195
["result",0,"message","voice","duration"] 1
["result",0,"message","voice","mime_type"] "audio/ogg"
["result",0,"message","voice","file_id"] "AwADAgADKQMAAh638UnbhHGzIMozZgI"
["result",0,"message","voice","file_size"] 3963

View File

@ -0,0 +1,26 @@
["ok"] true
["result",0,"update_id"] 146860896
["result",0,"message","message_id"] 6618
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","from"] {"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"}
["result",0,"message","chat","id"] 123456789
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","chat"] {"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"}
["result",0,"message","date"] 1555934195
["result",0,"message","voice","duration"] 1
["result",0,"message","voice","mime_type"] "audio/ogg"
["result",0,"message","voice","file_id"] "AwADAgADKQMAAh638UnbhHGzIMozZgI"
["result",0,"message","voice","file_size"] 3963
["result",0,"message","voice"] {"duration":1,"mime_type":"audio/ogg","file_id":"AwADAgADKQMAAh638UnbhHGzIMozZgI","file_size":3963}
["result",0,"message"] {"message_id":6618,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934195,"voice":{"duration":1,"mime_type":"audio/ogg","file_id":"AwADAgADKQMAAh638UnbhHGzIMozZgI","file_size":3963}}
["result",0] {"update_id":146860896,"message":{"message_id":6618,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934195,"voice":{"duration":1,"mime_type":"audio/ogg","file_id":"AwADAgADKQMAAh638UnbhHGzIMozZgI","file_size":3963}}}
["result"] [{"update_id":146860896,"message":{"message_id":6618,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934195,"voice":{"duration":1,"mime_type":"audio/ogg","file_id":"AwADAgADKQMAAh638UnbhHGzIMozZgI","file_size":3963}}}]
[] {"ok":true,"result":[{"update_id":146860896,"message":{"message_id":6618,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":123456789,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934195,"voice":{"duration":1,"mime_type":"audio/ogg","file_id":"AwADAgADKQMAAh638UnbhHGzIMozZgI","file_size":3963}}}]}

View File

@ -0,0 +1,18 @@
["ok"] true
["result",0,"update_id"] 146860897
["result",0,"message","message_id"] 6619
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","chat","id"] 586928566
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","date"] 1555934204
["result",0,"message","contact","phone_number"] "222222"
["result",0,"message","contact","first_name"] "ADAC Pannenhilfe"
["result",0,"message","contact","vcard"] "BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"

View File

@ -0,0 +1,25 @@
["ok"] true
["result",0,"update_id"] 146860897
["result",0,"message","message_id"] 6619
["result",0,"message","from","id"] 123456789
["result",0,"message","from","is_bot"] false
["result",0,"message","from","first_name"] "Kay"
["result",0,"message","from","last_name"] "M"
["result",0,"message","from","username"] "Gnadelwartz"
["result",0,"message","from","language_code"] "de"
["result",0,"message","from"] {"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"}
["result",0,"message","chat","id"] 586928566
["result",0,"message","chat","first_name"] "Kay"
["result",0,"message","chat","last_name"] "M"
["result",0,"message","chat","username"] "Gnadelwartz"
["result",0,"message","chat","type"] "private"
["result",0,"message","chat"] {"id":586928566,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"}
["result",0,"message","date"] 1555934204
["result",0,"message","contact","phone_number"] "222222"
["result",0,"message","contact","first_name"] "ADAC Pannenhilfe"
["result",0,"message","contact","vcard"] "BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"
["result",0,"message","contact"] {"phone_number":"222222","first_name":"ADAC Pannenhilfe","vcard":"BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"}
["result",0,"message"] {"message_id":6619,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":586928566,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934204,"contact":{"phone_number":"222222","first_name":"ADAC Pannenhilfe","vcard":"BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"}}
["result",0] {"update_id":146860897,"message":{"message_id":6619,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":586928566,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934204,"contact":{"phone_number":"222222","first_name":"ADAC Pannenhilfe","vcard":"BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"}}}
["result"] [{"update_id":146860897,"message":{"message_id":6619,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":586928566,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934204,"contact":{"phone_number":"222222","first_name":"ADAC Pannenhilfe","vcard":"BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"}}}]
[] {"ok":true,"result":[{"update_id":146860897,"message":{"message_id":6619,"from":{"id":123456789,"is_bot":false,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","language_code":"de"},"chat":{"id":586928566,"first_name":"Kay","last_name":"M","username":"Gnadelwartz","type":"private"},"date":1555934204,"contact":{"phone_number":"222222","first_name":"ADAC Pannenhilfe","vcard":"BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD"}}}]}

View File

@ -1,5 +1,5 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.62-0-g5d5dbae
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh
@ -26,13 +26,13 @@ echo "Check process_message ..."
for i in 1 2
do
[ "${i}" = "1" ] && ! which python >/dev/null 2>&1 && continue
[ "${i}" = "1" ] && echo " ... JsonDecode Phyton"
[ "${i}" = "2" ] && echo " ... JsonDecode Bash" && export BASHDECODE="yes"
[ "${i}" = "1" ] && echo " ... with JsonDecode Phyton" && unset BASHBOT_DECODE
[ "${i}" = "2" ] && echo " ... with JsonDecode Bash" && export BASHBOT_DECODE="yes"
set -x
{ process_message "0"; set +x; } >>"${LOGFILE}" 2>&1;
# output processed input
print_array "USER" "CHAT" "REPLYTO" "FORWARD" "URLS" "CONTACT" "CAPTION" "LOCATION" "MESSAGE" >"${OUTPUTFILE}"
print_array "USER" "CHAT" "REPLYTO" "FORWARD" "URLS" "CONTACT" "CAPTION" "LOCATION" "MESSAGE" "VENUE" >"${OUTPUTFILE}"
diff -c "${REFFILE}" "${OUTPUTFILE}" || exit 1
echo "${SUCCESS}"
done

View File

@ -30,8 +30,14 @@ CONTACT: FIRST_NAME ADAC
CONTACT: LAST_NAME Pannenhilfe
CONTACT: NUMBER 222222
CONTACT: USER_ID
CONTACT: VCARD BEGIN:VCARD\nVERSION:2.1\nN:Pannenhilfe;ADAC;;;\nFN:ADAC Pannenhilfe\nTEL;CELL;PREF:+49179222222\nTEL;X-Mobil:222222\nEND:VCARD
CAPTION: 0
LOCATION: LATITUDE 49.631824
LOCATION: LONGITUDE 8.377072
MESSAGE: 0 😂😝👌☺❤😕😈#⃣🌏🎉🙊🙉☕🚀✈🚂💯✔〽🔚
MESSAGE: ID 6541
VENUE: ADDRESS Am Rhein 1
VENUE: FOURSQUARE 4c4321afce54e21eee980d1a
VENUE: LATITUDE 49.631824
VENUE: LONGITUDE 8.377072
VENUE: TITLE Kolb's Biergarten

38
test/d-send_message-test.sh Executable file
View File

@ -0,0 +1,38 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh
source "./ALL-tests.inc.sh"
set -e
cd "${TESTDIR}" || exit 1
# source bashbot.sh function, uncomment if you want to test functions
# shellcheck source=./bashbot.sh
source "${TESTDIR}/bashbot.sh" source
source "${TESTDIR}/modules/background.sh"
# start writing your tests here ...
# over write sendJson to output parameter only
sendJson() {
printf 'chat:%s\tJSON:%s\nURL:%s\n\n' "${1}" "${2}" "${3}"
}
# send text input to send_message
#set -x
echo -n " Send line ..."
while IFS='' read -r line || [[ -n "$line" ]]; do
echo -n "."
send_message "123456" "$line" >>"${OUTPUTFILE}"
done < "${INPUTFILE}" 2>>"${LOGFILE}"
echo " done."
{ diff -c "${REFFILE}" "${OUTPUTFILE}" || exit 1; } | cat -v
echo " ... all \"send_message\" functions seems to work as expected."
echo "${SUCCESS}"

View File

@ -0,0 +1,18 @@
# test for text only output
This is a normal text
This is a normal text mynewlinestartshere with a line break
html_parse_mode This is a <b>HTML</b> text
html_parse_mode This is a <b>HTML</b> text mynewlinestartshere with a line break
markdown_parse_mode This is a *MARKDOWN* text
markdown_parse_mode This is a *MARKDOWN* text mynewlinestartshere with a line break
# test for keyboard, file, venue output
Text plus keyboard will appear in chat mykeyboardstartshere [ "Yep, sure" , "No, highly unlikely" ]
Text plus file will appear in chat myfilelocationstartshere /home/user/doge.jpg
Text plus location will appear in chat mylatstartshere la10 mylongstartshere lo20
Text plus vuene will appear in chat mylatstartshere la10 mylongstartshere lo20 mytitlestartshere my home myaddressstartshere Diagon Alley N. 37
All in one will appear in chat mykeyboardstartshere [ "Yep, sure" , "No, highly unlikely" ] myfilelocationstartshere /home/user/doge.jpg mylatstartshere la10 mylongstartshere lo20
# test for new inline button
Text plus keyboard will appear in chat mybtextstartshere Button Text myburlstartshere https://www...
STABILO 88/240 Fineliner point 88 mynewlinestartshere mynewlinestartshere [https://images-na.ssl-images-amazon.com/images/I/41oypA3kmHL.l_SX300.jpg] mynewlinestartshere mybtextstartshere Bei Amazon ansehen ... myburlstartshere https://www.amazon.de/dp/B014TN3JYW mytextstartshere second part of text mynewlinestartshere plus newline.

View File

@ -0,0 +1,61 @@
chat:123456 JSON:"text":"# test for text only output"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"This is a normal text"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"This is a normal text
with a line break"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":" This is a <b>HTML</b> text","parse_mode":"html"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":" This is a <b>HTML</b> text
with a line break","parse_mode":"html"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":" This is a *MARKDOWN* text","parse_mode":"markdown"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":" This is a *MARKDOWN* text
with a line break","parse_mode":"markdown"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"# test for keyboard, file, venue output"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"Text plus keyboard will appear in chat", "reply_markup": {"keyboard": [ [ "Yep, sure" , "No, highly unlikely" ] ] , "one_time_keyboard":true}
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"action": "upload_photo"
URL:https://api.telegram.org/botbashbottestscript/sendChatAction
chat:123456 JSON:"latitude": la10, "longitude": lo20
URL:https://api.telegram.org/botbashbottestscript/sendLocation
chat:123456 JSON:"latitude": la10, "longitude": lo20, "address": "Diagon Alley N. 37", "title": "my home"
URL:https://api.telegram.org/botbashbottestscript/sendVenue
chat:123456 JSON:"text":"All in one will appear in chat", "reply_markup": {"keyboard": [ [ "Yep, sure" , "No, highly unlikely" ] ] , "one_time_keyboard":true}
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"action": "upload_photo"
URL:https://api.telegram.org/botbashbottestscript/sendChatAction
chat:123456 JSON:"latitude": la10, "longitude": lo20
URL:https://api.telegram.org/botbashbottestscript/sendLocation
chat:123456 JSON:"text":"# test for new inline button"
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"Text plus keyboard will appear in chat", "reply_markup": {"inline_keyboard": [ [ {"text":"Button Text", "url":"https://www..."}] ]}
URL:https://api.telegram.org/botbashbottestscript/sendMessage
chat:123456 JSON:"text":"STABILO 88/240 Fineliner point 88
[https://images-na.ssl-images-amazon.com/images/I/41oypA3kmHL.l_SX300.jpg]
second part of text
plus newline.", "reply_markup": {"inline_keyboard": [ [ {"text":"Bei Amazon ansehen ...", "url":"https://www.amazon.de/dp/B014TN3JYW"}] ]}
URL:https://api.telegram.org/botbashbottestscript/sendMessage

60
test/d-user_is-test.sh Executable file
View File

@ -0,0 +1,60 @@
#!/usr/bin/env bash
#### $$VERSION$$ v0.7-rc1-0-g8279bdb
# include common functions and definitions
# shellcheck source=test/ALL-tests.inc.sh
source "./ALL-tests.inc.sh"
set -e
cd "${TESTDIR}" || exit 1
# source bashbot.sh function, uncomment if you want to test functions
# shellcheck source=./bashbot.sh
source "${TESTDIR}/bashbot.sh" source
# start writing your tests here ...
# first user asking for botadmin will botadmin
echo "Check \"user_is_botadmin\" ..."
echo '?' >"${ADMINFILE}" # auto mode
user_is_botadmin "BOTADMIN" || exit 1 # should never fail
user_is_botadmin "NOBOTADMIN" && exit 1 # should fail
user_is_botadmin "BOTADMIN" || exit 1 # same name as first one, should work
if [ "$(cat "${ADMINFILE}")" = "BOTADMIN" ]; then
echo " ... \"user_is_botadmin\" seems to work as expected."
else
exit 1
fi
echo "${SUCCESS}"
# lets see If UAC works ...
echo "Check \"user_is_allowed\" ..."
echo " ... with not rules"
user_is_allowed "NOBOTADMIN" "ANYTHING" && exit 1 # should always fail because no rules exist
user_is_allowed "BOTADMIN" "ANYTHING" && exit 1 # should fail even is BOTADMIN
echo "${SUCCESS}"
echo " ... with BOTADMIN:*:*"
echo 'BOTADMIN:*:*' >"${ACLFILE}" # RULE allow BOTADMIN everything
user_is_allowed "BOTADMIN" "ANYTHING" || exit 1 # should work now
user_is_allowed "NOBOTADMIN" "ANYTHING" && exit 1 # should fail because user is not listed
echo "${SUCCESS}"
echo " ... with NOBOTAMIN:SOMETHING:*"
echo 'NOBOTADMIN:SOMETHING:*' >>"${ACLFILE}" # RULE allow NOBOTADMIN something
user_is_allowed "BOTADMIN" "ANYTHING" || exit 1 # should work
user_is_allowed "BOTADMIN" "SOMETHING" || exit 1 # should work
user_is_allowed "NOBOTADMIN" "SOMETHING" || exit 1 # should work now
user_is_allowed "NOBOTADMIN" "ANYTHING" && exit 1 # should fail because only SOMETHING is listed
echo "${SUCCESS}"
echo " ... \"user_is_allowed\" seems to work as expected."