Compare commits
12 Commits
main
...
3712c4ddbd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3712c4ddbd | ||
|
|
dccbaa332a | ||
|
|
75b0fb91b3 | ||
|
|
dc9106b8fd | ||
|
|
df7bd7415c | ||
|
|
835b415bc6 | ||
|
|
1be9fd8a1c | ||
|
|
361f22e014 | ||
|
|
76d0627aa9 | ||
|
|
f7bd4393f2 | ||
|
|
caf04ec659 | ||
|
|
a2c0fece12 |
8
.env
Normal file
8
.env
Normal 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/
|
||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
.env
|
||||
.venv/
|
||||
session.txt
|
||||
store/
|
||||
110
README.md
110
README.md
@@ -1,93 +1,45 @@
|
||||
# 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.
|
||||
|
||||
## 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.
|
||||
(L'emplacement et le nom d'utilisateur sont libres tant que c'est cohérent avec le service.)
|
||||
8838
fra_wikipedia_2021_10K-sentences.txt
Normal file
8838
fra_wikipedia_2021_10K-sentences.txt
Normal file
File diff suppressed because it is too large
Load Diff
23
markov.py
Normal file
23
markov.py
Normal file
@@ -0,0 +1,23 @@
|
||||
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 phrase in fichier:
|
||||
antepenultieme, penultieme = "", ""
|
||||
for word in phrase.split():
|
||||
suivants[(antepenultieme, penultieme)].append(word)
|
||||
antepenultieme, penultieme = penultieme, word
|
||||
|
||||
def parle():
|
||||
phrases = []
|
||||
for _ in range(randrange(1, 4)):
|
||||
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)
|
||||
85
tchap-beta.py
Normal file
85
tchap-beta.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import asyncio
|
||||
from functools import wraps
|
||||
|
||||
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.eventparser import MessageEventParser, ignore_when_not_concerned, EventNotConcerned
|
||||
from matrix_bot.config import logger
|
||||
from tchap_bot.config import Config
|
||||
|
||||
|
||||
from markov import parle
|
||||
|
||||
|
||||
class ConfigProxy(Config):
|
||||
https_proxy: str = Field("", description="Proxy URL")
|
||||
|
||||
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
|
||||
# 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()
|
||||
|
||||
# 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) / 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,
|
||||
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
Normal file
16
tchap-beta.service
Normal 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
|
||||
Reference in New Issue
Block a user