Last active
April 25, 2024 06:37
-
-
Save juffaz/3e7ae3c896d707291698d72735a42f96 to your computer and use it in GitHub Desktop.
python-gitlab-webhook-telegram-alarm-changes-count.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[root@docker01test gitlab-webhook]# ls | |
app.py Dockerfile req.txt | |
[root@docker01test gitlab-webhook]# cat app.py | |
import os | |
from flask import Flask, request, jsonify | |
import json | |
import requests | |
app = Flask(__name__) | |
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN') | |
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID') | |
MAX_CHANGES = int(os.getenv('MAX_CHANGES', 500)) | |
def send_telegram_message(message): | |
url = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage' | |
payload = { | |
'chat_id': TELEGRAM_CHAT_ID, | |
'text': message, | |
'parse_mode': 'HTML' | |
} | |
response = requests.post(url, json=payload) | |
return response.json() | |
@app.route('/gitlab/webhook', methods=['POST']) | |
def handle_webhook(): | |
data = json.loads(request.data) | |
if data['object_kind'] == 'merge_request': | |
changes_count = len(data['changes']) | |
if changes_count > MAX_CHANGES: | |
message = f"⚠️ Alert: Merge Request with {changes_count} changes exceeds the maximum allowed." | |
send_telegram_message(message) | |
return jsonify({'status': 'success', 'message': 'Excessive changes, notification sent'}), 200 | |
else: | |
return jsonify({'status': 'success', 'message': 'Changes within limit'}), 200 | |
else: | |
return jsonify({'status': 'ignored', 'message': 'Not a merge request event'}), 200 | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=5000) | |
[root@docker01test gitlab-webhook]# cat Dockerfile | |
FROM python:3.9-slim | |
WORKDIR /app | |
COPY req.txt . | |
RUN pip install --no-cache-dir -r req.txt | |
COPY . . | |
ENV TELEGRAM_TOKEN='TOKEN' | |
ENV TELEGRAM_CHAT_ID='CHAT_ID' | |
ENV MAX_CHANGES=500 | |
EXPOSE 5000 | |
CMD ["python", "app.py"] | |
[root@docker01test gitlab-webhook]# cat req.txt | |
Flask==2.0.3 | |
Werkzeug==2.0.1 | |
requests==2.26.0 | |
[root@docker01test gitlab-webhook]# docker build -t gitlab-webhook-app . | |
[root@docker01test gitlab-webhook]# docker rm -f my-webhook-app | |
[root@docker01test gitlab-webhook]# docker run -d -p 5066:5000 --name my-webhook-app gitlab-webhook-app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment