INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
close socket immediately.
def shutdown(self): """close socket, immediately.""" if self.sock: self.sock.close() self.sock = None self.connected = False
turn on/ off the traceability.
def enableTrace(traceable, handler = logging.StreamHandler()): """ turn on/off the traceability. traceable: boolean value. if set True, traceability is enabled. """ global _traceEnabled _traceEnabled = traceable if traceable: _logger.addHandler(handler) _logger.setLevel(logg...
validate the ABNF frame. skip_utf8_validation: skip utf8 validation.
def validate(self, skip_utf8_validation=False): """ validate the ABNF frame. skip_utf8_validation: skip utf8 validation. """ if self.rsv1 or self.rsv2 or self.rsv3: raise WebSocketProtocolException("rsv is not implemented, yet") if self.opcode not in ABNF.OPC...
create frame to send text binary and other data.
def create_frame(data, opcode, fin=1): """ create frame to send text, binary and other data. data: data to send. This is string value(byte array). if opcode is OPCODE_TEXT and this value is unicode, data value is converted into unicode string, automatically. opc...
format this object to string ( byte array ) to send data to server.
def format(self): """ format this object to string(byte array) to send data to server. """ if any(x not in (0, 1) for x in [self.fin, self.rsv1, self.rsv2, self.rsv3]): raise ValueError("not 0 or 1") if self.opcode not in ABNF.OPCODES: raise ValueError("In...
mask or unmask data. Just do xor for each byte
def mask(mask_key, data): """ mask or unmask data. Just do xor for each byte mask_key: 4 byte string(byte). data: data to mask/unmask. """ if data is None: data = "" if isinstance(mask_key, six.text_type): mask_key = six.b(mask_key) ...
send message. data: message to send. If you set opcode to OPCODE_TEXT data must be utf - 8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT.
def send(self, data, opcode=ABNF.OPCODE_TEXT): """ send message. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ if not self.sock or self.sock.send(da...
close websocket connection.
def close(self, **kwargs): """ close websocket connection. """ self.keep_running = False if self.sock: self.sock.close(**kwargs) self.sock = None
run event loop for WebSocket framework. This loop is infinite loop and is alive during websocket is available. sockopt: values for socket. setsockopt. sockopt must be tuple and each element is argument of sock. setsockopt. sslopt: ssl socket optional dict. ping_interval: automatically send ping command every specified ...
def run_forever(self, sockopt=None, sslopt=None, ping_interval=0, ping_timeout=None, http_proxy_host=None, http_proxy_port=None, http_no_proxy=None, http_proxy_auth=None, skip_utf8_validation=False, host=None, origin=Non...
this functions extracts the code reason from the close body if they exists and if the self. on_close except three arguments
def _get_close_args(self, data): """ this functions extracts the code, reason from the close body if they exists, and if the self.on_close except three arguments """ # if the on_close callback is "old", just return empty list if sys.version_info < (3, 0): if not self.on_close...
GET request.
def get(self, url, headers=None, params=None, stream=False, timeout=None): """GET request. :param str url: Request url :param dict headers: (optional) Request headers :param dict params: (optional) Request query parameter :param bool stream: (optional) get content as stream ...
POST request.
def post(self, url, headers=None, data=None, timeout=None): """POST request. :param str url: Request url :param dict headers: (optional) Request headers :param data: (optional) Dictionary, bytes, or file-like object to send in the body :param timeout: (optional), How long to wai...
Get request body as iterator content ( stream ).
def iter_content(self, chunk_size=1024, decode_unicode=False): """Get request body as iterator content (stream). :param int chunk_size: :param bool decode_unicode: """ return self.response.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode)
Convert to snake case.
def to_snake_case(text): """Convert to snake case. :param str text: :rtype: str :return: """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Convert to camel case.
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
safe_compare_digest method.
def safe_compare_digest(val1, val2): """safe_compare_digest method. :param val1: string or bytes for compare :type val1: str | bytes :param val2: string or bytes for compare :type val2: str | bytes """ if len(val1) != len(val2): return False result = 0 if PY3 and isinstance...
Return dictionary from this object.
def as_json_dict(self): """Return dictionary from this object. :return: dict """ data = {} for key, value in self.__dict__.items(): camel_key = utils.to_camel_case(key) if isinstance(value, (list, tuple, set)): data[camel_key] = list() ...
Create a new instance from a dict.
def new_from_json_dict(cls, data): """Create a new instance from a dict. :param data: JSON dict :rtype: :return: """ new_data = {utils.to_snake_case(key): value for key, value in data.items()} return cls(**new_data)
Get cls object w/ deserialization from json if needed.
def get_or_new_from_json_dict(data, cls): """Get `cls` object w/ deserialization from json if needed. If data is instance of cls, return data. Else if data is instance of dict, create instance from dict. Else, return None. :param data: :param cls: :rtype: object...
Get cls object w/ deserialization from json by using type key hint if needed.
def get_or_new_from_json_dict_with_types( data, cls_map, type_key='type' ): """Get `cls` object w/ deserialization from json by using type key hint if needed. If data is instance of one of cls, return data. Else if data is instance of dict, create instance from dict. Els...
Call reply message API.
def reply_message(self, reply_token, messages, timeout=None): """Call reply message API. https://devdocs.line.me/en/#reply-message Respond to events from users, groups, and rooms. Webhooks are used to notify you when an event occurs. For events that you can respond to, a reply...
Call push message API.
def push_message(self, to, messages, timeout=None): """Call push message API. https://devdocs.line.me/en/#push-message Send messages to users, groups, and rooms at any time. :param str to: ID of the receiver :param messages: Messages. Max: 5 :type messages:...
Call get profile API.
def get_profile(self, user_id, timeout=None): """Call get profile API. https://devdocs.line.me/en/#bot-api-get-profile Get user profile information. :param str user_id: User ID :param timeout: (optional) How long to wait for the server to send data before giving up...
Call get group member profile API.
def get_group_member_profile(self, group_id, user_id, timeout=None): """Call get group member profile API. https://devdocs.line.me/en/#get-group-room-member-profile Gets the user profile of a member of a group that the bot is in. This can be the user ID of a user who has not ad...
Call get room member profile API.
def get_room_member_profile(self, room_id, user_id, timeout=None): """Call get room member profile API. https://devdocs.line.me/en/#get-group-room-member-profile Gets the user profile of a member of a room that the bot is in. This can be the user ID of a user who has not added ...
Call get group member IDs API.
def get_group_member_ids(self, group_id, start=None, timeout=None): """Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as ...
Call get room member IDs API.
def get_room_member_ids(self, room_id, start=None, timeout=None): """Call get room member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a f...
Call get content API.
def get_message_content(self, message_id, timeout=None): """Call get content API. https://devdocs.line.me/en/#get-content Retrieve image, video, and audio data sent by users. :param str message_id: Message ID :param timeout: (optional) How long to wait for the server ...
Call leave group API.
def leave_group(self, group_id, timeout=None): """Call leave group API. https://devdocs.line.me/en/#leave Leave a group. :param str group_id: Group ID :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, ...
Call leave room API.
def leave_room(self, room_id, timeout=None): """Call leave room API. https://devdocs.line.me/en/#leave Leave a room. :param str room_id: Room ID :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (...
Call get rich menu API.
def get_rich_menu(self, rich_menu_id, timeout=None): """Call get rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu :param str rich_menu_id: ID of the rich menu :param timeout: (optional) How long to wait for the server to send data bef...
Call create rich menu API.
def create_rich_menu(self, rich_menu, timeout=None): """Call create rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu :param rich_menu: Inquired to create a rich menu object. :type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu` ...
Call delete rich menu API.
def delete_rich_menu(self, rich_menu_id, timeout=None): """Call delete rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server ...
Call get rich menu ID of user API.
def get_rich_menu_id_of_user(self, user_id, timeout=None): """Call get rich menu ID of user API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-id-of-user :param str user_id: IDs of the user :param timeout: (optional) How long to wait for the server ...
Call link rich menu to user API.
def link_rich_menu_to_user(self, user_id, rich_menu_id, timeout=None): """Call link rich menu to user API. https://developers.line.me/en/docs/messaging-api/reference/#link-rich-menu-to-user :param str user_id: ID of an uploaded rich menu :param str rich_menu_id: ID of the user ...
Call unlink rich menu from user API.
def unlink_rich_menu_from_user(self, user_id, timeout=None): """Call unlink rich menu from user API. https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user :param str user_id: ID of the user :param timeout: (optional) How long to wait for the server ...
Call download rich menu image API.
def get_rich_menu_image(self, rich_menu_id, timeout=None): """Call download rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image :param str rich_menu_id: ID of the rich menu with the image to be downloaded :param timeout: (optional) ...
Call upload rich menu image API.
def set_rich_menu_image(self, rich_menu_id, content_type, content, timeout=None): """Call upload rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image Uploads and attaches an image to a rich menu. :param str rich_menu_id: IDs of the ri...
Call get rich menu list API.
def get_rich_menu_list(self, timeout=None): """Call get rich menu list API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (connect...
Check signature.
def validate(self, body, signature): """Check signature. https://devdocs.line.me/en/#webhook-authentication :param str body: Request body (as text) :param str signature: X-Line-Signature value (as text) :rtype: bool :return: result """ gen_signature = hm...
Parse webhook request body as text.
def parse(self, body, signature): """Parse webhook request body as text. :param str body: Webhook request body (as text) :param str signature: X-Line-Signature value (as text) :rtype: list[T <= :py:class:`linebot.models.events.Event`] :return: """ if not self.sig...
[ Decorator ] Add handler method.
def add(self, event, message=None): """[Decorator] Add handler method. :param event: Specify a kind of Event which you want to handle :type event: T <= :py:class:`linebot.models.events.Event` class :param message: (optional) If event is MessageEvent, specify kind of Messages...
Handle webhook.
def handle(self, body, signature): """Handle webhook. :param str body: Webhook request body (as text) :param str signature: X-Line-Signature value (as text) """ events = self.parser.parse(body, signature) for event in events: func = None key = No...
Get action.
def get_action(action): """Get action.""" action_obj = Base.get_or_new_from_json_dict_with_types( action, { 'postback': PostbackAction, 'message': MessageAction, 'uri': URIAction, 'datetimepicker': DatetimePickerAction, 'camera': CameraAction, ...
Get actions.
def get_actions(actions): """Get actions.""" new_actions = [] if actions: for action in actions: action_obj = get_action(action) if action_obj: new_actions.append(action_obj) return new_actions
Saves a: class: Post: class: Profile or: class: StoryItem to a. json or. json. xz file such that it can later be loaded by: func: load_structure_from_file.
def save_structure_to_file(structure: JsonExportable, filename: str) -> None: """Saves a :class:`Post`, :class:`Profile` or :class:`StoryItem` to a '.json' or '.json.xz' file such that it can later be loaded by :func:`load_structure_from_file`. If the specified filename ends in '.xz', the file will be LZMA...
Loads a: class: Post: class: Profile or: class: StoryItem from a. json or. json. xz file that has been saved by: func: save_structure_to_file.
def load_structure_from_file(context: InstaloaderContext, filename: str) -> JsonExportable: """Loads a :class:`Post`, :class:`Profile` or :class:`StoryItem` from a '.json' or '.json.xz' file that has been saved by :func:`save_structure_to_file`. :param context: :attr:`Instaloader.context` linked to the new...
Create a post object from a given shortcode
def from_shortcode(cls, context: InstaloaderContext, shortcode: str): """Create a post object from a given shortcode""" # pylint:disable=protected-access post = cls(context, {'shortcode': shortcode}) post._node = post._full_metadata return post
Create a post object from a given mediaid
def from_mediaid(cls, context: InstaloaderContext, mediaid: int): """Create a post object from a given mediaid""" return cls.from_shortcode(context, Post.mediaid_to_shortcode(mediaid))
Lookups given fields in _node and if not found in _full_metadata. Raises KeyError if not found anywhere.
def _field(self, *keys) -> Any: """Lookups given fields in _node, and if not found in _full_metadata. Raises KeyError if not found anywhere.""" try: d = self._node for key in keys: d = d[key] return d except KeyError: d = self._full...
: class: Profile instance of the Post s owner.
def owner_profile(self) -> 'Profile': """:class:`Profile` instance of the Post's owner.""" if not self._owner_profile: if 'username' in self._node['owner']: owner_struct = self._node['owner'] else: # Sometimes, the 'owner' structure does not contai...
Timestamp when the post was created ( local time zone ).
def date_local(self) -> datetime: """Timestamp when the post was created (local time zone).""" return datetime.fromtimestamp(self._node["date"] if "date" in self._node else self._node["taken_at_timestamp"])
Timestamp when the post was created ( UTC ).
def date_utc(self) -> datetime: """Timestamp when the post was created (UTC).""" return datetime.utcfromtimestamp(self._node["date"] if "date" in self._node else self._node["taken_at_timestamp"])
Sidecar nodes of a Post with typename == GraphSidecar.
def get_sidecar_nodes(self) -> Iterator[PostSidecarNode]: """Sidecar nodes of a Post with typename==GraphSidecar.""" if self.typename == 'GraphSidecar': for edge in self._field('edge_sidecar_to_children', 'edges'): node = edge['node'] is_video = node['is_video...
Caption.
def caption(self) -> Optional[str]: """Caption.""" if "edge_media_to_caption" in self._node and self._node["edge_media_to_caption"]["edges"]: return self._node["edge_media_to_caption"]["edges"][0]["node"]["text"] elif "caption" in self._node: return self._node["caption"]
List of all lowercased hashtags ( without preceeding # ) that occur in the Post s caption.
def caption_hashtags(self) -> List[str]: """List of all lowercased hashtags (without preceeding #) that occur in the Post's caption.""" if not self.caption: return [] # This regular expression is from jStassen, adjusted to use Python's \w to support Unicode # http://blog.jsta...
List of all lowercased profiles that are mentioned in the Post s caption without preceeding
def caption_mentions(self) -> List[str]: """List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.""" if not self.caption: return [] # This regular expression is from jStassen, adjusted to use Python's \w to support Unicode # http://bl...
List of all lowercased users that are tagged in the Post.
def tagged_users(self) -> List[str]: """List of all lowercased users that are tagged in the Post.""" try: return [edge['node']['user']['username'].lower() for edge in self._field('edge_media_to_tagged_user', ...
Whether the viewer has liked the post or None if not logged in.
def viewer_has_liked(self) -> Optional[bool]: """Whether the viewer has liked the post, or None if not logged in.""" if not self._context.is_logged_in: return None if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']: return self._node['likes']['viewer_h...
r Iterate over all comments of the post.
def get_comments(self) -> Iterator[PostComment]: r"""Iterate over all comments of the post. Each comment is represented by a PostComment namedtuple with fields text (string), created_at (datetime), id (int), owner (:class:`Profile`) and answers (:class:`~typing.Iterator`\ [:class:`PostCommentAn...
Iterate over all likes of the post. A: class: Profile instance of each likee is yielded.
def get_likes(self) -> Iterator['Profile']: """Iterate over all likes of the post. A :class:`Profile` instance of each likee is yielded.""" if self.likes == 0: # Avoid doing additional requests if there are no comments return likes_edges = self._field('edge_media_preview_...
If the Post has a location returns PostLocation namedtuple with fields id lat and lng and name.
def location(self) -> Optional[PostLocation]: """If the Post has a location, returns PostLocation namedtuple with fields 'id', 'lat' and 'lng' and 'name'.""" loc = self._field("location") if self._location or not loc: return self._location location_id = int(loc['id']) ...
Create a Profile instance from a given username raise exception if it does not exist.
def from_username(cls, context: InstaloaderContext, username: str): """Create a Profile instance from a given username, raise exception if it does not exist. See also :meth:`Instaloader.check_profile_id`. :param context: :attr:`Instaloader.context` :param username: Username :ra...
Create a Profile instance from a given userid. If possible use: meth: Profile. from_username or constructor directly rather than this method since it requires more requests.
def from_id(cls, context: InstaloaderContext, profile_id: int): """Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username` or constructor directly rather than this method, since it requires more requests. :param context: :attr:`Instaloader.context` ...
Return URL of profile picture. If logged in the HD version is returned otherwise a lower - quality version.
def profile_pic_url(self) -> str: """Return URL of profile picture. If logged in, the HD version is returned, otherwise a lower-quality version. .. versionadded:: 4.0.3 .. versionchanged:: 4.2.1 Require being logged in for HD version (as required by Instagram).""" if self._c...
Retrieve all posts from a profile.
def get_posts(self) -> Iterator[Post]: """Retrieve all posts from a profile.""" self._obtain_metadata() yield from (Post(self._context, node, self) for node in self._context.graphql_node_list("472f257a40c653c64c666ce877d59d2b", ...
Retrieve all posts where a profile is tagged.
def get_tagged_posts(self) -> Iterator[Post]: """Retrieve all posts where a profile is tagged. .. versionadded:: 4.0.7""" self._obtain_metadata() yield from (Post(self._context, node, self if int(node['owner']['id']) == self.userid else None) for node in self._contex...
Retrieve list of followers of given profile. To use this one needs to be logged in and private profiles has to be followed.
def get_followers(self) -> Iterator['Profile']: """ Retrieve list of followers of given profile. To use this, one needs to be logged in and private profiles has to be followed. """ if not self._context.is_logged_in: raise LoginRequiredException("--login required to ge...
: class: Profile instance of the story item s owner.
def owner_profile(self) -> Profile: """:class:`Profile` instance of the story item's owner.""" if not self._owner_profile: self._owner_profile = Profile.from_id(self._context, self._node['owner']['id']) return self._owner_profile
This ID only equals amongst: class: Story instances which have the same owner and the same set of: class: StoryItem. For all other: class: Story instances this ID is different.
def unique_id(self) -> str: """ This ID only equals amongst :class:`Story` instances which have the same owner and the same set of :class:`StoryItem`. For all other :class:`Story` instances this ID is different. """ if not self._unique_id: id_list = [item.mediaid for ...
Timestamp when the story has last been watched or None ( local time zone ).
def last_seen_local(self) -> Optional[datetime]: """Timestamp when the story has last been watched or None (local time zone).""" if self._node['seen']: return datetime.fromtimestamp(self._node['seen'])
Timestamp when the story has last been watched or None ( UTC ).
def last_seen_utc(self) -> Optional[datetime]: """Timestamp when the story has last been watched or None (UTC).""" if self._node['seen']: return datetime.utcfromtimestamp(self._node['seen'])
Retrieve all items from a story.
def get_items(self) -> Iterator[StoryItem]: """Retrieve all items from a story.""" yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items']))
Retrieve all associated highlight items.
def get_items(self) -> Iterator[StoryItem]: """Retrieve all associated highlight items.""" self._fetch_items() yield from (StoryItem(self._context, item, self.owner_profile) for item in self._items)
Duplicates a requests. Session.
def copy_session(session: requests.Session) -> requests.Session: """Duplicates a requests.Session.""" new = requests.Session() new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies)) new.headers = session.headers.copy() return new
Log a message to stdout that can be suppressed with -- quiet.
def log(self, *msg, sep='', end='\n', flush=False): """Log a message to stdout that can be suppressed with --quiet.""" if not self.quiet: print(*msg, sep=sep, end=end, flush=flush)
Log a non - fatal error message to stderr which is repeated at program termination.
def error(self, msg, repeat_at_end=True): """Log a non-fatal error message to stderr, which is repeated at program termination. :param msg: Message to be printed. :param repeat_at_end: Set to false if the message should be printed, but not repeated at program termination.""" print(msg, ...
Print error log and close session
def close(self): """Print error log and close session""" if self.error_log and not self.quiet: print("\nErrors occured:", file=sys.stderr) for err in self.error_log: print(err, file=sys.stderr) self._session.close()
Context manager to catch print and record InstaloaderExceptions.
def error_catcher(self, extra_info: Optional[str] = None): """ Context manager to catch, print and record InstaloaderExceptions. :param extra_info: String to prefix error message with.""" try: yield except InstaloaderException as err: if extra_info: ...
Returns default HTTP header we use for requests.
def _default_http_header(self, empty_session_only: bool = False) -> Dict[str, str]: """Returns default HTTP header we use for requests.""" header = {'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive', ...
Returns our default anonymous requests. Session object.
def get_anonymous_session(self) -> requests.Session: """Returns our default anonymous requests.Session object.""" session = requests.Session() session.cookies.update({'sessionid': '', 'mid': '', 'ig_pr': '1', 'ig_vw': '1920', 'csrftoken': '', ...
Not meant to be used directly use: meth: Instaloader. save_session_to_file.
def save_session_to_file(self, sessionfile): """Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.""" pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)
Not meant to be used directly use: meth: Instaloader. load_session_from_file.
def load_session_from_file(self, username, sessionfile): """Not meant to be used directly, use :meth:`Instaloader.load_session_from_file`.""" session = requests.Session() session.cookies = requests.utils.cookiejar_from_dict(pickle.load(sessionfile)) session.headers.update(self._default_h...
Not meant to be used directly use: meth: Instaloader. login.
def login(self, user, passwd): """Not meant to be used directly, use :meth:`Instaloader.login`. :raises InvalidArgumentException: If the provided username does not exist. :raises BadCredentialsException: If the provided password is wrong. :raises ConnectionException: If connection to In...
Second step of login if 2FA is enabled. Not meant to be used directly use: meth: Instaloader. two_factor_login.
def two_factor_login(self, two_factor_code): """Second step of login if 2FA is enabled. Not meant to be used directly, use :meth:`Instaloader.two_factor_login`. :raises InvalidArgumentException: No two-factor authentication pending. :raises BadCredentialsException: 2FA verification code...
Output the number of GraphQL queries grouped by their query_hash within the last time.
def _dump_query_timestamps(self, current_time: float): """Output the number of GraphQL queries grouped by their query_hash within the last time.""" windows = [10, 11, 15, 20, 30, 60] print("GraphQL requests:", file=sys.stderr) for query_hash, times in self._graphql_query_timestamps.items...
Return how many GraphQL requests can be done within the sliding window.
def _graphql_request_count_per_sliding_window(self, query_hash: str) -> int: """Return how many GraphQL requests can be done within the sliding window.""" if self.is_logged_in: max_reqs = {'1cb6ec562846122743b61e492c85999f': 20, '33ba35852cb50da46f5b5e889df7d159': 20} else: ...
Calculate time needed to wait before GraphQL query can be executed.
def _graphql_query_waittime(self, query_hash: str, current_time: float, untracked_queries: bool = False) -> int: """Calculate time needed to wait before GraphQL query can be executed.""" sliding_window = 660 if query_hash not in self._graphql_query_timestamps: self._graphql_query_tim...
Called before a GraphQL query is made in order to stay within Instagram s rate limits.
def _ratecontrol_graphql_query(self, query_hash: str, untracked_queries: bool = False): """Called before a GraphQL query is made in order to stay within Instagram's rate limits. :param query_hash: The query_hash parameter of the query. :param untracked_queries: True, if 429 has been returned to...
JSON request to Instagram.
def get_json(self, path: str, params: Dict[str, Any], host: str = 'www.instagram.com', session: Optional[requests.Session] = None, _attempt=1) -> Dict[str, Any]: """JSON request to Instagram. :param path: URL, relative to the given domain which defaults to www.instagram.com/ :p...
Do a GraphQL Query.
def graphql_query(self, query_hash: str, variables: Dict[str, Any], referer: Optional[str] = None, rhx_gis: Optional[str] = None) -> Dict[str, Any]: """ Do a GraphQL Query. :param query_hash: Query identifying hash. :param variables: Variables for the Query. ...
Retrieve a list of GraphQL nodes.
def graphql_node_list(self, query_hash: str, query_variables: Dict[str, Any], query_referer: Optional[str], edge_extractor: Callable[[Dict[str, Any]], Dict[str, Any]], rhx_gis: Optional[str] = None, first_data: Optio...
JSON request to i. instagram. com.
def get_iphone_json(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]: """JSON request to ``i.instagram.com``. :param path: URL, relative to ``i.instagram.com/`` :param params: GET parameters :return: Decoded response dictionary :raises QueryReturnedBadRequestException:...
Write raw response data into a file.
def write_raw(self, resp: Union[bytes, requests.Response], filename: str) -> None: """Write raw response data into a file. .. versionadded:: 4.2.1""" self.log(filename, end=' ', flush=True) with open(filename, 'wb') as file: if isinstance(resp, requests.Response): ...
Downloads a file anonymously.
def get_raw(self, url: str, _attempt=1) -> requests.Response: """Downloads a file anonymously. :raises QueryReturnedNotFoundException: When the server responds with a 404. :raises QueryReturnedForbiddenException: When the server responds with a 403. :raises ConnectionException: When dow...
Downloads and writes anonymously - requested raw data into a file.
def get_and_write_raw(self, url: str, filename: str) -> None: """Downloads and writes anonymously-requested raw data into a file. :raises QueryReturnedNotFoundException: When the server responds with a 404. :raises QueryReturnedForbiddenException: When the server responds with a 403. :r...
rhx_gis string returned in the/ query.
def root_rhx_gis(self) -> Optional[str]: """rhx_gis string returned in the / query.""" if self.is_logged_in: # At the moment, rhx_gis seems to be required for anonymous requests only. By returning None when logged # in, we can save the root_rhx_gis lookup query. retur...
Returns default session filename for given username.
def get_default_session_filename(username: str) -> str: """Returns default session filename for given username.""" dirname = tempfile.gettempdir() + "/" + ".instaloader-" + getpass.getuser() filename = dirname + "/" + "session-" + username return filename.lower()
Decorator to raise an exception if herewith - decorated function is called without being logged in
def _requires_login(func: Callable) -> Callable: """Decorator to raise an exception if herewith-decorated function is called without being logged in""" @wraps(func) def call(instaloader, *args, **kwargs): if not instaloader.context.is_logged_in: raise LoginRequiredException("--login=USER...
Decorator to retry the function max_connection_attemps number of times.
def _retry_on_connection_error(func: Callable) -> Callable: """Decorator to retry the function max_connection_attemps number of times. Herewith-decorated functions need an ``_attempt`` keyword argument. This is to decorate functions that do network requests that may fail. Note that :meth:`.get_json`, ...