Compare commits

..

12 Commits

Author SHA1 Message Date
root
b4182cb71f correction imports 2026-02-04 18:39:27 +01:00
root
173bb371eb refactor 2026-02-04 18:35:38 +01:00
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
10 changed files with 91 additions and 38 deletions

13
.env Normal file → Executable file
View File

@@ -1,8 +1,7 @@
## Matrix env variables
VERBOSE=True VERBOSE=True
SYSTEMD_LOGGING=False SYSTEMD_LOGGING=True
matrix_home_server="https://matrix.agent.ministere_example.tchap.gouv.fr" matrix_home_server="https://matrix.agent.dev-durable.tchap.gouv.fr"
matrix_bot_username="jean.quidam@ministere_example.gouv.fr" matrix_bot_username="@chat.beta-developpement-durable.gouv.fr:agent.dev-durable.tchap.gouv.fr"
matrix_bot_password="test" matrix_bot_password="C.5;oTYw+Mksn<,7jtgx/TbWHY2Ugf"
#https_proxy=http://adresse.du.proxy:port/ salt=b'I\x87>\xe5\x91\xbdw\x99\xb3\xea7\xc2\xa6\xbf\x8f#'
https_proxy=http://pfrie-std.proxy.e2.rie.gouv.fr:8080/

5
.gitignore vendored Executable file
View File

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

21
README.md Normal file → Executable file
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.)

28
callbacks.py Executable file
View File

@@ -0,0 +1,28 @@
from functools import wraps
from nio import MatrixRoom, Event
from matrix_bot.config import logger
from matrix_bot.client import MatrixClient
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

9
config.py Executable file
View File

@@ -0,0 +1,9 @@
from pydantic import Field
from tchap_bot.config import Config
class ConfigProxy(Config):
https_proxy: str = Field("", description="Proxy URL")
env_config = ConfigProxy()

0
fra_wikipedia_2021_10K-sentences.txt Normal file → Executable file
View File

0
markov.py Normal file → Executable file
View File

21
tchapbeta.py → tchap-beta.py Normal file → Executable file
View File

@@ -1,25 +1,17 @@
import asyncio import asyncio
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 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 tchap_bot.config import Config
from config import env_config
from callbacks import properly_fail
from markov import parle from markov import parle
class ConfigProxy(Config):
https_proxy: str = Field("", description="Proxy URL")
env_config = ConfigProxy()
# 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,16 +24,18 @@ 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")
tchap_bot = MatrixBot( tchap_bot = MatrixBot(
env_config.matrix_home_server, env_config.matrix_home_server,
env_config.matrix_bot_username, env_config.matrix_bot_username,
@@ -57,3 +51,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 Executable 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