-
-
Save KyMidd/daef76c7ca39955f7f105fffcc342d28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Download file for user to bot | |
| # I apologize to future developers who have to maintain this code. | |
| # I can only blame the byzantine nature of the Microsoft Graph API and Teams API, | |
| # which stores files in whatever location it feels like, and then | |
| # provides a content URL that may or may not work. | |
| def download_file_for_user(file_name, file_url, headers): | |
| # If file is shared in a Team channel, the file is stored in sharepoint for the Team | |
| # We need to decode and fetch a great deal of info about sharepoint to fetch the file | |
| try: | |
| if ".sharepoint.com/sites/" in file_url: | |
| # Parse SharePoint URL | |
| parts = file_url.split(".sharepoint.com/sites/") | |
| hostname = parts[0].replace("https://", "") + ".sharepoint.com" | |
| site_path_and_file = parts[1] | |
| site_name = site_path_and_file.split("/")[0] | |
| file_relative_path_raw = site_path_and_file[len(site_name)+1:] | |
| # Get the SharePoint site ID | |
| site_lookup_url = f"https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{site_name}" | |
| site_resp = requests.get(site_lookup_url, headers=headers) | |
| site_resp.raise_for_status() | |
| site_id = site_resp.json()["id"] | |
| # Get default document library (drive) ID | |
| drive_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive" | |
| drive_resp = requests.get(drive_url, headers=headers) | |
| drive_resp.raise_for_status() | |
| drive_id = drive_resp.json()["id"] | |
| # Try the exact file path, there are sometimes invalid unicode characters like \u202f embedded | |
| file_path_encoded = urllib.parse.quote(file_relative_path_raw, safe="/") | |
| graph_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/root:/{file_path_encoded}:/content" | |
| resp = requests.get(graph_url, headers=headers) | |
| if resp.status_code == 200: | |
| print(f"🟢 Download succeeded from SharePoint site using exact path: {graph_url}") | |
| return resp.content | |
| else: | |
| print(f"🚫 Exact path download failed: {resp.status_code} - {resp.text}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment