Compare commits
2 Commits
main
...
caf04ec659
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caf04ec659 | ||
|
|
a2c0fece12 |
@@ -1,9 +1,8 @@
|
|||||||
## Matrix env variables
|
## Matrix env variables
|
||||||
|
|
||||||
VERBOSE=True
|
VERBOSE=True
|
||||||
SYSTEMD_LOGGING=False
|
SYSTEMD_LOGGING=False
|
||||||
matrix_home_server="https://matrix.agent.ministere_example.tchap.gouv.fr"
|
matrix_home_server="https://matrix.agent.ministere_example.tchap.gouv.fr"
|
||||||
matrix_bot_username="jean.quidam@ministere_example.gouv.fr"
|
matrix_bot_username="jean.quidam@ministere_example.gouv.fr"
|
||||||
matrix_bot_password="test"
|
matrix_bot_password="test"
|
||||||
join_on_invite=True
|
#https_proxy=http://adresse.du.proxy:port/
|
||||||
#https_proxy=http://adresse.du.proxy:port/
|
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -1,6 +0,0 @@
|
|||||||
.env
|
|
||||||
.venv/
|
|
||||||
session.txt
|
|
||||||
store/
|
|
||||||
__pycache__
|
|
||||||
corpus/
|
|
||||||
24
README.md
Executable file → Normal file
24
README.md
Executable file → Normal file
@@ -1,6 +1,6 @@
|
|||||||
# Tchap Beta
|
# Tchap Beta
|
||||||
|
|
||||||
Agent conversationnel à petit modèle de langage de bêtise artificielle pour la messagerie Tchap.
|
Agent conversationnel à petit modèle de langage de bêtise artificelle 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
|
||||||
@@ -20,27 +20,11 @@ pip install \
|
|||||||
tchap-bot --index-url https://code.peren.fr/api/v4/projects/83/packages/pypi/simple
|
tchap-bot --index-url https://code.peren.fr/api/v4/projects/83/packages/pypi/simple
|
||||||
|
|
||||||
# Renseignez les informations de connexion :
|
# Renseignez les informations de connexion :
|
||||||
$EDITOR .env
|
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 tchap-beta.py
|
python tchapbeta.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.)
|
|
||||||
|
|
||||||
|
|||||||
30
callbacks.py
30
callbacks.py
@@ -1,30 +0,0 @@
|
|||||||
from functools import wraps
|
|
||||||
|
|
||||||
from nio import MatrixRoom, Event
|
|
||||||
|
|
||||||
from matrix_bot.config import logger
|
|
||||||
from matrix_bot.client import MatrixClient
|
|
||||||
|
|
||||||
|
|
||||||
def properly_fail(error_message="failed to answer", style="m.notice"):
|
|
||||||
def custom_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, error_message, style)
|
|
||||||
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
|
|
||||||
return custom_properly_fail
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
from pydantic import Field
|
|
||||||
|
|
||||||
from tchap_bot.config import Config
|
|
||||||
|
|
||||||
|
|
||||||
class ConfigProxy(Config):
|
|
||||||
https_proxy: str = Field("", description="Proxy URL")
|
|
||||||
|
|
||||||
env_config = ConfigProxy()
|
|
||||||
26
markov.py
Executable file → Normal file
26
markov.py
Executable file → Normal file
@@ -1,20 +1,18 @@
|
|||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from pathlib import Path
|
from random import choice, randrange
|
||||||
from random import choice
|
|
||||||
|
|
||||||
|
|
||||||
suivants = defaultdict(list)
|
suivants = defaultdict(list)
|
||||||
for chemin in Path("corpus").iterdir():
|
|
||||||
with open(chemin, "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(nb_phrases=1):
|
with open("fra_wikipedia_2021_10K-sentences.txt", "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():
|
||||||
phrases = []
|
phrases = []
|
||||||
for _ in range(nb_phrases):
|
for _ in range(randrange(1, 4)):
|
||||||
antepenultieme, penultieme = "", ""
|
antepenultieme, penultieme = "", ""
|
||||||
phrase = []
|
phrase = []
|
||||||
while mots_possibles := suivants[(antepenultieme, penultieme)]:
|
while mots_possibles := suivants[(antepenultieme, penultieme)]:
|
||||||
@@ -23,7 +21,3 @@ def parle(nb_phrases=1):
|
|||||||
antepenultieme, penultieme = penultieme, mot_suivants
|
antepenultieme, penultieme = penultieme, mot_suivants
|
||||||
phrases.append(" ".join(phrase))
|
phrases.append(" ".join(phrase))
|
||||||
return "\n".join(phrases)
|
return "\n".join(phrases)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
print(parle())
|
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
|
|
||||||
from nio import MatrixRoom, Event
|
|
||||||
|
|
||||||
from matrix_bot.bot import MatrixBot
|
|
||||||
from matrix_bot.client import MatrixClient
|
|
||||||
from matrix_bot.eventparser import MessageEventParser, ignore_when_not_concerned, EventNotConcerned
|
|
||||||
|
|
||||||
from config import env_config
|
|
||||||
from callbacks import properly_fail
|
|
||||||
from markov import parle
|
|
||||||
|
|
||||||
|
|
||||||
async def non_lus(room_id):
|
|
||||||
room = tchap_bot.matrix_client.rooms[room_id]
|
|
||||||
if room.unread_notifications:
|
|
||||||
response = await tchap_bot.matrix_client.room_messages(room_id=room_id, limit=room.unread_notifications, direction="back", start="")
|
|
||||||
for message in response.chunk:
|
|
||||||
await repond(room, message, tchap_bot.matrix_client)
|
|
||||||
|
|
||||||
|
|
||||||
# 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
|
|
||||||
# permet de laisser event_parser gérer le cas où la commande n'est pas concernée
|
|
||||||
@properly_fail("Oups, j'ai buggué 😿")
|
|
||||||
@ignore_when_not_concerned
|
|
||||||
async def repond(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
|
|
||||||
# on initialise un event_parser pour décider à quel message cette commande va répondre
|
|
||||||
event_parser = MessageEventParser(room=room, event=message, matrix_client=matrix_client)
|
|
||||||
# il ne va pas répondre à ses propres messages
|
|
||||||
event_parser.do_not_accept_own_message()
|
|
||||||
|
|
||||||
|
|
||||||
if not hasattr(message, "body") or not hasattr(message, "formatted_body"):
|
|
||||||
# message non textuel
|
|
||||||
raise EventNotConcerned
|
|
||||||
|
|
||||||
# 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
|
|
||||||
|
|
||||||
# il envoie l'information qu'il est en train d'écrire
|
|
||||||
await matrix_client.room_typing(room.room_id)
|
|
||||||
reponse = parle()
|
|
||||||
await asyncio.sleep(len(reponse) / 50)
|
|
||||||
# il envoie le message
|
|
||||||
await matrix_client.room_typing(room.room_id, typing_state=False)
|
|
||||||
await matrix_client.send_html_message(room.room_id, reponse)
|
|
||||||
|
|
||||||
|
|
||||||
@properly_fail("Oups, j'ai buggué 😿")
|
|
||||||
@ignore_when_not_concerned
|
|
||||||
async def dune(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
|
|
||||||
event_parser = MessageEventParser(room=room, event=message, matrix_client=matrix_client)
|
|
||||||
event_parser.do_not_accept_own_message()
|
|
||||||
|
|
||||||
if ("Adrien" in message.body or "adrien" in message.body):
|
|
||||||
await matrix_client.room_typing(room.room_id)
|
|
||||||
await matrix_client.send_html_message(room.room_id, "<em>Lisan al-Gaib !</em>", "m.notice")
|
|
||||||
|
|
||||||
|
|
||||||
tchap_bot = MatrixBot(
|
|
||||||
env_config.matrix_home_server,
|
|
||||||
env_config.matrix_bot_username,
|
|
||||||
env_config.matrix_bot_password,
|
|
||||||
proxy=env_config.https_proxy,
|
|
||||||
use_functions=True,
|
|
||||||
ssl=True
|
|
||||||
)
|
|
||||||
|
|
||||||
tchap_bot.callbacks.register_on_startup(non_lus)
|
|
||||||
tchap_bot.callbacks.register_on_message_event(dune)
|
|
||||||
tchap_bot.callbacks.register_on_message_event(repond)
|
|
||||||
tchap_bot.run()
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# /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
|
|
||||||
59
tchapbeta.py
Normal file
59
tchapbeta.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import asyncio
|
||||||
|
|
||||||
|
from nio import MatrixRoom, Event, AsyncClient
|
||||||
|
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 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
|
||||||
|
# permet de laisser event_parser gérer le cas où la commande n'est pas concernée
|
||||||
|
@properly_fail
|
||||||
|
@ignore_when_not_concerned
|
||||||
|
async def repond(room: MatrixRoom, message: Event, matrix_client: MatrixClient):
|
||||||
|
# on initialise un event_parser pour décider à quel message cette commande va répondre
|
||||||
|
event_parser = MessageEventParser(room=room, event=message, matrix_client=matrix_client)
|
||||||
|
# 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):
|
||||||
|
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)
|
||||||
|
# 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,
|
||||||
|
env_config.matrix_bot_password,
|
||||||
|
proxy=env_config.https_proxy,
|
||||||
|
use_functions=True,
|
||||||
|
ssl=True
|
||||||
|
)
|
||||||
|
|
||||||
|
tchap_bot.matrix_client.matrix_config.encryption_enabled = True
|
||||||
|
tchap_bot.matrix_client.matrix_config.ignore_unverified_devices = True
|
||||||
|
tchap_bot.matrix_client.matrix_config.join_on_invite = True
|
||||||
|
|
||||||
|
tchap_bot.callbacks.register_on_message_event(repond)
|
||||||
|
tchap_bot.run()
|
||||||
14
tchapbeta.servicee
Normal file
14
tchapbeta.servicee
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# /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