Compare commits

..

10 Commits

Author SHA1 Message Date
MALINGREY Adrien
3712c4ddbd personnalisation du gestionnaire d'erreur 2026-02-04 16:57:27 +00:00
MALINGREY Adrien
dccbaa332a répond en message direct ou dans les salons publics en cas d'interpellation 2026-02-04 16:33:57 +00:00
MALINGREY Adrien
75b0fb91b3 renommage 2026-02-04 16:01:45 +00:00
MALINGREY Adrien
dc9106b8fd Ajout EnvironmentFile 2026-02-04 16:01:18 +00:00
MALINGREY Adrien
df7bd7415c ajout chown 2026-02-04 15:56:50 +00:00
MALINGREY Adrien
835b415bc6 Ajout de commentaires 2026-02-04 14:52:42 +00:00
MALINGREY Adrien
1be9fd8a1c renommage des fichiers en tchap-beta 2026-02-04 14:34:17 +00:00
MALINGREY Adrien
361f22e014 Installation en tant que service 2026-02-04 14:30:26 +00:00
MALINGREY Adrien
76d0627aa9 Add .gitignore 2026-02-04 14:13:23 +00:00
MALINGREY Adrien
f7bd4393f2 Edit README.md 2026-02-04 14:06:01 +00:00
5 changed files with 68 additions and 21 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
.env
.venv/
session.txt
store/

View File

