Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Location Search #100

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,12 +366,13 @@ Upload medias to your feed. Common arguments:

* `path` - Path to source file
* `caption` - Text for you post
* `storyUpload` - If True will create a story from image (default: False)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why need storyUpload in photo_upload? Use photo_upload_to_story for uploading photo to story

* `usertags` - List[Usertag] of mention users (see `Usertag` in [types.py](/instagrapi/types.py))
* `location` - Location (e.g. `Location(name='Test', lat=42.0, lng=42.0)`)

| Method | Return | Description |
| ------------------------------------------------------------------------------------------------------------------------- | ------- | ---------------------------------- |
| photo_upload(path: Path, caption: str, upload_id: str, usertags: List[Usertag], location: Location) | Media | Upload photo (Support JPG files) |
| photo_upload(path: Path, caption: str, storyUpload:bool , upload_id: str, usertags: List[Usertag], location: Location) | Media | Upload photo (Support JPG files) |
| video_upload(path: Path, caption: str, thumbnail: Path, usertags: List[Usertag], location: Location) | Media | Upload video (Support MP4 files) |
| igtv_upload(path: Path, title: str, caption: str, thumbnail: Path, usertags: List[Usertag], location: Location) | Media | Upload IGTV (Support MP4 files) |
| album_upload(paths: List[Path], caption: str, usertags: List[Usertag], location: Location) | Media | Upload Album (Support JPG and MP4) |
Expand All @@ -382,6 +383,7 @@ Upload medias to your stories. Common arguments:

* `path` - Path to media file
* `caption` - Caption for story (now use to fetch mentions)
* `blur` - Fill Story Background with Image Blur (Default: True)
* `thumbnail` - Thumbnail instead capture from source file
* `mentions` - Tag profiles in story
* `locations` - Add locations to story
Expand Down
Binary file added examples/photos/example.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/photos/example.jpg_STORIES.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions examples/photos/upload_photos.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from instagrapi import Client

cl = Client()
cl.login("YOUR_LOGIN", "YOUR_PASSWORD")

cl.photo_upload("example.jpg"," 😀 😃 😄 😁 😆 😅 😂 🤣 ", True)
24 changes: 24 additions & 0 deletions instagrapi/extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,30 @@ def extract_location(data):
"""Extract location info"""
if not data:
return None
data["pk"] = data.get("id", data.get("pk"))
data["external_id"] = data.get("external_id", data.get("facebook_places_id"))
data["external_id_source"] = data.get(
"external_id_source", data.get("external_source")
)

# address_json = data.get("address_json", "{}")
# if isinstance(address_json, str):
# address_json = json.loads(address_json)
# data['address_json'] = address_json
return Location(**data)



def extract_locationV2(data):
"""Extract location info"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extract_locationV2 - broken naming in the project (use extract_location_v2)

if not data:
return None
data=data["place"]["location"]
data["pk"] = data.get("id", data.get("pk"))
try:
data=data["place"]["location"]
except:
pass
data["pk"] = data.get("id", data.get("pk", None))
data["external_id"] = data.get("external_id", data.get("facebook_places_id"))
data["external_id_source"] = data.get(
Expand Down
113 changes: 105 additions & 8 deletions instagrapi/mixins/location.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from instagrapi.exceptions import (ClientLoginRequired, ClientNotFoundError,
LocationNotFound)
from instagrapi.extractors import extract_location
from instagrapi.extractors import extract_location,extract_locationV2
from instagrapi.types import Location, Media


Expand Down Expand Up @@ -42,6 +42,98 @@ def location_search(self, lat: float, lng: float) -> List[Location]:
venue["lat"] = lat
venue["lng"] = lng
locations.append(extract_location(venue))

print("location list")
print(locations)
print("--end location list")

return locations

def location_search_pk(self, pk: int) -> Location:
"""
Get locations using pk

Parameters
----------
pk: int
id
Returns
-------
Location
An object of Location
"""
result = self.top_search(self.location_info(pk).name)

location = "{}"
for places in result["places"]:
single_location=extract_locationV2(places)
if single_location.pk==pk:
location=single_location

return location

def location_search_name(self, LocationName: str) -> List[Location]:
"""
Get locations using name

Parameters
----------
LocationName: string
LocationName
Returns
-------
List[Location]
List of objects of Location
"""
result = self.top_search(LocationName)
locations = []
for places in result["places"]:
locations.append(extract_locationV2(places))

return locations

def location_search_pk(self, location_pk: int) -> Location:
"""
Get locations using pk

Parameters
----------
pk: int
id
Returns
-------
Location
An object of Location
"""
result = self.top_search(self.location_info(location_pk).name)

location = "{}"
for places in result["places"]:
single_location=extract_location(places)
if int(single_location.pk)==location_pk:
location=single_location
break

return location

def location_search_name(self, locationName) -> List[Location]:
"""
Get locations using locationName

Parameters
----------
LocationName: string
LocationName
Returns
-------
List[Location]
List of objects of Location
"""
result = self.top_search(locationName)
locations = []
for places in result["places"]:
locations.append(extract_location(places))

return locations

def location_complete(self, location: Location) -> Location:
Expand Down Expand Up @@ -95,21 +187,26 @@ def location_build(self, location: Location) -> str:
-------
str
"""
if not location:
return "{}"
if not location.external_id and location.lat:
try:
location = self.location_search(location.lat, location.lng)[0]
except IndexError:
pass
if location.pk != None:
location = self.location_search_pk(location.pk)
else:
if not location:
return "{}"
if not location.external_id and location.lat:
try:
location = self.location_search(location.lat, location.lng)[0]
except IndexError:
pass
data = {
"pk": location.pk,
"name": location.name,
"address": location.address,
"lat": location.lat,
"lng": location.lng,
"external_source": location.external_id_source,
"facebook_places_id": location.external_id,
}

return json.dumps(data, separators=(",", ":"))

def location_info_a1(self, location_pk: int) -> Location:
Expand Down
3 changes: 3 additions & 0 deletions instagrapi/mixins/photo.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ def photo_upload(
self,
path: Path,
caption: str,
storyUpload:bool=False,
upload_id: str = "",
usertags: List[Usertag] = [],
location: Location = None,
Expand Down Expand Up @@ -198,6 +199,8 @@ def photo_upload(
):
media = self.last_json.get("media")
self.expose()
if storyUpload:
self.photo_upload_to_story(path,caption)
return extract_media_v1(media)
raise PhotoConfigureError(
response=self.last_response, **self.last_json
Expand Down
9 changes: 6 additions & 3 deletions instagrapi/mixins/private.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,12 @@ def _send_private_request(
if self.user_id and login:
raise Exception(f"User already login ({self.user_id})")
try:
if not endpoint.startswith('/'):
endpoint = f"/v1/{endpoint}"
api_url = f"https://{config.API_DOMAIN}/api{endpoint}"
if "topsearch" in endpoint:
api_url= endpoint
else:
if not endpoint.startswith('/'):
endpoint = f"/v1/{endpoint}"
api_url = f"https://{config.API_DOMAIN}/api{endpoint}"
if data: # POST
# Client.direct_answer raw dict
# data = json.dumps(data)
Expand Down
2 changes: 1 addition & 1 deletion instagrapi/mixins/public.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def top_search(self, query):
"rank_token": 0.7763938004511706,
"include_reel": "true",
}
response = self.public_request(url, params=params, return_json=True)
response = self.private_request(url, params=params)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error using private requests in a public module, this makes no sense (You use private_request in public.py module)

return response


Expand Down