示例#1
0
    def get_medias_info(
        self,
        media_ids,  # type: Union[str, List, Tuple, Set]
        fields=None,  # type: Optional[Union[str, List, Tuple, Set]]
        return_json=False  # type: bool
    ):
        # type: (...) -> dict
        """
        Retrieve the media info by media id.
        :param media_ids: Comma-separated id string for media which you want.
                You can also pass this with an id list, tuple, set.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
        :param return_json: Set to false will return a dict values are instance of IgProUser.
                Or return json data. Default is false.
        """
        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_OWNER_FIELD

        args = {
            "fields": enf_comma_separated("fields", fields),
            "ids": enf_comma_separated("media_ids", media_ids)
        }

        resp = self._request(path='{0}/'.format(self.version), args=args)

        data = self._parse_response(resp)
        if return_json:
            return data
        else:
            return {
                _id: IgProMedia.new_from_json_dict(p_data)
                for _id, p_data in iteritems(data)
            }
示例#2
0
    def get_media_info(
        self,
        media_id,  # type: str
        fields=None,  # type: Optional[Union[str, List, Tuple, Set]]
        return_json=False  # type: bool
    ):
        # type: (...) -> Union[IgProMedia, dict]
        """
        Retrieve the media info by media id.
        :param media_id: The media id for which you want to get data.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
        :param return_json: Set to false will return instance of IgProUser.
                Or return json data. Default is false.
        """
        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_OWNER_FIELD

        args = {'fields': enf_comma_separated("fields", fields)}

        resp = self._request(path='{0}/{1}'.format(self.version, media_id),
                             args=args)

        data = self._parse_response(resp)
        if return_json:
            return data
        else:
            return IgProMedia.new_from_json_dict(data)
示例#3
0
    def get_mentioned_media_info(
            self,
            user_id,  # type: str
            media_id,  # type: str
            fields=None,  # type: Union[str, List, Tuple, Set]
            access_token=None,  # type: str
            return_json=False,  # type: bool
    ):
        # type: (...) -> Union[IgProMedia, dict]
        """
        You can use this to retrieve media info which an ig user has been @mentioned in a caption by another ig user.

        :param user_id: Target user id which media mentioned for.
        :param media_id: The media id which the ig user has been @mentioned.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
                Default is all public fields. fields as follows:
                (caption,comments,comments_count,like_count,media_type,media_url,owner,timestamp,username)
        :param access_token: Target user access token. If not will use default access token.
        :param return_json: Set to false will return a list of instance of IgProMedia.
                Or return json data. Default is false.
        :return: media data
        """

        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_PUBLIC_FIELD.union({
                "comments{{{}}}".format(",".join(
                    constant.INSTAGRAM_COMMENT_FIELD))
            })

        args = {
            "fields":
            "mentioned_media.media_id({media_id}){{{fields}}}".format(
                media_id=media_id,
                fields=enf_comma_separated(field="fields", value=fields))
        }

        if access_token is not None:
            args["access_token"] = access_token

        resp = self._request(path="{0}/{1}".format(self.version, user_id),
                             args=args)
        data = self._parse_response(resp)

        if return_json:
            return data["mentioned_media"]
        else:
            return IgProMedia.new_from_json_dict(data["mentioned_media"])
