Bots
Bots are simply Telegram accounts operated by software, not people
At the core, Telegram bots are special accounts that do not require an additional phone number to set up.
bot global schematic
We can access our "Pi0_bot" using :
- "Telegram" application, as from my mobile "Mi9" { text displayed right}
- python code, to send an "alarm" from R3, "odin" {text displayed left, as bot answers to Mi9}
.------------------------------------------------.
( )
. Internet .
( )
. .
| |
| .==================================. |
| ( ) |
| . Telegram . |
| | | |
| | | |
| | .------. |
| | .----------------- | Mi9 | |
| | | .------. |
| | | | |
| | | | |
| . v . |
| ( .---------. ) |
| .======= | Pi0_bot | ==============. |
| .---------. |
| ^ |
| | |
| | |
| | |
| .---------. |
| | R3_odin | |
| .---------. |
| |
. .
( )
.----------------------------------------------------.
How to create a bot
Just talk to BotFather
/newbot
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
rita_bot
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
rita_user_bot
Done! Congratulations on your new bot. You will find it at
t.me/rita_user_bot.
You can now add a description, about section and profile picture for your bot, see /help for a list of commands.
what is the chat_id ?
user_id is the Telegram ID of the user sending a message to bot.
chat_id is the Telegram ID of the chat where a message is being sent to bot.
So, in one to one conversation, the user will send a message in his own chat (with respect to bot). That's the reason both are same.
stack overflow
# Sebas [304588090]
# Miquel [441014222]
# ESP [453540582]
# Irina [819799527]
# Albert [ ]
How to change bot description
- access BotFather
- enter /mybots
- a list of bots comes up - select one
- here you can
- API Token
- Edit Bot - Edit Name, Edit Description, Edit About, Edit Botpic, Edit Commands
- Bot Settings - Inline Mode, Allow Groups ? Group Privacy, Payments, Domain
- Payments
- Transfer Ownership
- Delete Bot
Making requests to a Telegram Bot
From bots API :
All queries to the Telegram Bot API must be served over HTTPS and need to be presented in this form:
https://api.telegram.org/bot<token>/METHOD_NAME
Like this for example:
https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe
We support GET and POST HTTP methods.
We support four ways of passing parameters in Bot API requests:
- URL query string
- application/x-www-form-urlencoded
- application/json (except for uploading files)
- multipart/form-data (use to upload files)
The response contains a JSON object, which always has a Boolean field 'ok'
and may have an optional String field 'description' with a human-readable description of the result.
If 'ok' equals true, the request was successful and the result of the query can be found in the 'result' field.
In case of an unsuccessful request, 'ok' equals false and the error is explained in the 'description'.
Telegram Bot API Client Framework
We have
- tgbotapi : pypi ,
github , with wiki
- telebot - pyTelegramBotAPI : github
simple user code ,
detailed example ,
30 code examples with links,
all API commands {***}
pyTelegramBotAPI is a python implementation of the Telegram Bot API
- python-telegram-bot : github ,
wiki ,
examples ,
documentation ,
homepage
user code ,
more
- telegram.ext {gracies, Ramon} : es un "package" de python-telegram-bot
telegram.ext package ,
your first bot , step by step ;
sample code, step by step ;
another
- Albert 202105 : telepot ! SAG : R4
telebot details
The module is here : eternnoir at https://github.com/eternnoir/pyTelegramBotAPI
The minimal code is
import telebot
bot = telebot.TeleBot(TOKEN) # create Telegram bot object
@bot.message_handler(commands=['ajuda']) # define msg handler
def send_welcome(message):
bot.reply_to(message, "How are you doing?")
bot.set_update_listener(my_listener) # register listener
bot.polling() # poll Telegram servers for new messages
Advanced use of the API - Asynchronous delivery of messages
There exists an implementation of TeleBot which executes all send_xyz and the get_me functions asynchronously.
This can speed up you bot significantly, but it has unwanted side effects if used without caution.
To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
tbot = telebot.AsyncTeleBot( "MY_TOKEN" )
tbot = telebot.AsyncTeleBot( os.environ[ "TELEBOT_BOT_TOKEN" ] )
Now, every function that calls the Telegram API is executed in a separate thread.
The functions are modified to return an AsyncTask instance (defined in util.py).
telepot details
Es el que fa servir en Albert
- reference
- github , as "Issues"
- 30 examples
- homepage - how to install
sebas@r4:~/python/telegram/telepot $ python3 -m pip install telepot
* BotFather
** name = sag_r4_temp
** username = sag_r4_temp_bot
Use this token to access the HTTP API:
1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi
sebas@r4:~/python/telegram/telepot $ cat /etc/environment
SAG_TG_R4_TKN="1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi"
sebas@r4:~/python/telegram/telepot $ ./1_llegir_token.py
llegit token [ 1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi ].
llargada [ 46 ].
sebas@r4:~/python/telegram/telepot $ ./2_get_me.py
{'id': 1801372584, 'is_bot': True, 'first_name': 'sag_r4_temp', 'username': 'sag_r4_temp_bot',
'can_join_groups': True, 'can_read_all_group_messages': False, 'supports_inline_queries': False}
- all user info :
bot = telepot.Bot(TOKEN)
info = bot.getChat(chat_id) # retrieve all the info of a user
- get user_id :
bot = telepot.Bot(TOKEN)
info = bot.getChat(user_id)
print(info)
- get name :
entity = client.get_entity(chat_id)
name = entity.chat.name
- ask for some user answer :
stackoverflow
import telepot
from telepot.loop import MessageLoop
import time
bot = telepot.Bot('my_token')
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
send1 = bot.sendMessage(chat_id,'whats your name?')
if send1:
text1 = msg['text']
print(text1)
MessageLoop(bot,handle).run_as_thread()
while 1:
time.sleep(1)
Here text1 variable is the reply associate to question "whats your name?"
- El seu codi es :
$ cat send_temp_to_bot.py
import os
import time
import telepot
def my_handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print( 'received command: {%s}' % command )
if command == '/temp':
mytemp = os.popen('sudo piheat-cli read').read()
bot.sendMesage( chat_id, mytemp )
else:
bot.sendMesage( chat_id, 'huh?' )
bot = telepot.Bot( '12345' )
print( bot.getMe() )
bot.message_loop( my_handle )
white True:
time.sleep(10)
- telepot is discontinued - Aug 2, 2018
telepot contents
20210612 I cant read "username" -
sebas@r4:~/python/telegram/telepot $ python3
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import telepot
>>> dir(telepot)
['Bot', 'DelegatorBot', 'PY_3', 'SpeakerBot', '_BotBase', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__path__', '__spec__', '__version__', '__version_info__', '_dismantle_message_identifier',
'_file_type', '_find_first_key', '_isfile', '_isstring', '_rectify', '_split_input_media_array', '_string_type', '_strip',
'all_content_types', 'api', 'bisect', 'chat_flavors', 'collections', 'exception', 'filtering', 'flance', 'flavor', 'flavor_router',
'fleece', 'glance', 'hack', 'helper', 'inline_flavors', 'inspect', 'io', 'is_event', 'json', 'message_identifier',
'origin_identifier', 'peel', 'queue', 'sys', 'threading', 'time', 'traceback']
>>> dir(telepot.Bot)
['Scheduler', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'_api_request', '_api_request_with_file', 'addStickerToSet', 'answerCallbackQuery', 'answerInlineQuery', 'answerPreCheckoutQuery',
'answerShippingQuery', 'createNewStickerSet', 'deleteChatPhoto', 'deleteChatStickerSet', 'deleteMessage', 'deleteStickerFromSet',
'deleteWebhook', 'download_file', 'editMessageCaption', 'editMessageLiveLocation', 'editMessageReplyMarkup', 'editMessageText',
'exportChatInviteLink', 'forwardMessage', 'getChat', 'getChatAdministrators', 'getChatMember', 'getChatMembersCount', 'getFile',
'getGameHighScores', 'getMe', 'getStickerSet', 'getUpdates', 'getUserProfilePhotos', 'getWebhookInfo', 'handle', 'kickChatMember',
'leaveChat', 'message_loop', 'pinChatMessage', 'promoteChatMember', 'restrictChatMember', 'router', 'scheduler', 'sendAudio',
'sendChatAction', 'sendContact', 'sendDocument', 'sendGame', 'sendInvoice', 'sendLocation', 'sendMediaGroup', 'sendMessage',
'sendPhoto', 'sendSticker', 'sendVenue', 'sendVideo', 'sendVideoNote', 'sendVoice', 'setChatDescription', 'setChatPhoto',
'setChatStickerSet', 'setChatTitle', 'setGameScore', 'setStickerPositionInSet', 'setWebhook', 'stopMessageLiveLocation',
'unbanChatMember', 'unpinChatMessage', 'uploadStickerFile']
>>> dir(telepot.Bot.getChat)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__',
'__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>>
sending alerts to TG bot
First we define what to send, then call the function :
nicolau@mars:~/sebas/python/telegram$ cat msg_a_tg.sh
#!/bin/bash
# send a msg to Telegram
# used from :
# 1) /home/nicolau/.config/systemd/user/mars_start.service
# 2) crontab
myLog="/home/sebas/logs/msg_a_tg.log"
date_name=`date +"Y%y/M%m/D%d"`
time_name=`date +"h%H:m%M"`
szTs="$date_name - $time_name"
szID='*** ('$szTs') *** ('$0') ***'
echo -e "\n(1) msg id is - $szID" >> $myLog
# eIP=$(curl -m 2 -s icanhazip.com) >> $myLog 2>&1
eIP=$(curl -m 2 -s http://checkip.amazonaws.com) >> $myLog 2>&1
rc1=$?
# echo ">>> (2) icanhazip rc ($rc1)" >> $myLog
echo ">>> (2) checkip amazonaws rc ($rc1)" >> $myLog
nom_wifi=$(/sbin/iwgetid) >> $myLog 2>&1
rc2=$?
echo ">>> (3) iwgetid rc ($rc2)" >> $myLog
szNet='-no wifi-'
if [ $rc2 -eq 0 ]
then
szWifi=$(echo $nom_wifi| cut -d'"' -f 2)
szNet=${szWifi//_/ }
fi
szTG="($szTs) [$HOSTNAME] boot, [$eIP] $szNet"
if [ $rc1 -eq 0 ]
then
echo -e "+++ Send msg to TG bot" >> $myLog
echo "$szTG" >> $myLog
/home/sebas/python/telegram/client.py "$szTG"
rc3=$?
echo ">>> Sent msg to TG bot, rc ($rc3)" >> $myLog
else
echo "--- dont send to TG as we have no eIP ---" >> $myLog
fi
exit 0
And here is the implementation of the sender :
nicolau@mars:~/sebas/python/telegram$ cat client.py
#!/usr/bin/env python3
import logging
import sys
import requests #
requests : HTTP for Humans
fnLog = '/home/nicolau/logs/send_telegram.log'
logging.basicConfig( filename=fnLog, level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S' )
bot_token = os.environ["SAG_tg_tkn"] # get token from envir var, set
here (at /etc/environment)
bot_token = '1234567890987654321' # ... or write it explicit here
bot_chatID = '304588090'
bot_Name = 'nom_del_bot' # not provided by BotFather - I use it just to improve clarity, to know which bot am I sending
# define "send" function
def telegram_bot_sendtext(bot_message):
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message ; maybe "parseMode"
try:
response = requests.get(send_text)
return response.json()
except requests.exceptions.RequestException as e:
return "--- requests.get() error ---"
# start main program
szTxt = " *** MARS envia al bot {"+bot_Name+"} del TG *** "
numArg = len(sys.argv)
if ( numArg > 1 ) :
szTxt = sys.argv[1]
logging.info( '\n *** MARS envia al bot del TG (%s).', szTxt )
logging.warning( '+++ Texte per al bot {%s}', szTxt )
tg_rc = telegram_bot_sendtext( szTxt )
logging.debug( f'RC {tg_rc}' )
sys.exit()
If the text you send has a plus sign ("+"), you have to use "%2B" instead, so it is not converted to a space
*** (./client.py) anem a enviar al bot.
08/04/2024 11:05:47 >>> Texte a TG {A%2BQ}
08/04/2024 11:05:47 Starting new HTTPS connection (1): api.telegram.org:443
08/04/2024 11:05:47 https://api.telegram.org:443 "GET /bot123:ABC/sendMessage?chat_id=987&parseMode=Markdown&text=A%2BQ HTTP/1.1" 200 266
08/04/2024 11:05:47 RC {{'ok': True, 'result': {'message_id': 7997,
'from': {'id': 1137683, 'is_bot': True, 'first_name': 'r0', 'username': 'alertas_bot'},
'chat': {'id': 3045090, 'first_name': 'Seb', 'last_name': 'Alt', 'username': 'Ceba3', 'type': 'private'},
'date': 1712567147,
'text': 'A+Q'}
}}
els meus bots
En tinc 3 - use "/mybots" at BotFather :
I un en construccio :
[r3] name = sag_r3_server / username = sag_r3_server_bot
Accepta comandes com
Per escriure a qualsevol d'ells, fes servir
sebas@minie:~/dades/python/telegram/proves_tg_bot.py
pi@pi0:~/python/bot $ ./curl_bot.sh
{"ok":true,"result":{"message_id":13131,"from":{"id":1136067683,"is_bot":true,"first_name":"sag_r0","username":"mars_super_bot"},
"chat":{"id":304588090,"first_name":"Sebastia","last_name":"Altemir","username":"Ceba3","type":"private"},
"date":1744735919,"text":"La Raspberry te saluda."}}
pi@R4:~/python/telegram/telepot $ ./5_curl_bot.sh
{"ok":true,"result":{"message_id":598,"from":{"id":1801372584,"is_bot":true,"first_name":"sag_r4","username":"sag_r4_temp_bot"},
"chat":{"id":304588090,"first_name":"Sebastia","last_name":"Altemir","username":"Ceba3","type":"private"},
"date":1744736684,"text":"{r4} la Raspberry te saluda."}}
Atenció :
- va be al R0
- no surt res al R4 - va OK 20250415
el codi dels meus bots
En tinc de 2 tipus :
(telebot) Pi0 and MARS,
(telepot) R4 ;
pendent (telegram) R3
Pi0 : telebot
Tenim bot_pihole.py, basat en
aquest sample
Install requisites :
# python3 -m pip install gpiozero
# python3 -m pip install pyTelegramBotAPI
Has problems when network fails, as there are many uncatched exceptions, whose documentation I cant find
sebas@pi0alby:/home/sebas/python/bot $ cat bot_pihole.py
# bot service
# starts from /etc/systemd/system/my_bot.service
# logs to /home/pi/logs/bot_service.log
import telebot # sudo pip3 install pyTelegramBotAPI
logger = telebot.logger
telebot.logger.setLevel(logging.INFO) # DEBUG, ERROR
bot = telebot.TeleBot(TOKEN) # create a new Telegram Bot object
# bot = telebot.AsyncTeleBot( os.environ[ "TELEBOT_BOT_TOKEN" ] ) # set at /etc/environment
bot.set_update_listener(listener) # register listener
my_user = "--- no user ---"
try:
me_bot = bot.get_me() # getMe :
my_user = me_bot.first_name
except:
logger.error( "--- GET_ME unexpected error --- " + str( sys.exc_info()[0] ) )
# getMe() output : {'id': 1136067683, 'is_bot': True, 'first_name': 'mars_ubuntu', 'username': 'mars_super_bot', 'last_name': None,
# 'language_code': None, 'can_join_groups': True, 'can_read_all_group_messages': False, 'supports_inline_queries': False}
try:
# Upon calling this function, TeleBot starts polling the Telegram servers for new messages.
# bot.polling()
# - none_stop: True/False (default False) - Don't stop polling when receiving an error from the Telegram servers
# - interval: True/False (default False) - The interval between polling requests
# - timeout: integer (default 20) - Timeout in seconds for long polling.
bot.polling( none_stop=True, interval=5, timeout=123 )
except Exception as e:
logger.error( "--- POLL EXCEPTION ---" + str(e) )
time.sleep(30)
except ( NewConnectionError, ConnectionError ):
logger.error( "--- ConnectionError ---" )
time.sleep(30)
except:
print( "--- POLL unexpected error --- " + str( sys.exc_info()[0] ) )
time.sleep(30)
### --- end of code
Stored at ramonet github
Starts as a service :
pi@pi0:~ $ cat /etc/systemd/system/my_bot.service
[Unit]
Description=My PWM service - /etc/systemd/system/my_bot.service - (v 1.b)
; 20200813 1.a - start
; 20200813 1.b - stdout and stderr
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
; simple - a long-running process that does not background itself and stays attached to the shell
; forking - a typical daemon that forks itself detaching it from the process that ran it, effectively backgrounding itself
; oneshot - a short-lived process that is expected to exit
WorkingDirectory=/home/pi/python/bot/
ExecStart=/home/pi/python/bot/bot_pihole.py
StandardOutput=append:/home/pi/logs/bot_service.log
StandardError=inherit
Restart=always
RestartSec=3
SyslogIdentifier=bot_service
User=pi
TimeoutStartSec=infinity
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
Commands to manage the service :
# sudo systemctl status my_bot
# sudo systemctl enable my_bot
# sudo systemctl stop my_bot
# sudo systemctl start my_bot
# sudo systemctl status my_bot
Lets display its status :
pi@pi0:~/python/bot $ sudo systemctl status my_bot
● my_bot.service - R0 bot service - /etc/systemd/system/my_bot.service - (v 2.a)
Loaded: loaded (/etc/systemd/system/my_bot.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2022-07-30 13:52:46 CEST; 55min ago
Main PID: 9125 (python3)
Tasks: 4 (limit: 877)
CGroup: /system.slice/my_bot.service
└─9125 python3 /home/pi/python/bot/bot_pihole.py
Jul 30 13:52:46 pi0 systemd[1]: Started R0 bot service - /etc/systemd/system/my_bot.service - (v 2.a).
And here it is :
pi@pi0:~/python/bot $ ps -ef | grep b[o]t
pi 20903 1 73 12:13 ? 00:00:02 /usr/bin/python3 /home/pi/python/bot/bot_pihole.py
How to access it : search TG for "sag_r0"
Minie sends to r0_bot
Cada nit s'envia un missatge, si m'he deixat la maquina engegada :
sebas@minie:~$ crontab -l
# m h dom mon dow command
08 02 * * * /home/sebas/eines/minie_start_tg.sh KRON
Que ve a fer
/home/sebas/dades/python/telegram/1_client.py "$szTG"
Que te codificat
try:
response = requests.get(send_text)
return response.json()
except requests.exceptions.RequestException as e:
return "--- requests.get() error ---"
I que deix un log a /home/sebas/logs/send_telegram.log
Compte : en engegar la maquina, tambe s'envia un missatge al bot :
/home/sebas/.config/systemd/user/2_minie_start_tg.service
/home/sebas/eines/minie_start_tg.sh boot --> minie_start_tg.log
/home/sebas/dades/python/telegram/1_client.py --> send_telegram.log
few URLs we used
MARS : another telebot
Mentre el Arduino estigui conectat al MARS via USB, tenim un codi "servidor" del bot "rita" en el MARS :
/home/nicolau/sebas/python/bot $ cat 1_bot_pihole_2.py
TOKEN_RITA = os.environ.get('MY_TOKEN_RITA')
TOKEN = TOKEN_RITA
...
## -------------------------------------------------------------
@bot.message_handler(commands=['L1']) # LED on
def command_hn(m):
cid = m.chat.id
missatge = "Piscina-ON\n"
logger.info( "Ordre a Arduino [Piscina-ON]" )
arduino.write(missatge.encode('utf-8'))
diuArduino = arduino.readline().decode('UTF-8').strip()
logger.info( "Arduino diu {" + diuArduino + "}" )
bot.send_message( cid, "LED ON" )
## -------------------------------------------------------------
@bot.message_handler(commands=['L0']) # LED off
def command_hn(m):
cid = m.chat.id
missatge = "Piscina-OFF\n"
logger.info( "Ordre a Arduino [Piscina-OFF]" )
arduino.write(missatge.encode('utf-8'))
diuArduino = arduino.readline().decode('UTF-8').strip()
logger.info( "Arduino diu {" + diuArduino + "}" )
bot.send_message( cid, "LED OFF" )
## -------------------------------------------------------------
...
R3 : python-telegram-bot.ext
Gracies, Ramon ! *** encara per implementar *** (20201003)
Homepage : https://python-telegram-bot.org
telegram-bot documentation :
telegram.ext package ,
telegram package ,
telegram-utils package
pypi telegram bot ,
extensions first bot
questions at stackOverflow
The telegram.ext submodule is built on top of the pure API implementation,
and it consists of several classes, but the two most important ones are telegram.ext.Updater and telegram.ext.Dispatcher
"dispatcher" : this class dispatches all kinds of updates to its registered handlers
"updater" : its purpose is to receive the updates from Telegram and to deliver them to said dispatcher
The Updater class continuously fetches new updates from telegram and passes them on to the Dispatcher class.
If you create an Updater object, it will create a Dispatcher for you and link them together with a Queue.
Les capceleres del codi python son :
$ cat PS_telegram_bot1.1.py
import telegram
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
python-telegram-bot on github ,
github examples ,
30 real examples showing how to use telegram.ext.CommandHandler() [***]
Els exemples que ens interessen, d'entrada son :
Real world examples
R4 - telepot
We have a bot server code as
$ sebas@r4:~/python/telegram/telepot $ cat 3_alby_bot.py
import telepot # https://telepot.readthedocs.io/en/latest/
# start of code
my_envir_var="SAG_TG_R4_TKN" # see /etc/environment - compte si engeguem com servei
szText = " " # create var to be used in handle
szVersio = "v 2.b" # identify code version
fnLog = '/home/sebas/logs/log_del_bot.log'
logging.basicConfig( filename=fnLog, level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S' )
logging.info( '\n\n *** R4 bot starts {%s} ***' % szVersio )
# message handler code
def my_handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print( 'received command: {%s}' % command )
szText = "*** received command is {%s} ***" % new_command
logging.info( szText )
# bot code
try:
my_token = os.environ[ my_envir_var ] # /etc/environment if not a service
bot = telepot.Bot( my_token )
print( bot.getMe() )
bot.message_loop(my_handle) # set handler
except KeyError:
print( "Environment variable (%s) does not exist" % my_envir_var )
while True:
time.sleep(10)
We define a "simple" user service :
sebas@r4:~ $ cat /home/pi/.config/systemd/user/r4_bot.service
[Unit]
Description=Raspberry 4 bot code - /home/pi/.config/systemd/user/r4_bot.service - (v 1.c)
; v 1.a - start
; v 1.b - run "simple" and not "forking" to get python messages into log file
; v 1.c - remove StdOut and StdErr - we use "logging" inside pythyon
; systemctl --user status r4_bot.service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
; simple - a long-running process that does not background itself and stays attached to the shell
; forking - a typical daemon that forks itself detaching it from the process that ran it, effectively backgrounding itself
; oneshot - a short-lived process that is expected to exit
WorkingDirectory=/home/sebas/python/telegram/telepot/
ExecStart=/home/sebas/python/telegram/telepot/3_alby_bot.py
EnvironmentFile=/home/pi/python/telegram/telepot/my_bot.conf
; StandardOutput=append:/home/sebas/logs/r4_bot.log
; StandardError=inherit
Restart=always
RestartSec=5
SyslogIdentifier=r4_bot
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
Set environment for process (in a file) :
cat /home/pi/python/telegram/telepot/my_bot.conf
Environment=My_IP=192.168.1.2
We display its status by
sebas@r4:~ $ systemctl --user status r4_bot.service
● r4_bot.service - Raspberry 4 bot code - /home/sebas/.config/systemd/user/r4_bot.service - (v 1.c)
Loaded: loaded (/home/sebas/.config/systemd/user/r4_bot.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2021-06-13 11:04:13 CEST; 3min 3s ago
Main PID: 7419 (python3)
CGroup: /user.slice/user-1001.slice/user@1001.service/r4_bot.service
└─7419 python3 /home/sebas/python/telegram/telepot/3_alby_bot.py
Drawback : if python bot code runs in background ("forking"), its messages are lost -> we use "simple"
els bots de'n ESP
RRG []