Spaces:
Running
Running
Update app.py
Browse files2 unmodified lines3456787 unmodified lines1617181920212223242526272829304 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778795 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161175 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721739 unmodified lines1831841851861871883 unmodified lines1921931941951961971981992002012022032042052061 unmodified line2082092102112122132142152162172182192202212222232242252261 unmodified line2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612 unmodified linesimport base64import loggingimport osapp = Flask(__name__)logging.basicConfig(level=logging.INFO)7 unmodified linesCW_CLIENT_ID = os.environ.get("CW_CLIENT_ID", "e45cf35f-24a8-4f5f-b47a-19376cafce64")BASE_URL = "https://api-na.myconnectwise.net/v4_6_release/apis/3.0"# ββ HARDCODED FALLBACKS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Set these as Hugging Face Secrets once you find the real values in ConnectWise.# Log into ConnectWise manually and check:# CW_BOARD_ID β Service Desk β Boards β open your board β ID is in the URL# CW_COMPANY_NUM_IDβ Companies β your company β ID in URL# CW_PRIORITY_ID β Service Desk β Priority List β ID in URLCW_BOARD_ID = os.environ.get("CW_BOARD_ID", "") # e.g. "1"CW_COMPANY_NUM_ID = os.environ.get("CW_COMPANY_NUM_ID", "") # e.g. "250"CW_PRIORITY_ID = os.environ.get("CW_PRIORITY_ID", "") # e.g. "8"auth = f"{CW_COMPANY_ID}+{CW_PUBLIC_KEY}:{CW_PRIVATE_KEY}"encoded_auth = base64.b64encode(auth.encode()).decode()4 unmodified lines"Content-Type": "application/json",}# ββ Discovery (works only once 403 is fixed) βββββββββββββββββββββββββββββββββββdef discover():"""Try to pull board/company/priority IDs from the API."""board_id = company_id = priority_id = Noneboard_name = "default"try:r = requests.get(f"{BASE_URL}/service/boards", headers=CW_HEADERS,params={"pageSize": 100}, timeout=10)logger.info("Boards %s: %s", r.status_code, r.text[:400])if r.status_code == 200 and r.json():b = r.json()[0]board_id, board_name = b["id"], b["name"]except Exception as e:logger.warning("Board discover error: %s", e)try:r = requests.get(f"{BASE_URL}/company/companies", headers=CW_HEADERS,params={"pageSize": 50}, timeout=10)logger.info("Companies %s: %s", r.status_code, r.text[:400])if r.status_code == 200 and r.json():# Try to match our company name, else take firstall_companies = r.json()match = next((c for c in all_companiesif CW_COMPANY_ID.lower() in (c.get("name","") + c.get("identifier","")).lower()),all_companies[0])company_id = match["id"]logger.info("Matched company: %s id=%s", match.get("name"), company_id)except Exception as e:logger.warning("Company discover error: %s", e)try:r = requests.get(f"{BASE_URL}/service/priorities", headers=CW_HEADERS,params={"pageSize": 50}, timeout=10)logger.info("Priorities %s: %s", r.status_code, r.text[:300])if r.status_code == 200 and r.json():priority_id = r.json()[0]["id"]except Exception as e:5 unmodified lines# ββ Ticket creation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef post_ticket(payload):r = requests.post(f"{BASE_URL}/service/tickets",headers=CW_HEADERS,json=payload,timeout=10,)logger.info("CW POST %s: %s", r.status_code, r.text[:500])return rdef create_ticket(issue):summary = issue[:100]# Use hardcoded env var IDs if set, otherwise try discoveryif CW_BOARD_ID and CW_COMPANY_NUM_ID:board_id = int(CW_BOARD_ID)company_id = int(CW_COMPANY_NUM_ID)priority_id = int(CW_PRIORITY_ID) if CW_PRIORITY_ID else Noneboard_name = "configured"logger.info("Using env var IDs: board=%s company=%s priority=%s",board_id, company_id, priority_id)else:board_id, board_name, company_id, priority_id = discover()attempts = []# ββ 1. Numeric IDs (most reliable) βββββββββββββββββββββββββββββββββββββββif board_id and company_id:payload = {"summary": summary, "initialDescription": issue,5 unmodified linesr = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), board_nameattempts.append(r.text)# ββ 2. Company numeric ID only (no board) ββββββββββββββββββββββββββββββββif company_id:payload = {"summary": summary, "initialDescription": issue,"company": {"id": company_id},}r = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), "default"attempts.append(r.text)# ββ 3. Member's own company as the company (common CW pattern) βββββββββββ# When company = the MSP itself, CW sometimes needs companyType or contactId# Try with just the member company ID from logintry:r2 = requests.get(f"{BASE_URL}/system/members/me",headers=CW_HEADERS, timeout=10)if r2.status_code == 200:me = r2.json()my_company_id = me.get("company", {}).get("id")logger.info("Member company id: %s", my_company_id)if my_company_id:payload = {"summary": summary, "initialDescription": issue,"company": {"id": my_company_id},}if board_id:payload["board"] = {"id": board_id}r = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), board_name or "default"attempts.append(r.text)except Exception as e:logger.warning("Member lookup failed: %s", e)# ββ 4. Absolute minimum βββββββββββββββββββββββββββββββββββββββββββββββββββr = post_ticket({"summary": summary, "initialDescription": issue})if r.status_code in (200, 201):return r.json().get("id"), "default"logger.error("All attempts failed. Last errors: %s", attempts[-3:])return None, None9 unmodified lines)# ββ Routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.route("/")3 unmodified lines@app.route("/debug/cw")def debug_cw():"""Visit /debug/cw to see what your API key CAN access.If you see 403 errors here, your API key needs more permissions in ConnectWise.Go to: System β Members β API Members β Security Role β enable Inquire on:Companies > Company MaintenanceService Desk > Service BoardsService Desk > Service Tickets (Add + Inquire)Service Desk > Priorities"""out = {"env_vars": {"CW_BOARD_ID": CW_BOARD_ID or "NOT SET",1 unmodified line"CW_PRIORITY_ID": CW_PRIORITY_ID or "NOT SET",}}for label, url, params in [("boards", f"{BASE_URL}/service/boards", {"pageSize": 50}),("companies", f"{BASE_URL}/company/companies", {"pageSize": 20}),("priorities", f"{BASE_URL}/service/priorities", {"pageSize": 20}),("member_me", f"{BASE_URL}/system/members/me", {}),]:try:r = requests.get(url, headers=CW_HEADERS, params=params, timeout=10)out[label] = {"status": r.status_code, "data": r.json()}except Exception as e:out[label] = {"error": str(e)}return jsonify(out)1 unmodified linedef slack_events():data = request.get_json()if data.get("type") == "url_verification":return jsonify({"challenge": data.get("challenge")})event = data.get("event", {})if event.get("bot_id") or event.get("subtype") == "bot_message":return "", 200if event.get("type") == "message":text = event.get("text", "")channel = event.get("channel")text = text.replace("<@U0AL3KRRELE>", "").strip()if not text:return "", 200ticket_id, board_used = create_ticket(text)if ticket_id:reply = f"β Ticket created!\nπ« ID: `{ticket_id}`\nπ Board: {board_used}"else:reply = ("β οΈ Could not create ticket. Your API key needs more permissions in ConnectWise.\n""Go to: System β Members β API Members β Security Role\n""Enable Inquire on: Company Maintenance, Service Boards, Service Tickets, Priorities")send_slack(channel, reply)return "", 2002 unmodified lines34567897 unmodified lines1718192021222324254 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586875 unmodified lines939495969798991001011021031041051061071081091101111121131141151165 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511529 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961973 unmodified lines2012022032042052061 unmodified line2082092102112122132142152162172182192202212222232241 unmodified line2262272282292302312322332342352362372382392402412422432442 unmodified linesimport base64import loggingimport osimport threadingapp = Flask(__name__)logging.basicConfig(level=logging.INFO)7 unmodified linesCW_CLIENT_ID = os.environ.get("CW_CLIENT_ID", "e45cf35f-24a8-4f5f-b47a-19376cafce64")BASE_URL = "https://api-na.myconnectwise.net/v4_6_release/apis/3.0"CW_BOARD_ID = os.environ.get("CW_BOARD_ID", "")CW_COMPANY_NUM_ID = os.environ.get("CW_COMPANY_NUM_ID", "")CW_PRIORITY_ID = os.environ.get("CW_PRIORITY_ID", "")auth = f"{CW_COMPANY_ID}+{CW_PUBLIC_KEY}:{CW_PRIVATE_KEY}"encoded_auth = base64.b64encode(auth.encode()).decode()4 unmodified lines"Content-Type": "application/json",}# ββ Deduplication: track already-processed Slack event IDs ββββββββββββββββββββ# Stores the last 500 event IDs to prevent duplicate processingprocessed_events = set()processed_lock = threading.Lock()def already_seen(event_id):"""Returns True if we've already processed this event. Thread-safe."""with processed_lock:if event_id in processed_events:return Trueprocessed_events.add(event_id)# Keep the set from growing foreverif len(processed_events) > 500:oldest = next(iter(processed_events))processed_events.discard(oldest)return False# ββ Discovery ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef discover():board_id = company_id = priority_id = Noneboard_name = "default"try:r = requests.get(f"{BASE_URL}/service/boards", headers=CW_HEADERS,params={"pageSize": 100}, timeout=10)if r.status_code == 200 and r.json():b = r.json()[0]board_id, board_name = b["id"], b["name"]logger.info("Discovered board: %s id=%s", board_name, board_id)except Exception as e:logger.warning("Board discover error: %s", e)try:r = requests.get(f"{BASE_URL}/company/companies", headers=CW_HEADERS,params={"pageSize": 50}, timeout=10)if r.status_code == 200 and r.json():all_cos = r.json()match = next((c for c in all_cosif CW_COMPANY_ID.lower() in (c.get("name","") + c.get("identifier","")).lower()),all_cos[0])company_id = match["id"]logger.info("Discovered company: %s id=%s", match.get("name"), company_id)except Exception as e:logger.warning("Company discover error: %s", e)try:r = requests.get(f"{BASE_URL}/service/priorities", headers=CW_HEADERS,params={"pageSize": 50}, timeout=10)if r.status_code == 200 and r.json():priority_id = r.json()[0]["id"]except Exception as e:5 unmodified lines# ββ Ticket creation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef post_ticket(payload):r = requests.post(f"{BASE_URL}/service/tickets",headers=CW_HEADERS, json=payload, timeout=10)logger.info("CW POST %s: %s", r.status_code, r.text[:400])return rdef create_ticket(issue):summary = issue[:100]if CW_BOARD_ID and CW_COMPANY_NUM_ID:board_id = int(CW_BOARD_ID)company_id = int(CW_COMPANY_NUM_ID)priority_id = int(CW_PRIORITY_ID) if CW_PRIORITY_ID else Noneboard_name = "configured"else:board_id, board_name, company_id, priority_id = discover()# Attempt 1: full numeric IDsif board_id and company_id:payload = {"summary": summary, "initialDescription": issue,5 unmodified linesr = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), board_name# Attempt 2: company onlyif company_id:r = post_ticket({"summary": summary, "initialDescription": issue,"company": {"id": company_id}})if r.status_code in (200, 201):return r.json().get("id"), "default"# Attempt 3: use member's own company IDtry:r2 = requests.get(f"{BASE_URL}/system/members/me", headers=CW_HEADERS, timeout=10)if r2.status_code == 200:my_cid = r2.json().get("company", {}).get("id")if my_cid:payload = {"summary": summary, "initialDescription": issue,"company": {"id": my_cid}}if board_id:payload["board"] = {"id": board_id}r = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), board_name or "default"except Exception as e:logger.warning("Member lookup failed: %s", e)logger.error("All ticket attempts failed")return None, None9 unmodified lines)def handle_event(event_data):"""Run in background thread so Slack gets 200 instantly."""event = event_data.get("event", {})if event.get("bot_id") or event.get("subtype") == "bot_message":returnif event.get("type") != "message":returntext = event.get("text", "")channel = event.get("channel")text = text.replace("<@U0AL3KRRELE>", "").strip()if not text:returnticket_id, board_used = create_ticket(text)if ticket_id:reply = f"β Ticket created!\nπ« ID: `{ticket_id}`\nπ Board: {board_used}"else:reply = ("β οΈ Could not create ConnectWise ticket.\n""Visit /debug/cw to check API permissions.")send_slack(channel, reply)# ββ Routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.route("/")3 unmodified lines@app.route("/debug/cw")def debug_cw():out = {"env_vars": {"CW_BOARD_ID": CW_BOARD_ID or "NOT SET",1 unmodified line"CW_PRIORITY_ID": CW_PRIORITY_ID or "NOT SET",}}for label, url, params in [("boards", f"{BASE_URL}/service/boards", {"pageSize": 50}),("companies", f"{BASE_URL}/company/companies", {"pageSize": 20}),("priorities", f"{BASE_URL}/service/priorities", {"pageSize": 20}),("member_me", f"{BASE_URL}/system/members/me", {}),]:try:r = requests.get(url, headers=CW_HEADERS, params=params, timeout=10)out[label] = {"status": r.status_code, "data": r.json()}except Exception as e:out[label] = {"error": str(e)}return jsonify(out)1 unmodified linedef slack_events():data = request.get_json()# URL verification handshakeif data.get("type") == "url_verification":return jsonify({"challenge": data.get("challenge")})# ββ Deduplicate: drop retries of the same event ββββββββββββββββββββββββevent_id = data.get("event_id", "")if event_id and already_seen(event_id):logger.info("Duplicate event %s β ignored", event_id)return "", 200# ββ Return 200 immediately so Slack stops retrying βββββββββββββββββββββthread = threading.Thread(target=handle_event, args=(data,), daemon=True)thread.start()return "", 200
app.py+83-100