Skip to main content

Send a webhook when a repo event occurs

Me:

Is there a way to trigger another server to perform a task whenever content is pushed to main in this repo?

Copilot:

Yes, you can trigger another server to perform a task whenever content is pushed to the main branch in this repository by using a webhook. A webhook allows you to send HTTP POST requests to a specified URL when certain events occur in your GitHub repository.

Here’s how you can set up a webhook in your GitHub repository:

  1. Create a Webhook:
    • Go to your repository on GitHub.
    • Click on Settings.
    • In the left sidebar, click on Webhooks.
    • Click the Add webhook button.
    • In the Payload URL field, enter the URL of the server you want to notify.
    • Set the Content type to application/json.
    • In the Which events would you like to trigger this webhook? section, select Just the push event.
    • Click the Add webhook button.
  2. Handle the Webhook on Your Server:
    • On your server, set up an endpoint to receive the webhook payload.
    • The payload will contain information about the push event, including the repository, the branch, and the commits.

Here’s an example of how you might handle the webhook in a Python Flask application:

from flask import Flask, request, jsonify
 
app = Flask(__name__)
 
@app.route('/webhook', methods=['POST'])
 
def webhook():
    data = request.json
    if data['ref'] == 'refs/heads/main':
        # Perform your task here
        print("Push to main branch detected")
        # Example: Run a script or trigger another process
 
    return jsonify({'status': 'success'})
 
if __name__ == '__main__':
    app.run(port=5000)

In this example, the Flask application listens for POST requests at the /webhook endpoint. When a push event to the main branch is detected, it performs the specified task.

  1. Secure the Webhook:
    • To ensure that the webhook requests are coming from GitHub, you can set up a secret token.
    • In the webhook settings on GitHub, add a secret token.
    • In your server code, verify the token in the request headers.

Here’s an example of how to verify the secret token in the Flask application:

import hmac
import hashlib
 
from flask import Flask, request, jsonify, abort
 
app = Flask(__name__)
 
GITHUB_SECRET = 'your_secret_token'
 
def verify_signature(payload, signature):
    mac = hmac.new(GITHUB_SECRET.encode(), msg=payload, digestmod=hashlib.sha256)
    return hmac.compare_digest('sha256=' + mac.hexdigest(), signature)
 
@app.route('/webhook', methods=['POST'])
 
def webhook():
    signature = request.headers.get('X-Hub-Signature-256')
 
    if not verify_signature(request.data, signature):
        abort(403)
 
    data = request.json
 
    if data['ref'] == 'refs/heads/main':
        # Perform your task here
        print("Push to main branch detected")
        # Example: Run a script or trigger another process
 
    return jsonify({'status': 'success'})
 
if __name__ == '__main__':
    app.run(port=5000)

In this example, the verify_signature function checks the signature of the incoming request to ensure it matches the secret token. If the signature is invalid, the request is aborted with a 403 status code.

https://docs.github.com/en/webhooks