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
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
Now just run systemctl start your_service_name on your terminal
For log you can create new log file in your code.
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)
Example supervisor config(/etc/supervisor/conf.d/adflaunt.conf):
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