Mr-Help's picture
Update app.py
13ec99b verified
raw
history blame
5.59 kB
from fastapi import FastAPI, Request
from pydantic import BaseModel
import requests
import logging
from datetime import datetime
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
app = FastAPI()
# ClickUp API URL for creating a task
LIST_ID = "901208781277"
URL = f"https://api.clickup.com/api/v2/list/{LIST_ID}/task"
# WhatsApp API URL
WHATSAPP_URL = "https://7105.api.greenapi.com/waInstance7105210836/sendMessage/805b69f6c85d4e6caea0edaba692b889abecc9e6bb8b457e8f"
# Your access token
ACCESS_TOKEN = "2144425825_36f2249dc27c5aca075ac5442b1bbcdf01c3a29b9e41b86bda46a6cf651acd0f"
# Headers for ClickUp authorization
headers = {
"Authorization": ACCESS_TOKEN,
"Content-Type": "application/json"
}
# Headers for WhatsApp API
whatsapp_headers = {
"Content-Type": "application/json"
}
class TaskData(BaseModel):
task_name: str
task_type: str # "Reel" or "Design"
campaign_name: str
platforms: list[str]
assignees: list[int] # List of user IDs
due_date: int # Unix timestamp in milliseconds
@app.post("/singetask")
def create_task(task: TaskData):
logging.info(f"Received task data: {task}")
# Convert Unix timestamp to a readable date
due_date_human = datetime.utcfromtimestamp(task.due_date / 1000).strftime('%Y-%m-%d %H:%M:%S')
description = f"Task Type: {task.task_type}\nCampaign: {task.campaign_name}\nPlatforms: {', '.join(task.platforms)}"
payload = {
"name": task.task_name,
"description": description,
"assignees": task.assignees,
"priority": 3, # Priority levels: 1 (Low), 2 (Normal), 3 (High), 4 (Urgent)
"due_date": task.due_date, # Unix timestamp in milliseconds
"status": "backlog" # Adjust based on your workflow
}
logging.info(f"Sending request to ClickUp with payload: {payload}")
response = requests.post(URL, headers=headers, json=payload)
response_data = response.json()
logging.info(f"Received response from ClickUp: {response.status_code}, {response_data}")
# Prepare WhatsApp notification
if response.status_code == 200:
task_id = response_data.get("id", "Unknown ID")
task_link = f"https://app.clickup.com/t/{task_id}"
whatsapp_payload = {
"chatId": "201092003112@c.us", # Updated recipient number
"message": f"🚀 *New Task Assigned!*\n\n📌 *Task:* {task.task_name}\n📅 *Due Date:* {due_date_human}\n👤 *Assigned To:* {', '.join(map(str, task.assignees))}\n📝 *Description:* {description}\n\n🔗 *View Task:* {task_link}\n\nLet's get this done! ✅"
}
else:
# If ClickUp API fails, send an error message on WhatsApp mentioning the task name
error_message = response_data.get("err", "Unknown error")
failure_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
whatsapp_payload = {
"chatId": "201092003112@c.us", # Updated recipient number
"message": f"⚠️ *Task Creation Failed!*\n\n📌 *Task:* {task.task_name}\n❌ *Error:* {error_message}\n⏰ *Time:* {failure_time}\n\nPlease check the request and try again."
}
logging.info(f"Sending WhatsApp notification with payload: {whatsapp_payload}")
whatsapp_response = requests.post(WHATSAPP_URL, json=whatsapp_payload, headers=whatsapp_headers)
logging.info(f"WhatsApp API Response: {whatsapp_response.status_code}, {whatsapp_response.json()}")
return {"status_code": response.status_code, "response": response_data}
@app.post("/updates")
async def task_update(request: Request):
data = await request.json()
logging.info(f"Received task update from ClickUp: {data}")
event_type = data.get("event")
task_id = data.get("task_id", "Unknown ID")
task_name = data.get("task", {}).get("name", "Unknown Task")
task_link = f"https://app.clickup.com/t/{task_id}"
if event_type == "taskUpdated":
# Extract the new status
history_items = data.get("history_items", [])
if history_items:
new_status = history_items[0].get("after", {}).get("status", "").lower()
action_timestamp = history_items[0].get("date", 0)
else:
logging.error("No history items found in taskUpdated event.")
return {"error": "No history items found."}
# Convert action timestamp to readable date
action_date_human = datetime.utcfromtimestamp(int(action_timestamp) / 1000).strftime('%Y-%m-%d %H:%M:%S') if action_timestamp else "Unknown Date"
logging.info(f"Task: {task_name}, New Status: {new_status}, Action Date: {action_date_human}")
if new_status == "ready for review":
whatsapp_payload = {
"chatId": "201092003112@c.us",
"message": f"📝 *Task Submitted for Review!*\n\n📌 *Task:* {task_name}\n📅 *Submitted On:* {action_date_human}\n\n🔗 *View Task:* {task_link}\n\nPlease review the task and provide feedback."
}
logging.info(f"Sending WhatsApp notification: {whatsapp_payload}")
whatsapp_response = requests.post(WHATSAPP_URL, json=whatsapp_payload, headers=whatsapp_headers)
logging.info(f"WhatsApp API Response: {whatsapp_response.status_code} - {whatsapp_response.text}")
elif event_type == "taskTagUpdated":
# Just print the response instead of sending a WhatsApp notification
logging.info(f"TaskTagUpdated event received: {data}")
return {"status": "Update received"}