skip to Main Content

Im trying to set up a webhook with learnworlds

Here is my setup:
Ubuntu 23.04 x64 server from vultr.com
URL from namescheap that redirects to the server ip
Within the server, i have a python script called webhook_server.py and an empty CSV
-The csv is supposed to be filled as the python script colects calls from learnworld.

Here is the code for webhoobhook_server.py

import csv
from flask import Flask, request, abort
import json
import hashlib
import logging

app = Flask(__name__)

EXPECTED_SIGNATURE = "{expected signiture, cut this out}"

CSV_FILE_PATH = "userData.csv"  # Path to the CSV file

# Configure logging
logging.basicConfig(filename='app.log', level=logging.INFO)

@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.get_json()
    
    # Verify the webhook signature
    signature = hashlib.sha256(json.dumps(data).encode()).hexdigest()
    if signature != EXPECTED_SIGNATURE:
        abort(401)  # Return 401 Unauthorized status code if the signature does not match
    
    # Extract the webhook type
    webhook_type = data['type']
    
    if webhook_type == 'userUpdated':
        user_data = data['data']['user']
        user_id = user_data['id']
        
        # Search for matching ID in the CSV file
        csv_data = read_csv_file(CSV_FILE_PATH)
        matching_row = find_matching_row(csv_data, user_id)
        
        if matching_row:
            # Update existing line in CSV file
            updated_data = update_data(matching_row, user_data)
            write_csv_file(CSV_FILE_PATH, csv_data)
            logging.info(f"User data updated: {user_id}")
        else:
            # Append data to the end of the CSV file
            append_data_to_csv(CSV_FILE_PATH, user_data)
            logging.info(f"New user data appended: {user_id}")
    
    # Process or perform additional operations based on the webhook type
    
    # Return a response (optional)
    return 'Webhook received successfully'






def read_csv_file(file_path):
    """
    Read the contents of a CSV file and return the data as a list of dictionaries.
    """
    with open(file_path, 'r') as csv_file:
        reader = csv.DictReader(csv_file)
        data = list(reader)
    return data


def find_matching_row(data, user_id):
    """
    Find and return the row in the CSV data with a matching user ID.
    """
    for row in data:
        if row['id'] == user_id:
            return row
    return None


def update_data(row, new_data):
    """
    Update the existing row in the CSV data with the new data.
    """
    row.update(new_data)
    return row


def write_csv_file(file_path, data):
    """
    Write the data to a CSV file.
    """
    fieldnames = data[0].keys() if data else []
    with open(file_path, 'w', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)


def append_data_to_csv(file_path, new_data):
    """
    Append new data to the end of the CSV file.
    """
    with open(file_path, 'a', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=new_data.keys())
        writer.writerow(new_data)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

My problem:
I am able to runwebhook_server.py within the server but it doesnt change the CSV. in fact, i dont even know how to get to the python terminal so i could see any errors it throws up.
ChatGPT says my python code checks out (as far as i trust that:/) but the code doesnt seem to do anything.

Another issue, when i run the program, it doesnt let me do anything else. it gives me the option to "Press CTR:+C to quit" but i cant even look into the CSV without killing the flask server.

How do i get this running?

2

Answers


  1. First you have create services for your program in etc/systemd/system/your_service_name.service

    Then write script for your code in your_service_name.service

    The code would like bellows

    [Unit]
    Description=test demo service
    After=network.target
    StartLimitIntervalSec=0
    [Service]
    Type=simple
    Restart=always
    RestartSec=1
    User=centos
    ExecStart=/usr/local/bin/ python /path/to/your_code.py
    
    [Install]
    WantedBy=multi-user.target
    

    Now just run systemctl start your_service_name on your terminal

    For log you can create new log file in your code.

    Login or Signup to reply.
  2. you can run your flask application for development using a virtual environment and gunicorn with nginx port forwarding. I’ll put an example with supervisorctl.

    example NGINX configuriation(/etc/nginx/sites-enabled/{your app} – don’t forget to delete default first)

    server {
        server_name example.com;
    
        client_max_body_size 20M;
    
        location / {
            proxy_pass http://localhost:8000;
            include /etc/nginx/proxy_params;
            proxy_redirect off;
        }
        location /socket.io {
            include proxy_params;
            proxy_http_version 1.1;
            proxy_buffering off;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass http://127.0.0.1:8000/socket.io;
        }
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/adflaunt.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/adflaunt.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    
    }
    server {
        if ($host = adflaunt.com) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
    
        listen 80;
    
        server_name adflaunt.com;
        return 404; # managed by Certbot
    
    
    }
    

    Example supervisor config(/etc/supervisor/conf.d/adflaunt.conf):

    [program:yourprogram]
    command= /home/yourusername/yourfolder/env/bin/gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 app:app
    directory=/home/yourusername/yourfolder
    autostart=true
    autorestart=true
    killasgroup=true
    stopasgroup=true
    stdout_logfile=/home/yourusername/out.log
    stderr_logfile=/home/yourusername/err.log
    

    Note: this configuration is allowing you to use socket.io if you need.
    Note:you need to create a virtual environment.

    You can find a simple youtube tutorial here:https://yewtu.be/watch?v=LUFn-QVcmB8

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search