Compare commits
13 Commits
caf04ec659
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
ccba64ed35
|
|||
|
|
b4182cb71f | ||
|
|
173bb371eb | ||
|
|
3712c4ddbd | ||
|
|
dccbaa332a | ||
|
|
75b0fb91b3 | ||
|
|
dc9106b8fd | ||
|
|
df7bd7415c | ||
|
|
835b415bc6 | ||
|
|
1be9fd8a1c | ||
|
|
361f22e014 | ||
|
|
76d0627aa9 | ||
|
|
f7bd4393f2 |
13
.env
Normal file → Executable file
13
.env
Normal file → Executable file
@@ -1,8 +1,7 @@
|
||||
## Matrix env variables
|
||||
|
||||
VERBOSE=True
|
||||
SYSTEMD_LOGGING=False
|
||||
matrix_home_server="https://matrix.agent.ministere_example.tchap.gouv.fr"
|
||||
matrix_bot_username="jean.quidam@ministere_example.gouv.fr"
|
||||
matrix_bot_password="test"
|
||||
#https_proxy=http://adresse.du.proxy:port/
|
||||
SYSTEMD_LOGGING=True
|
||||
matrix_home_server="https://matrix.agent.dev-durable.tchap.gouv.fr"
|
||||
matrix_bot_username="@chat.beta-developpement-durable.gouv.fr:agent.dev-durable.tchap.gouv.fr"
|
||||
matrix_bot_password="C.5;oTYw+Mksn<,7jtgx/TbWHY2Ugf"
|
||||
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
5
.gitignore
vendored
Executable file
@@ -0,0 +1,5 @@
|
||||
.env
|
||||
.venv/
|
||||
session.txt
|
||||
store/
|
||||
__pycache__
|
||||
21
README.md
Normal file → Executable file
21
README.md
Normal file → Executable file
@@ -1,6 +1,6 @@
|
||||
# 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).
|
||||
|
||||
@@ -8,7 +8,7 @@ Voir la [documentation technique - Bot et Integrations Tchap](https://aide.tchap
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
```bash
|
||||
git clone https://gitlab-forge.din.developpement-durable.gouv.fr/drieat-if/dsin/usrt/tchap-beta.git
|
||||
cd tchap-beta
|
||||
python -m venv .venv
|
||||
@@ -24,7 +24,22 @@ editor .env
|
||||
python -c 'import secrets; print("salt=", secrets.token_bytes(16), sep="")' >> .env
|
||||
|
||||
# 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).
|
||||
|
||||
## 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
28
callbacks.py
Executable 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
9
config.py
Executable 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
0
fra_wikipedia_2021_10K-sentences.txt
Normal file → Executable file
10
markov.py
Normal file → Executable file
10
markov.py
Normal file → Executable file
@@ -2,17 +2,19 @@ from collections import defaultdict
|
||||
from random import choice, randrange
|
||||
|
||||
suivants = defaultdict(list)
|
||||
|
||||
with open("fra_wikipedia_2021_10K-sentences.txt", "r", encoding="utf-8") as fichier:
|
||||
for path in (
|
||||
"fra_wikipedia_2021_10K-sentences.txt",
|
||||
):
|
||||
with open(path, "r", encoding="utf-8") as fichier:
|
||||
for phrase in fichier:
|
||||
antepenultieme, penultieme = "", ""
|
||||
for word in phrase.split():
|
||||
suivants[(antepenultieme, penultieme)].append(word)
|
||||
antepenultieme, penultieme = penultieme, word
|
||||
|
||||
def parle():
|
||||
def parle(nb_phrases=1):
|
||||
phrases = []
|
||||
for _ in range(randrange(1, 4)):
|
||||
for _ in range(nb_phrases):
|
||||
antepenultieme, penultieme = "", ""
|
||||
phrase = []
|
||||
while mots_possibles := suivants[(antepenultieme, penultieme)]:
|
||||
|
||||
21
tchapbeta.py → tchap-beta.py
Normal file → Executable file
21
tchapbeta.py → tchap-beta.py
Normal file → Executable file
@@ -1,25 +1,17 @@
|
||||
import asyncio
|
||||
|
||||
from nio import MatrixRoom, Event, AsyncClient
|
||||
from nio import MatrixRoom, Event
|
||||
from nio.crypto import ENCRYPTION_ENABLED
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from matrix_bot.bot import MatrixBot
|
||||
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 tchap_bot.config import Config
|
||||
|
||||
from config import env_config
|
||||
from callbacks import properly_fail
|
||||
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
|
||||
# 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
|
||||
@@ -32,16 +24,18 @@ async def repond(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
|
||||
# il ne va pas répondre à ses propres messages
|
||||
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
|
||||
|
||||
reponse = parle()
|
||||
# il envoie l'information qu'il est en train d'écrire
|
||||
await matrix_client.room_typing(room.room_id)
|
||||
await asyncio.sleep(len(reponse) / 20)
|
||||
await asyncio.sleep(len(reponse) / 30)
|
||||
# il envoie le message
|
||||
await matrix_client.send_text_message(room.room_id, reponse, "m.notice")
|
||||
|
||||
|
||||
tchap_bot = MatrixBot(
|
||||
env_config.matrix_home_server,
|
||||
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.run()
|
||||
|
||||
16
tchap-beta.service
Executable file
16
tchap-beta.service
Executable 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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user