@@ -1,6 +1,6 @@
# Tchap Beta # Tchap Beta
Agent conversationnel à petit modèle de langage de bêtise artificelle pour la messagerie Tchap. Agent conversationnel à petit modèle de langage de bêtise artificielle pour la messagerie Tchap.
Basé sur [tchapbot](https://code.peren.gouv.fr/open-source/tchapbot). Basé sur [tchapbot](https://code.peren.gouv.fr/open-source/tchapbot).
@@ -8,7 +8,7 @@ Voir la [documentation technique - Bot et Integrations Tchap](https://aide.tchap
## Installation ## Installation
``` ```bash
git clone https://gitlab-forge.din.developpement-durable.gouv.fr/drieat-if/dsin/usrt/tchap-beta.git git clone https://gitlab-forge.din.developpement-durable.gouv.fr/drieat-if/dsin/usrt/tchap-beta.git
cd tchap-beta cd tchap-beta
python -m venv .venv python -m venv .venv
@@ -24,7 +24,22 @@ editor .env
python -c 'import secrets; print("salt=", secrets.token_bytes(16), sep="")' >> .env python -c 'import secrets; print("salt=", secrets.token_bytes(16), sep="")' >> .env
# Lancer # Lancer
python tchapbeta.py python tchap-beta.py
``` ```
Pour que les messages apparaissent authentifiés, il faut se connecter sur [Tchap](https://www.tchap.gouv.fr/) avec le compte du bot et taper dans un salon `/verify <device-id> <device-fingerprint>` avec les informations indiquées au démarrage du bot (sans les espaces). Pour que les messages apparaissent authentifiés, il faut se connecter sur [Tchap](https://www.tchap.gouv.fr/) avec le compte du bot et taper dans un salon `/verify <device-id> <device-fingerprint>` avec les informations indiquées au démarrage du bot (sans les espaces).
## Installer en tant que service
En plus des commandes précédentes :
```bash
sudo cp tchap-beta.service /lib/systemd/system/
cd ..
mv tchap-beta /opt/
sudo adduser --system chatbeta
sudo chown chatbeta -R /opt/tchap-beta
sudo systemctl enable --now tchap-beta.service
````
(L'emplacement et le nom d'utilisateur sont libres tant que c'est cohérent avec le service.)

View File

@@ -1,16 +1,18 @@
import asyncio import asyncio
from functools import wraps
from nio import MatrixRoom, Event, AsyncClient from nio import MatrixRoom, Event
from nio.crypto import ENCRYPTION_ENABLED from nio.crypto import ENCRYPTION_ENABLED
from pydantic import Field from pydantic import Field
from matrix_bot.bot import MatrixBot from matrix_bot.bot import MatrixBot
from matrix_bot.client import MatrixClient from matrix_bot.client import MatrixClient
from matrix_bot.callbacks import properly_fail
from matrix_bot.eventparser import MessageEventParser, ignore_when_not_concerned, EventNotConcerned from matrix_bot.eventparser import MessageEventParser, ignore_when_not_concerned, EventNotConcerned
from matrix_bot.config import logger
from tchap_bot.config import Config from tchap_bot.config import Config
from markov import parle from markov import parle
@@ -20,6 +22,28 @@ class ConfigProxy(Config):
env_config = ConfigProxy() env_config = ConfigProxy()
def properly_fail(function):
"""use this decorator so that your async callback never crash, log the error and return a message to the room"""
@wraps(function)
def decorated(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
function_instance = function(room, message, matrix_client)
async def inner():
try:
return await function_instance
except Exception as unexpected_exception: # noqa
await matrix_client.send_text_message(room.room_id, "Oups, j'ai buggué 😿", "m.notice")
logger.warning(f"command failed with exception : {unexpected_exception}")
exit()
finally:
await matrix_client.room_typing(room.room_id, typing_state=False)
return inner()
return decorated
# le décorateur @properly_fail va permettre à la commande de laisser un message d'erreur si la commande plante et # le décorateur @properly_fail va permettre à la commande de laisser un message d'erreur si la commande plante et
# d'envoyer le message que le bot n'est plus en train d'écrire # d'envoyer le message que le bot n'est plus en train d'écrire
# la fonction va être appelée dans tous les cas, le décorateur @ignore_when_not_concerned # la fonction va être appelée dans tous les cas, le décorateur @ignore_when_not_concerned
@@ -32,13 +56,14 @@ async def repond(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
# il ne va pas répondre à ses propres messages # il ne va pas répondre à ses propres messages
event_parser.do_not_accept_own_message() event_parser.do_not_accept_own_message()
if not (message.formatted_body and matrix_client.user_id in message.formatted_body): # ne répond qu'en message direct ou dans un salon s'il est interpellé avec @identifiant.du.bot dans le corps du message
if len(room.users) > 2 and not (message.formatted_body and matrix_client.user_id in message.formatted_body):
raise EventNotConcerned raise EventNotConcerned
reponse = parle() reponse = parle()
# il envoie l'information qu'il est en train d'écrire # il envoie l'information qu'il est en train d'écrire
await matrix_client.room_typing(room.room_id) await matrix_client.room_typing(room.room_id)
await asyncio.sleep(len(reponse) / 20) await asyncio.sleep(len(reponse) / 30)
# il envoie le message # il envoie le message
await matrix_client.send_text_message(room.room_id, reponse, "m.notice") await matrix_client.send_text_message(room.room_id, reponse, "m.notice")
@@ -57,3 +82,4 @@ tchap_bot.matrix_client.matrix_config.join_on_invite = True
tchap_bot.callbacks.register_on_message_event(repond) tchap_bot.callbacks.register_on_message_event(repond)
tchap_bot.run() tchap_bot.run()

16
tchap-beta.service Normal file
View File

@@ -0,0 +1,16 @@
# /lib/systemd/system/tchap-beta.service
[Unit]
Description=Tchap Beta
After=network.target
[Service]
User=chatbeta
WorkingDirectory=/opt/tchap-beta
ExecStart=/opt/tchap-beta/.venv/bin/python tchap-beta.py
Restart=always
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=/opt/tchap-beta/.env
[Install]
WantedBy=multi-user.target

View File

@@ -1,14 +0,0 @@
# /lib/systemd/system/tchapbeta.service
[Unit]
Description=Tchap Beta
After=network.target
[Service]
User=chatbeta
WorkingDirectory=/opt/tchapbeta
ExecStart=/opt/tchapbeta/.venv/bin/python tchapbeta.py
Restart=always
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target