Spaces:
Running
Running
Update app.py
Browse files7 unmodified lines89101112131415161718194 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677781 unmodified line808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418514 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212221 unmodified line2242252262272282292301 unmodified line2322332342352362372382 unmodified lines2412422432442452462472482492502512522532547 unmodified lineslogger = logging.getLogger(__name__)# ββ Credentials ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSLACK_TOKEN = "xoxb-7025747032292-10683671864694-lhUNPKF1KSpYwRvrvZeP7CPy"CW_COMPANY_ID = "Intrinsic"CW_PUBLIC_KEY = "IkrljDywPCSE4s10"CW_PRIVATE_KEY = "kOwo89oUO6SVVSYi"CW_CLIENT_ID = "e45cf35f-24a8-4f5f-b47a-19376cafce64"BASE_URL = "https://api-na.myconnectwise.net/v4_6_release/apis/3.0"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",}# ββ Fallback name lists (tried in order) βββββββββββββββββββββββββββββββββββββββBOARD_FALLBACKS = ["Service Desk", "Help Desk", "Support", "Technical Support","IT Support", "Service Board", "Default", "General"]COMPANY_FALLBACKS = ["Intrinsic", "intrinsic", "INTRINSIC", "IntrinsicIT","intrinsicit", "Intrinsic IT"]PRIORITY_FALLBACKS = ["Priority 1", "P1", "High", "Critical", "Urgent","Medium", "Normal", "Low", "Priority 2", "Priority 3"]# ββ Discovery helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef discover_boards():"""Return list of active service board names from ConnectWise."""try:r = requests.get(f"{BASE_URL}/service/boards",headers=CW_HEADERS,params={"conditions": "inactive=false", "pageSize": 50},timeout=10,)if r.status_code == 200:names = [b.get("name") for b in r.json() if b.get("name")]logger.info("Discovered boards: %s", names)return namesexcept Exception as e:logger.warning("Board discovery failed: %s", e)return []def discover_companies():"""Return list of company identifiers from ConnectWise."""try:r = requests.get(f"{BASE_URL}/company/companies",headers=CW_HEADERS,params={"pageSize": 50},timeout=10,)if r.status_code == 200:ids = [c.get("identifier") for c in r.json() if c.get("identifier")]logger.info("Discovered companies: %s", ids)return idsexcept Exception as e:logger.warning("Company discovery failed: %s", e)return []def discover_priorities():"""Return list of priority names from ConnectWise."""try:r = requests.get(f"{BASE_URL}/service/priorities",1 unmodified lineparams={"pageSize": 50},timeout=10,)if r.status_code == 200:names = [p.get("name") for p in r.json() if p.get("name")]logger.info("Discovered priorities: %s", names)return namesexcept Exception as e:logger.warning("Priority discovery failed: %s", e)return []def best_match(discovered, fallbacks):"""Return the first discovered value that appears in fallbacks (case-insensitive),then the first discovered value, then the first fallback."""lower_disc = {d.lower(): d for d in discovered}for f in fallbacks:if f.lower() in lower_disc:return lower_disc[f.lower()]if discovered:return discovered[0]return fallbacks[0] # last resort: just try the first hardcoded name# ββ Ticket creation with progressive fallbacks βββββββββββββββββββββββββββββββββdef try_create(payload):r = requests.post(f"{BASE_URL}/service/tickets",headers=CW_HEADERS,json=payload,timeout=10,)logger.info("CW status=%s body=%s", r.status_code, r.text[:300])return rdef create_ticket(issue):# ββ Step 1: discover real values βββββββββββββββββββββββββββββββββββββββββboards = discover_boards()companies = discover_companies()priorities = discover_priorities()board_name = best_match(boards, BOARD_FALLBACKS)company_id = best_match(companies, COMPANY_FALLBACKS)priority_name = best_match(priorities, PRIORITY_FALLBACKS)logger.info("Using board=%s company=%s priority=%s",board_name, company_id, priority_name)# ββ Step 2: full payload ββββββββββββββββββββββββββββββββββββββββββββββββββfull_payload = {"summary": issue[:100],"initialDescription": issue,"board": {"name": board_name},"company": {"identifier": company_id},"priority": {"name": priority_name},}r = try_create(full_payload)if r.status_code in (200, 201):return r.json().get("id"), board_name# ββ Step 3: try every discovered board one-by-one ββββββββββββββββββββββββfor b in boards:if b == board_name:continuepayload = {**full_payload, "board": {"name": b}}r = try_create(payload)if r.status_code in (200, 201):return r.json().get("id"), b# ββ Step 4: drop priority (might be wrong) ββββββββββββββββββββββββββββββββlogger.warning("Retrying without priority field")no_priority = {k: v for k, v in full_payload.items() if k != "priority"}r = try_create(no_priority)if r.status_code in (200, 201):return r.json().get("id"), board_name# ββ Step 5: drop company too βββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββlogger.warning("Retrying without company or priority")minimal_board = {"summary": issue[:100],"initialDescription": issue,"board": {"name": board_name},}r = try_create(minimal_board)if r.status_code in (200, 201):return r.json().get("id"), board_name# ββ Step 6: bare minimum β just summary βββββββββββββββββββββββββββββββββββlogger.warning("Retrying with bare minimum payload")bare = {"summary": issue[:100], "initialDescription": issue}r = try_create(bare)if r.status_code in (200, 201):return r.json().get("id"), "default"logger.error("All ticket creation attempts failed")return None, None# ββ Slack helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef send_slack(channel, text):requests.post(14 unmodified linesreturn "Slack β ConnectWise Bot Running β "@app.route("/debug/cw", methods=["GET"])def debug_cw():"""Hit /debug/cw in your browser to see exactly what boards / companies /priorities exist in your ConnectWise instance."""return jsonify({"boards": discover_boards(),"companies": discover_companies(),"priorities": discover_priorities(),})@app.route("/slack/events", methods=["POST"])def slack_events():data = request.get_json()logger.info("Slack payload type=%s", data.get("type"))# URL verification handshakeif data.get("type") == "url_verification":1 unmodified lineevent = data.get("event", {})# Ignore bot messages to prevent loopsif event.get("bot_id") or event.get("subtype") == "bot_message":return "", 2001 unmodified linetext = event.get("text", "")channel = event.get("channel")# Strip bot mentiontext = text.replace("<@U0AL3KRRELE>", "").strip()if not text:return "", 2002 unmodified linesif ticket_id:reply = (f"β Support ticket created!\n"f"π« Ticket ID: `{ticket_id}`\n"f"π Board: {board_used}")else:reply = ("β οΈ Could not create a ConnectWise ticket right now.\n""Please contact support directly or try again shortly.")send_slack(channel, reply)7 unmodified lines89101112131415161718194 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990911 unmodified line9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717814 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified line2352362372382392402411 unmodified line2432442452462472482 unmodified lines2512522532542552562572582592602612622632647 unmodified lineslogger = logging.getLogger(__name__)# ββ Credentials ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSLACK_TOKEN = "xoxb-7025747032292-10683671864694-lhUNPKF1KSpYwRvrvZeP7CPy"CW_COMPANY_ID = "Intrinsic"CW_PUBLIC_KEY = "IkrljDywPCSE4s10"CW_PRIVATE_KEY = "kOwo89oUO6SVVSYi"CW_CLIENT_ID = "e45cf35f-24a8-4f5f-b47a-19376cafce64"BASE_URL = "https://api-na.myconnectwise.net/v4_6_release/apis/3.0"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",}COMPANY_NAME_VARIANTS = ["Intrinsic", "intrinsic", "INTRINSIC", "IntrinsicIT", "Intrinsic IT"]# ββ Discovery helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_all_boards():"""Return list of (id, name) for all service boards (active + inactive)."""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[:600])if r.status_code == 200:return [(b.get("id"), b.get("name")) for b in r.json() if b.get("id")]except Exception as e:logger.warning("Board fetch error: %s", e)return []def get_company_id():"""Try multiple name variants; fall back to first company in system."""for variant in COMPANY_NAME_VARIANTS:try:r = requests.get(f"{BASE_URL}/company/companies",headers=CW_HEADERS,params={"conditions": f'name contains "{variant}"',"pageSize": 10,},timeout=10,)logger.info("Company search '%s' β %s: %s", variant, r.status_code, r.text[:300])if r.status_code == 200 and r.json():return r.json()[0].get("id")except Exception as e:logger.warning("Company search error '%s': %s", variant, e)# Fall back to first company in the systemtry:r = requests.get(f"{BASE_URL}/company/companies",headers=CW_HEADERS,params={"pageSize": 1},timeout=10,)if r.status_code == 200 and r.json():c = r.json()[0]logger.warning("Using first company fallback: %s id=%s", c.get("name"), c.get("id"))return c.get("id")except Exception as e:logger.warning("Fallback company error: %s", e)return Nonedef get_priority_id():"""Return numeric id of the first available priority."""try:r = requests.get(f"{BASE_URL}/service/priorities",1 unmodified lineparams={"pageSize": 50},timeout=10,)logger.info("Priorities %s: %s", r.status_code, r.text[:300])if r.status_code == 200 and r.json():return r.json()[0].get("id")except Exception as e:logger.warning("Priority fetch error: %s", e)return None# ββ Ticket creation with 4-level fallback ββββββββββββββββββββββββββββββββββββββdef post_ticket(payload):r = requests.post(f"{BASE_URL}/service/tickets",headers=CW_HEADERS,json=payload,timeout=10,)logger.info("CW POST status=%s body=%s", r.status_code, r.text[:500])return rdef create_ticket(issue):summary = issue[:100]boards = get_all_boards() # [(id, name), ...]company_id = get_company_id() # numeric intpriority_id = get_priority_id() # numeric intlogger.info("Resolved β boards=%s company_id=%s priority_id=%s",boards, company_id, priority_id)# ββ Attempt 1: each board + company numeric ID ββββββββββββββββββββββββββββif company_id and boards:for bid, bname in boards:payload = {"summary": summary,"initialDescription": issue,"board": {"id": bid},"company": {"id": company_id},}if priority_id:payload["priority"] = {"id": priority_id}r = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), bname# ββ Attempt 2: company only (CW picks default 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"# ββ Attempt 3: string identifier variants βββββββββββββββββββββββββββββββββfor variant in COMPANY_NAME_VARIANTS:for bid, bname in (boards or [(None, None)]):payload = {"summary": summary,"initialDescription": issue,"company": {"identifier": variant},}if bid:payload["board"] = {"id": bid}r = post_ticket(payload)if r.status_code in (200, 201):return r.json().get("id"), bname or "default"# ββ Attempt 4: absolute minimum (summary only) ββββββββββββββββββββββββββββr = post_ticket({"summary": summary, "initialDescription": issue})if r.status_code in (200, 201):return r.json().get("id"), "default"logger.error("All ticket attempts failed")return None, None# ββ Slack helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef send_slack(channel, text):requests.post(14 unmodified linesreturn "Slack β ConnectWise Bot Running β "@app.route("/debug/cw")def debug_cw():"""Visit this URL in your browser to see the REAL board names, company IDs,and priority IDs in your ConnectWise instance."""out = {}try:r = requests.get(f"{BASE_URL}/service/boards", headers=CW_HEADERS,params={"pageSize": 100}, timeout=10)out["boards"] = r.json() if r.status_code == 200 else {"error": r.text}except Exception as e:out["boards"] = {"error": str(e)}try:r = requests.get(f"{BASE_URL}/company/companies", headers=CW_HEADERS,params={"pageSize": 20}, timeout=10)out["companies"] = r.json() if r.status_code == 200 else {"error": r.text}except Exception as e:out["companies"] = {"error": str(e)}try:r = requests.get(f"{BASE_URL}/service/priorities", headers=CW_HEADERS,params={"pageSize": 20}, timeout=10)out["priorities"] = r.json() if r.status_code == 200 else {"error": r.text}except Exception as e:out["priorities"] = {"error": str(e)}return jsonify(out)@app.route("/slack/events", methods=["POST"])def slack_events():data = request.get_json()# URL verification handshakeif data.get("type") == "url_verification":1 unmodified lineevent = data.get("event", {})# Block bot messages to prevent infinite loopsif event.get("bot_id") or event.get("subtype") == "bot_message":return "", 2001 unmodified linetext = event.get("text", "")channel = event.get("channel")text = text.replace("<@U0AL3KRRELE>", "").strip()if not text:return "", 2002 unmodified linesif ticket_id:reply = (f"β Ticket created!\n"f"π« ID: `{ticket_id}`\n"f"π Board: {board_used}")else:reply = ("β οΈ Could not create a ConnectWise ticket.\n""Visit /debug/cw to see available boards & companies.")send_slack(channel, reply)
app.py+135-125