11import os
2+ import time
23
34import requests
45
@@ -22,6 +23,7 @@ def platform_name(self) -> str:
2223
2324 def authenticate (self ) -> bool :
2425 if not self ._is_available :
26+ print ("Instagram: credentials not set (INSTAGRAM_BUSINESS_ACCOUNT_ID or INSTAGRAM_PAGE_ACCESS_TOKEN missing)" )
2527 return False
2628 try :
2729 response = requests .get (
@@ -32,7 +34,13 @@ def authenticate(self) -> bool:
3234 response .raise_for_status ()
3335 self ._authenticated = True
3436 return True
35- except Exception :
37+ except requests .exceptions .HTTPError as exc :
38+ body = exc .response .text if exc .response is not None else "no response body"
39+ print (f"Instagram auth failed (HTTP { exc .response .status_code } ): { body } " )
40+ self ._authenticated = False
41+ return False
42+ except Exception as exc :
43+ print (f"Instagram auth failed: { exc } " )
3644 self ._authenticated = False
3745 return False
3846
@@ -51,14 +59,25 @@ def publish(self, post: Post) -> PostResult:
5159
5260 try :
5361 container_id = self ._create_media_container (post )
62+ # Instagram needs time to process the uploaded image before publishing.
63+ # Publishing immediately returns "Media ID is not available" (error 9007).
64+ time .sleep (10 )
65+
5466 media_id = self ._publish_media (container_id )
5567 return PostResult (
5668 success = True ,
5769 post_id = media_id ,
5870 post_url = "https://www.instagram.com/cute.pets.boston/" ,
5971 )
72+ except requests .exceptions .HTTPError as exc :
73+ body = exc .response .text if exc .response is not None else "no response body"
74+ error = f"Instagram publish failed (HTTP { exc .response .status_code } ): { body } "
75+ print (error )
76+ return PostResult (success = False , error_message = error )
6077 except Exception as exc :
61- return PostResult (success = False , error_message = str (exc ))
78+ error = f"Instagram publish failed: { exc } "
79+ print (error )
80+ return PostResult (success = False , error_message = error )
6281
6382 def _create_media_container (self , post : Post ) -> str :
6483 """Create a media container and return its ID."""
@@ -75,6 +94,7 @@ def _create_media_container(self, post: Post) -> str:
7594 response .raise_for_status ()
7695 return response .json ()["id" ]
7796
97+
7898 def _publish_media (self , container_id : str ) -> str :
7999 response = requests .post (
80100 f"{ GRAPH_API_BASE } /{ self .account_id } /media_publish" ,
0 commit comments