Karol
Karol

Reputation: 1

Workspace as a Task Webhook - pretty common

im looking for solution for My Asana-Langchain app. Im trying to place a hook for all task in whole workspace, there is anyway to go over it? Whats the best solution for it ? Im considering how im supposed to invent my app. I have a conclusion at the moment, should i ADD dynamic hooks make when app creates new project make them static, and projects as well... or perhaps i can place 1 hook for whole workspace, i found some old talk on forum about it , but that was few years ago. I cannot find anything in asana docs, how to go over it.

import os
import asana
from asana.rest import ApiException
from dotenv import load_dotenv
from pprint import pprint

# Load environment variables (for stored PAT and X-Hook-Secret)
load_dotenv()

# Configure Asana client
configuration = asana.Configuration()
configuration.access_token = os.getenv('PAT')
api_client = asana.ApiClient(configuration)

# Create an instance of the Webhooks API
webhooks_api_instance = asana.WebhooksApi(api_client)

# Helper function to read X-Hook-Secret from the .env file
def get_x_hook_secret():
    with open('.env', 'r') as file:
        for line in file:
            if line.startswith('X_HOOK_SECRET='):
                return line.split('=')[1].strip()
    return ""

# Function to delete the webhook
# Documentation: https://github.com/Asana/python-asana/blob/v5.0.11/docs/WebhooksApi.md#delete_webhook
def delete_webhook(webhook_gid):
    try:
        webhooks_api_instance.delete_webhook(webhook_gid)
        print(f'Webhook {webhook_gid} deleted due to mismatch.')
    except ApiException as e:
        print(f"Exception when calling WebhooksApi->delete_webhook: {e}\n")

# Function to create the webhook
# Documentation: https://github.com/Asana/python-asana/blob/v5.0.11/docs/WebhooksApi.md#create_webhook
def create_webhook(target_uri, object_id, filter, resource_type):
    body = {
        "data": {
            "resource": object_id,
            "target": target_uri,
            "filters": [{"action": filter, "resource_type": resource_type}],
        }
    }

    # Documentation: https://developers.asana.com/docs/inputoutput-options
    opts = {}

    try:
        # Establish a webhook
        # Note: This request disables default pagination behavior
        # (see https://github.com/Asana/python-asana?tab=readme-ov-file#disabling-default-pagination-behaviour)
        api_response = webhooks_api_instance.create_webhook(body, opts, full_payload=True)

        print("The complete API response for POST /webhooks is below:")
        pprint(api_response)

        webhook_gid = api_response["data"]["gid"]
        
        x_hook_secret = api_response.get('X-Hook-Secret')
        stored_secret = get_x_hook_secret()

        if x_hook_secret != stored_secret:
            print(f'X-Hook-Secrets do not match! Deleting webhook with GID {webhook_gid}')
            delete_webhook(api_response["data"]["gid"])
        else:
            print("Webhook created successfully!")
            print(f'The GID of the newly-created webhook is: {webhook_gid}')
            print(f'The X-Hook-Secret from Asana\'s response is: {x_hook_secret}')

    except ApiException as e:
        print(f"Exception when calling WebhooksApi->create_webhook: {e}\n")

# TODO: Replace these values with your target URI, object ID, filter, and resource type
target_uri = 'https://ed4f-2a01-6f01-1209-8300-6c71-cf1a-6c0c-1e74.ngrok-free.app/receive_webhook'  # The webhook server's public endpoint
object_id = '1209047969345377'  # The Asana object ID you want to track (e.g., a task gid)
filter = 'changed'  # The action to filter for
resource_type = 'task'  # Specify the resource type

create_webhook(target_uri, object_id, filter, resource_type)

it goes smooth with projects, but not whole workspace, im considering what solutions would be the best?

python create_webhook.py
Exception when calling WebhooksApi->create_webhook: (403)
Reason: Forbidden
HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json; charset=UTF-8', 'Content-Length': '454', 'Connection': 'keep-alive', 'Date': 'Mon, 30 Dec 2024 13:28:06 GMT', 'Server': 'nginx', 'cache-control': 'no-store', 'pragma': 'no-cache', 'x-frame-options': 'DENY', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'content-security-policy': "report-uri https://app.asana.com/-/csp_report?report_only=false;default-src 'none';frame-src 'none';frame-ancestors 'none'", 'x-asana-api-version': '1.0', 'asana-change': 'name=new_user_task_lists;info=https://forum.asana.com/t/update-on-our-planned-api-changes-to-user-task-lists-a-k-a-my-tasks/103828, name=new_goal_memberships;info=https://forum.asana.com/t/launched-team-sharing-for-goals/378601;affected=true', 'x-robots-tag': 'none', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 e3f435228cbc8657d81bd707948f5910.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'DUB56-P1', 'X-Amz-Cf-Id': 'sSSBzl2yVXvUEsw0fRfJbsxAMjZo42taklPjfzXXocmobwHU_GJbsw==', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'X-UA-Compatible': 'IE=edge,chrome=1'})
HTTP response body: b'{"errors":[{"error":"invalid_filters_for_larger_scoped_webhooks","message":"Webhooks for larger scoped resources must have at least one filter and all filters must be in our whitelist.","user_message":"Webhooks for larger scoped resources must have at least one filter and all filters must be in our whitelist.","help":"For more information on API status codes and how to handle them, read the docs on errors: https://developers.asana.com/docs/errors"}]}'

Upvotes: 0

Views: 10

Answers (0)

Related Questions