Compare commits

...

21 Commits

Author SHA1 Message Date
Adrien.Malingrey
09e1e0724a .env exemple 2026-02-06 15:31:53 +01:00
Adrien.Malingrey
d3ab0e2844 message d'erreur personnalisable 2026-02-06 15:21:00 +01:00
Adrien.Malingrey
50248feea7 html 2026-02-06 11:12:46 +01:00
2f063f7a52 ignorer les ajouts dans corpus 2026-02-05 20:16:26 +01:00
8f9987fcd2 importer tout le dossier corpus 2026-02-05 20:15:56 +01:00
3c18739db0 test 2026-02-05 17:08:21 +01:00
ff30f59787 plusieurs sources, plusieurs phrases 2026-02-05 16:02:30 +01:00
root
16cd631d64 correction imports 2026-02-04 18:39:27 +01:00
root
b209964631 refactor 2026-02-04 18:35:38 +01:00
MALINGREY Adrien
3ed553b854 personnalisation du gestionnaire d'erreur 2026-02-04 16:57:27 +00:00
MALINGREY Adrien
d1f3f8207b répond en message direct ou dans les salons publics en cas d'interpellation 2026-02-04 16:33:57 +00:00
MALINGREY Adrien
95c611ad36 renommage 2026-02-04 16:01:45 +00:00
MALINGREY Adrien
162252b2de Ajout EnvironmentFile 2026-02-04 16:01:18 +00:00
MALINGREY Adrien
46347a2ea5 ajout chown 2026-02-04 15:56:50 +00:00
MALINGREY Adrien
1dc16b9447 Ajout de commentaires 2026-02-04 14:52:42 +00:00
MALINGREY Adrien
dab6faf9d0 renommage des fichiers en tchap-beta 2026-02-04 14:34:17 +00:00
MALINGREY Adrien
29b185b1c5 Installation en tant que service 2026-02-04 14:30:26 +00:00
MALINGREY Adrien
e883545e61 Add .gitignore 2026-02-04 14:13:23 +00:00
MALINGREY Adrien
a3e92ac244 Edit README.md 2026-02-04 14:06:01 +00:00
MALINGREY Adrien
7f688dc8aa Edit README.md 2026-02-04 12:49:19 +00:00
MALINGREY Adrien
129fb4eafb premier commit 2026-02-04 12:42:17 +00:00
9 changed files with 9022 additions and 78 deletions

8
.env.exemple Normal file
View File

@@ -0,0 +1,8 @@
## 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/

6
.gitignore vendored Executable file
View File

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

109
README.md Normal file → Executable file
View File

@@ -1,93 +1,46 @@
# Tchap Beta
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).
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab-forge.din.developpement-durable.gouv.fr/drieat-if/dsin/usrt/tchap-beta.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab-forge.din.developpement-durable.gouv.fr/drieat-if/dsin/usrt/tchap-beta/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
Voir la [documentation technique - Bot et Integrations Tchap](https://aide.tchap.numerique.gouv.fr/fr/article/documentation-technique-bot-et-integrations-tchap-1z3dfx/) pour la création du compte.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
```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
source .venv/bin/activate
pip install \
"Pillow>=10.4.0,<11.0.0" \
"aiohttp<3.10" \
"matrix-nio[e2e]>=0.24.0,<0.25.0" \
tchap-bot --index-url https://code.peren.fr/api/v4/projects/83/packages/pypi/simple
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
# Renseignez les informations de connexion :
editor .env
python -c 'import secrets; print("salt=", secrets.token_bytes(16), sep="")' >> .env
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
# Lancer
python tchap-beta.py
```
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
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).
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
## Installer en tant que service
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
En plus des commandes précédentes :
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
```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
````
## License
For open source projects, say how it is licensed.
(L'emplacement et le nom d'utilisateur sont libres tant que c'est cohérent avec le service.)
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

30
callbacks.py Executable file
View File

@@ -0,0 +1,30 @@
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

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()

File diff suppressed because it is too large Load Diff

29
markov.py Executable file
View File

@@ -0,0 +1,29 @@
from collections import defaultdict
from pathlib import Path
from random import choice
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):
phrases = []
for _ in range(nb_phrases):
antepenultieme, penultieme = "", ""
phrase = []
while mots_possibles := suivants[(antepenultieme, penultieme)]:
mot_suivants = choice(mots_possibles)
phrase.append(mot_suivants)
antepenultieme, penultieme = penultieme, mot_suivants
phrases.append(" ".join(phrase))
return "\n".join(phrases)
if __name__ == "__main__":
print(parle())

55
tchap-beta.py Executable file
View File

@@ -0,0 +1,55 @@
import asyncio
from nio import MatrixRoom, Event
from nio.crypto import ENCRYPTION_ENABLED
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
# 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()
# 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) / 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, "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()

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