Compare commits
1 Commits
master
...
post-on-ir
Author | SHA1 | Date |
---|---|---|
Darks | 6ea0a661cf |
|
@ -1,2 +1,2 @@
|
|||
__pycache__/
|
||||
gb_secrets.py
|
||||
secrets.py
|
||||
|
|
29
README.md
29
README.md
|
@ -1,12 +1,11 @@
|
|||
## GLaDOS bot
|
||||
|
||||
Ce bot recoit des requêtes Gitea, les parse et poste des messages en tant que `Gitea` sur la shoutbox.
|
||||
|
||||
Ce bot recoit des requêtes Gitea, les parse et poste des messages en tant que GLaDOS sur la shoutbox.
|
||||
|
||||
## Configuration du backend
|
||||
|
||||
1. Cloner le dépot dans `/home/pc/gitea-bot/`
|
||||
2. Copier les identifiants de `Gitea` dans `gb_secrets.py` (`credentials = {"username":"Gitea", "password":"P@ssw0rd"}`)
|
||||
2. Copier le cookie de session de GLaDOS dans `secrets.py`
|
||||
3. Placer `gitea-bot.service` dans `/etc/systemd/system/`
|
||||
4. Démarrer le service `gitea-bot`
|
||||
|
||||
|
@ -14,14 +13,13 @@ Ce bot recoit des requêtes Gitea, les parse et poste des messages en tant que `
|
|||
# su pc
|
||||
$ cd ~
|
||||
$ git clone gitea@gitea.planet-casio.com:devs/Gitea-bot.git gitea-bot
|
||||
$ vim gitea-bot/gb_secrets.py
|
||||
$ vim gitea-bot/secrets.py
|
||||
$ exit
|
||||
# cp /home/pc/gitea-bot/gitea-bot.service /etc/systemd/system/
|
||||
# systemctl enable --now gitea-bot
|
||||
```
|
||||
|
||||
En soit le cookie peut être celui de n'importe quel membre ayant le droit de causer sur la shout. Par contre ça ne sera plus `Gitea` qui causera.
|
||||
|
||||
En soit le cookie peut être celui de n'importe quel membre ayant le droit de causer sur la shout. Par contre ça ne sera plus GLaDOS qui causera.
|
||||
|
||||
## Configuration de Gitea
|
||||
|
||||
|
@ -42,7 +40,6 @@ Sélectionner des éléments qui déclencheront des évènements, vérifier que
|
|||
|
||||
Les derniers évènements sont affichés sous le formulaire.
|
||||
|
||||
|
||||
## Traiter de nouveaux évènements
|
||||
|
||||
La documentation sur les events est disponible [ici](https://docs.gitea.io/en-us/webhooks/).
|
||||
|
@ -51,7 +48,6 @@ Gitea logge les événements récents dans les paramètres du webhook dans le pa
|
|||
|
||||
Le script actuel est pas fou, n'hésitez pas à proposer des améliorations ! :)
|
||||
|
||||
|
||||
## Tester les modifications en local
|
||||
|
||||
Lancer le serveur de test avec `flask run` ; les requêtes enregistrées par Gitea peuvent être envoyées avec curl.
|
||||
|
@ -60,18 +56,6 @@ Lancer le serveur de test avec `flask run` ; les requêtes enregistrées par Git
|
|||
curl http://127.0.0.1:5000 -X POST -H 'X-Gitea-Event:push' -H 'Content-Type: application/json' -d "$(cat logged-push-event.json)"
|
||||
```
|
||||
|
||||
|
||||
## Modifier la verbosité des logs
|
||||
|
||||
Vous pouvez changer le niveau de verbosité des logs via la variable d’environement `LOGLEVEL` :
|
||||
|
||||
- `critical`
|
||||
- `error`
|
||||
- `warning`
|
||||
- `info` (défaut)
|
||||
- `debug`
|
||||
|
||||
|
||||
## Appliquer des modifications
|
||||
|
||||
```
|
||||
|
@ -81,8 +65,3 @@ $ git pull
|
|||
$ exit
|
||||
# systemctl restart gitea-bot
|
||||
```
|
||||
|
||||
|
||||
## En cas de soucis
|
||||
|
||||
Si le bot ne fonctionne plus sans modification apparente, vous pouvez essayer de redémarrer le service. Cela réinitialisera la session et ses cookies d’authentification.
|
||||
|
|
85
app.py
85
app.py
|
@ -1,15 +1,8 @@
|
|||
from flask import Flask, request
|
||||
from gb_secrets import credentials
|
||||
import logging, requests, os
|
||||
import re
|
||||
|
||||
LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()
|
||||
logging.basicConfig(level=LOGLEVEL)
|
||||
from secrets import cookie
|
||||
import requests as r
|
||||
|
||||
app = Flask(__name__)
|
||||
session = requests.Session()
|
||||
session.post("https://www.planet-casio.com/Fr/compte",
|
||||
data=credentials)
|
||||
|
||||
def make_url_user(user):
|
||||
return f"[url=https://gitea.planet-casio.com/{user['username']}]{user['username']}[/url]"
|
||||
|
@ -19,58 +12,39 @@ def make_url_repository(repository):
|
|||
|
||||
@app.route("/", methods=["GET", "POST"])
|
||||
def main():
|
||||
global session
|
||||
data = request.json
|
||||
event = request.headers['X-Gitea-Event']
|
||||
msg = None
|
||||
|
||||
if data["repository"]["private"] or data["repository"]["mirror"]:
|
||||
if data["repository"]["private"]:
|
||||
return "IGN"
|
||||
|
||||
url_repository = make_url_repository(data["repository"])
|
||||
|
||||
if event == "push" and data["commits"] != []:
|
||||
# Heuristic to handle pull request merges by detecting default merge message
|
||||
RE_MERGE = r"^Merge pull request '(.+)' \(#([0-9]+)\)"#from .* into"
|
||||
m = re.match(RE_MERGE, data["commits"][0]["message"])
|
||||
if len(data["commits"]) > 1 and m:
|
||||
pr_url = data["repository"]["html_url"] + "/pulls/" + m[2]
|
||||
pr_url = f"[url={pr_url}]{m[1]}[/url]"
|
||||
data["commits"] = data["commits"][1:]
|
||||
else:
|
||||
pr_url = None
|
||||
|
||||
commits = data["commits"]
|
||||
total_commits = data.get("total_commits", len(commits))
|
||||
commit_count = f"{total_commits} commit{'s' if total_commits > 1 else ''}"
|
||||
commit_count = f"{len(commits)} commit{'s' if len(commits) > 1 else ''}"
|
||||
message = "[inlinecode]" + commits[0]["message"].split('\n',1)[0] + "[/inlinecode]"
|
||||
|
||||
if total_commits <= 1:
|
||||
if len(commits) <= 1:
|
||||
others = ""
|
||||
elif total_commits == 2:
|
||||
elif len(commits) == 2:
|
||||
others = " (et 1 autre commit)"
|
||||
else:
|
||||
others = f" (et {total_commits-1} autres commits)"
|
||||
others = f" (et {len(commits)-1} autres commits)"
|
||||
|
||||
url_user = make_url_user(data['pusher'])
|
||||
|
||||
# Pull request merge
|
||||
if pr_url:
|
||||
msg = f"{url_user} a fusionné la PR {pr_url}: {message}{others}"
|
||||
# Ref doesn't have a previous commit = new branch
|
||||
elif all(c == "0" for c in data["before"]) and data["ref"].startswith("refs/heads/"):
|
||||
if all(c == "0" for c in data["before"]) and data["ref"].startswith("refs/heads/"):
|
||||
branch = data["ref"][11:]
|
||||
url_branch = data["repository"]["html_url"] + f"/src/branch/{branch}"
|
||||
url_branch = f"[url={url_branch}]{branch}[/url]"
|
||||
msg = f"{url_user} a créé une nouvelle branche {url_branch} dans {url_repository} : {message}{others}"
|
||||
# Pre-existing branch
|
||||
else:
|
||||
if data["ref"].startswith("refs/heads/"):
|
||||
branch = " (branche " + data["ref"][11:] + ")"
|
||||
else:
|
||||
branch = ""
|
||||
url_commits = f"[url={data['compare_url']}]{commit_count}[/url]"
|
||||
msg = f"{url_user} a poussé {url_commits} dans {url_repository}{branch} : {message}{others}"
|
||||
msg = f"{url_user} a poussé {url_commits} dans {url_repository} : {message}{others}"
|
||||
|
||||
if event == "push" and data["ref"].startswith("refs/tags/"):
|
||||
url_user = make_url_user(data['pusher'])
|
||||
|
@ -94,7 +68,7 @@ def main():
|
|||
elif data['action'] == "edited":
|
||||
msg = f"{url_user} a édité le ticket {url_issue} dans {url_repository}"
|
||||
else:
|
||||
return "IGN"
|
||||
msg = f"{url_user} a <{data['action']}> le ticket {url_issue} dans {url_repository}"
|
||||
|
||||
if event == "issue_comment":
|
||||
url_user = make_url_user(data['sender'])
|
||||
|
@ -102,8 +76,6 @@ def main():
|
|||
|
||||
if data['action'] == "created":
|
||||
msg = f"{url_user} a répondu au ticket {url_issue} dans {url_repository}"
|
||||
else:
|
||||
return "IGN"
|
||||
|
||||
if event == "pull_request" and data["action"] == "opened":
|
||||
url_user = make_url_user(data["sender"])
|
||||
|
@ -115,37 +87,21 @@ def main():
|
|||
url_user = make_url_user(data['sender'])
|
||||
msg = f"{url_user} a créé un nouveau dépôt {url_repository}"
|
||||
|
||||
if event == "repository" and data["action"] == "deleted":
|
||||
return "IGN"
|
||||
|
||||
if event == "push" and all(c == '0' for c in data["after"]):
|
||||
return "IGN"
|
||||
|
||||
if event == "push" and not data["ref"].startswith("refs/tags/") \
|
||||
and all(c == '0' for c in data["before"]) and data["commits"] == []:
|
||||
if event == "pull_request" and data["action"] in ["assigned", "closed", "synchronized"]:
|
||||
return "IGN"
|
||||
|
||||
if event == "pull_request" and data["action"] in ["assigned", "closed", "synchronized", "edited"]:
|
||||
return "IGN"
|
||||
|
||||
if event == "pull_request_approved" and data["action"] == "reviewed":
|
||||
url_user = make_url_user(data['sender'])
|
||||
url_pr = f"[url={data['pull_request']['url']}]{data['pull_request']['title']}[/url]"
|
||||
|
||||
msg = f"{url_user} a approuvé la PR {url_pr} dans {url_repository}"
|
||||
|
||||
if event == "pull_request_rejected" and data["action"] == "reviewed":
|
||||
url_user = make_url_user(data['sender'])
|
||||
url_pr = f"[url={data['pull_request']['url']}]{data['pull_request']['title']}[/url]"
|
||||
|
||||
msg = f"{url_user} a demandé des modifications sur la PR {url_pr} dans {url_repository}"
|
||||
|
||||
if event == "fork":
|
||||
return "IGN"
|
||||
|
||||
if event == "create" and data["ref_type"] in ["tag", "branch"]:
|
||||
return "IGN"
|
||||
|
||||
if event == "issue_comment":
|
||||
return "IGN"
|
||||
|
||||
if event == "delete":
|
||||
return "IGN"
|
||||
|
||||
|
@ -160,14 +116,9 @@ def main():
|
|||
|
||||
if msg:
|
||||
msg = f"[gray][i]{msg}[/i][/gray]"
|
||||
app.logger.info(msg)
|
||||
r = session.post("https://www.planet-casio.com/Fr/shoutbox/api/post",
|
||||
data={"message": msg, "channel": "projets"})
|
||||
|
||||
if r.status_code == 200:
|
||||
return "OK"
|
||||
else:
|
||||
app.logger.warn(f"Error: {r.status_code}")
|
||||
return f"ERR {r.status_code}"
|
||||
app.logger.warn(msg)
|
||||
r.post("https://www.planet-casio.com/Fr/shoutbox/api/post",
|
||||
data={"message": msg, "channel": "dev"}, cookies=cookie)
|
||||
return "OK"
|
||||
|
||||
return "ACK"
|
||||
|
|
|
@ -5,7 +5,6 @@ After=network.target
|
|||
[Service]
|
||||
User=pc
|
||||
WorkingDirectory=/home/pc/gitea-bot/
|
||||
Environment="LOGLEVEL=info"
|
||||
ExecStart=flask run
|
||||
Restart=always
|
||||
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
import socket
|
||||
from config import V5Config
|
||||
|
||||
BOLD = "\x02"
|
||||
ITALIC = "\x1d"
|
||||
UNDERLINE = "\x1f"
|
||||
STRIKETHROUGH = "\x1e"
|
||||
|
||||
NO_COLOR = "\x03"
|
||||
WHITE = "\x0300"
|
||||
BLACK = "\x0301"
|
||||
BLUE = "\x0302"
|
||||
GREEN = "\x0303"
|
||||
RED = "\x0304"
|
||||
BROWN = "\x0305"
|
||||
MAGENTA = "\x0306"
|
||||
ORANGE = "\x0307"
|
||||
YELLOW = "\x0308"
|
||||
LIGHT_GREEN = "\x0309"
|
||||
CYAN = "\x0310"
|
||||
LIGHT_CYAN = "\x0311"
|
||||
LIGHT_BLUE = "\x0312"
|
||||
PINK = "\x0313"
|
||||
GREY = "\x0314"
|
||||
LIGHT_GREY = "\x0315"
|
||||
|
||||
GLADOS_HOST = "127.0.0.1"
|
||||
GLADOS_PORT = 5555
|
||||
|
||||
def say(msg, channels = ["#general"]):
|
||||
""" GLaDOS will say <msg> on <channels>
|
||||
Channel #* means all channels where GLaDOS listens to
|
||||
Raw messages follow this partern:
|
||||
#channel1 #channel2: message"""
|
||||
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
|
||||
msg = ":".join([" ".join(channels), msg])
|
||||
sock.sendto(msg.encode(),(GLADOS_HOST, GLADOS_PORT))
|
|
@ -1,3 +1,2 @@
|
|||
# A cookie for GLaDOS
|
||||
cookie = {"planete_casio_session":"SomeSessionCookieFromGlados"}
|
||||
credentials = None
|
Loading…
Reference in New Issue