示例#4
0
    def discovery_user_medias(
            self,
            username,  # type: str
            fields=None,  # type: Optional[Union[str, List, Tuple, Set]]
            since_time=None,  # type: Optional[str]
            until_time=None,  # type: Optional[str]
            count=10,  # type: Optional[int]
            limit=10,  # type: int
            return_json=False  # type: bool
    ):
        # type: (...) -> List[Union[IgProMedia, dict]]
        """
        Retrieve other business user's public medias.

        :param username: The username for other business user.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
        :param since_time: Lower bound of the time range to the medias publish time.
                Format is %Y-%m-%d. If not provide, will not limit by this.
        :param until_time: Upper bound of the time range to the medias publish time.
                Format is %Y-%m-%d. If not provide, will not limit by this.
        :param count: The count is you want to retrieve medias. Default is 10.
                If you want to get all data. Set it to None.
                For now This may be not more than 10K.
        :param limit: Each request retrieve posts count from api.
                For medias it should no more than 500.
        :param return_json: Set to false will return a list instance of IgProMedia.
        Or return json data. Default is false.
        """

        try:
            if since_time is not None:
                since_time = datetime.datetime.strptime(since_time, '%Y-%m-%d')
            if until_time is not None:
                until_time = datetime.datetime.strptime(until_time, '%Y-%m-%d')
        except (ValueError, TypeError):
            raise PyFacebookException(
                ErrorMessage(
                    code=ErrorCode.INVALID_PARAMS,
                    message="since_time or until_time must format as %Y-%m-%d")
            )

        if count is not None:
            limit = min(limit, count)

        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_PUBLIC_FIELD
        fields = enf_comma_separated("fields", fields)

        if (since_time is not None
                or until_time is not None) and "timestamp" not in fields:
            raise PyFacebookException(
                ErrorMessage(
                    code=ErrorCode.MISSING_PARAMS,
                    message=
                    "Use the since and until must give `timestamp` field"))

        args = {
            'path': '{0}/{1}'.format(self.version, self.instagram_business_id),
            'username': username,
            'limit': limit,
            "metric": enf_comma_separated("fields", fields),
        }

        medias = []
        next_cursor = None

        while True:
            next_cursor, previous_cursor, data = self.paged_by_cursor(
                args=args, next_cursor=next_cursor, business_discovery=True)
            data = data.get('data', [])
            # check if the media meet the request.
            for item in data:
                begin_flag, end_flag = True, True

                if "timestamp" in item:
                    timestamp = datetime.datetime.strptime(
                        item['timestamp'][:-5], '%Y-%m-%dT%H:%M:%S')
                    if since_time is not None:
                        begin_flag = since_time < timestamp
                    if until_time is not None:
                        end_flag = until_time > timestamp

                if all([begin_flag, end_flag]):
                    if return_json:
                        medias.append(item)
                    else:
                        medias.append(IgProMedia.new_from_json_dict(item))
                if not begin_flag:
                    next_cursor = None
                    break

            if count is not None:
                if len(medias) >= count:
                    medias = medias[:count]
                    break
            if next_cursor is None:
                break
        return medias
示例#5
0
    def get_user_medias(
            self,
            user_id,  # type: str
            fields=None,  # type: Optional[Union[str, List, Tuple, Set]]
            since_time=None,  # type: Optional[str]
            until_time=None,  # type: Optional[str]
            count=10,  # type: Optional[int]
            limit=10,  # type: int
            return_json=False  # type: bool
    ):
        # type: (...) -> List[Union[IgProMedia, dict]]
        """
        Retrieve ig user medias data by user id.
        :param user_id: The id for instagram business user which you want to get data.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
        :param since_time: Lower bound of the time range to the medias publish time.
                Format is %Y-%m-%d. If not provide, will not limit by this.
        :param until_time: Upper bound of the time range to the medias publish time.
                Format is %Y-%m-%d. If not provide, will not limit by this.
        :param count: The count for you want to get medias.
                Default is 10.
                If need get all, set this with None.
        :param limit: Each request retrieve medias count from api.
                For medias it should no more than 500.
        :param return_json: Set to false will return instance of IgProUser.
                Or return json data. Default is false.
        """

        try:
            if since_time is not None:
                since_time = datetime.datetime.strptime(since_time, '%Y-%m-%d')
            if until_time is not None:
                until_time = datetime.datetime.strptime(until_time, '%Y-%m-%d')
        except (ValueError, TypeError):
            raise PyFacebookException(
                ErrorMessage(
                    code=ErrorCode.INVALID_PARAMS,
                    message="since_time or until_time must format as %Y-%m-%d",
                ))

        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_OWNER_FIELD

        if count is not None:
            limit = min(limit, count)

        args = {
            'fields': enf_comma_separated("fields", fields),
            'limit': limit
        }

        medias = []
        next_cursor = None

        while True:
            next_cursor, previous_cursor, data = self.paged_by_cursor(
                target=user_id,
                resource='media',
                args=args,
                next_cursor=next_cursor)
            data = data.get('data', [])
            for item in data:
                begin_flag, end_flag = True, True

                if "timestamp" in item:
                    timestamp = datetime.datetime.strptime(
                        item['timestamp'][:-5], '%Y-%m-%dT%H:%M:%S')
                    if since_time is not None:
                        begin_flag = since_time < timestamp
                    if until_time is not None:
                        end_flag = until_time > timestamp

                if all([begin_flag, end_flag]):
                    if return_json:
                        medias.append(item)
                    else:
                        medias.append(IgProMedia.new_from_json_dict(item))
                if not begin_flag:
                    next_cursor = None
                    break

            if count is not None:
                if len(medias) >= count:
                    medias = medias[:count]
                    break
            if next_cursor is None:
                break
        return medias
