Spaces:
Running
Running
Update app.py
Browse files1 unmodified line2345678910111213141516171819203 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061072 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851869 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632641 unmodified lineimport requestsimport base64import loggingapp = Flask(__name__)logging.basicConfig(level=logging.INFO)logger = 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()3 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",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():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(2 unmodified linesjson=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("https://slack.com/api/chat.postMessage",headers={"Authorization": f"Bearer {SLACK_TOKEN}","Content-Type": "application/json",},json={"channel": channel, "text": text},timeout=10,)9 unmodified lines@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)2 unmodified linesdef slack_events():data = request.get_json()# URL verification handshakeif data.get("type") == "url_verification":return jsonify({"challenge": data.get("challenge")})event = data.get("event", {})# Block bot messages to prevent infinite loopsif 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"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)1 unmodified line23456789101112131415161718192021222324252627282930313 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687882 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821839 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572581 unmodified lineimport requestsimport base64import loggingimport osapp = Flask(__name__)logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# ββ Credentials ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSLACK_TOKEN = os.environ.get("SLACK_TOKEN", "xoxb-7025747032292-10683671864694-lhUNPKF1KSpYwRvrvZeP7CPy")CW_COMPANY_ID = os.environ.get("CW_COMPANY_ID", "Intrinsic")CW_PUBLIC_KEY = os.environ.get("CW_PUBLIC_KEY", "IkrljDywPCSE4s10")CW_PRIVATE_KEY = os.environ.get("CW_PRIVATE_KEY", "kOwo89oUO6SVVSYi")CW_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()3 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:logger.warning("Priority discover error: %s", e)return board_id, board_name, company_id, priority_id# ββ Ticket creation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef post_ticket(payload):r = requests.post(2 unmodified linesjson=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,"board": {"id": board_id},"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"), 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, None# ββ Slack ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef send_slack(channel, text):requests.post("https://slack.com/api/chat.postMessage",headers={"Authorization": f"Bearer {SLACK_TOKEN}","Content-Type": "application/json"},json={"channel": channel, "text": text},timeout=10,)9 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","CW_COMPANY_NUM_ID": CW_COMPANY_NUM_ID or "NOT SET","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)2 unmodified linesdef 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)
app.py+143-149