示例#6
0
    def get_hashtag_recent_medias(
            self,
            hashtag_id,  # type: str
            fields=None,  # type: Union[str, List, Tuple, Set]
            count=25,  # type: Optional[int]
            limit=25,  # type: int
            return_json=False,  # type: bool
    ):
        # type: (...) -> List[Union[IgProMedia, dict]]
        """
        Retrieve a list of the most recently published photo and video IG Media objects
        published with a specific hashtag.

        :param hashtag_id: The id for hashtag which you want to retrieve data.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
        :param count: The count for you want to get medias.
                Default is 25.
                If need get all, set this with None.
        :param limit: Each request retrieve comments count from api.
                For medias it should no more than 50.
        :param return_json: Set to false will return a list of instance of IgProMedia.
                Or return json data. Default is false.
        :return: media data list.
        """
        if fields is None:
            fields = constant.INSTAGRAM_HASHTAG_MEDIA_FIELD

        if count is None:
            limit = 50  # Each query will return a maximum of 50 medias.
        else:
            limit = min(count, limit)

        args = {
            "user_id": self.instagram_business_id,
            "fields": enf_comma_separated(field="fields", value=fields),
            "limit": limit,
        }

        medias = []
        next_cursor = None

        while True:
            next_cursor, previous_cursor, data = self.paged_by_cursor(
                target=hashtag_id,
                resource='recent_media',
                args=args,
                next_cursor=next_cursor)
            data = data.get('data', [])

            if return_json:
                medias += data
            else:
                medias += [
                    IgProMedia.new_from_json_dict(item) for item in data
                ]
            if count is not None:
                if len(medias) >= count:
                    medias = medias[:count]
                    break
            if next_cursor is None:
                break
        return medias
示例#7
0
    def get_tagged_user_medias(
            self,
            user_id,  # type: str
            fields=None,  # type: Union[str, List, Tuple, Set]
            count=50,  # type: Optional[int]
            limit=50,  # type: int
            access_token=None,  # type: str
            return_json=False,  # type: bool
    ):
        # type: (...) -> List[Union[IgProMedia, dict]]
        """
        You can use this to retrieve medias which an ig user has been tagged by another ig user.

        Note:
            The private ig media will not be returned.

        :param user_id: Target user id which result medias tagged.
        :param fields: Comma-separated id string for data fields which you want.
                You can also pass this with an id list, tuple, set.
                Default is all public fields.
        :param count: The you want to get medias.
                Default is 50.
                If you want to get all medias. set with None.
        :param limit: Each request retrieve comments count from api.
                Not have a exact value. And default is 50.
        :param access_token: Target user access token. If not will use default access token.
        :param return_json: Set to false will return a list of instance of IgProMedia.
                Or return json data. Default is false.
        :return: medias list
        """
        if fields is None:
            fields = constant.INSTAGRAM_MEDIA_PUBLIC_FIELD.union({
                "comments{{{}}}".format(",".join(
                    constant.INSTAGRAM_COMMENT_FIELD))
            })

        if count is not None:
            limit = min(count, limit)

        args = {
            "fields": enf_comma_separated(field="fields", value=fields),
            "limit": limit,
        }

        if access_token is not None:
            args["access_token"] = access_token

        medias = []
        next_cursor = None

        while True:
            next_cursor, previous_cursor, data = self.paged_by_cursor(
                target=user_id,
                resource="tags",
                args=args,
                next_cursor=next_cursor)
            data = data.get('data', [])

            if return_json:
                medias += data
            else:
                medias += [
                    IgProMedia.new_from_json_dict(item) for item in data
                ]
            if count is not None:
                if len(medias) >= count:
                    medias = medias[:count]
            if next_cursor is None:
                break
        return medias