def search_username(client: ApiClient, username, count: int) -> List[dict]: username = se.Username(q=username, count=count) resp = client.search_username(username) return resp.json()['users']
import os from instauto.api.client import ApiClient from instauto.api.actions import post as ps if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') post = ps.PostStory(path='./test_story.jpg', ) resp = client.post_post(post, 80) print("Success: ", resp.ok)
class Bot: stop: bool = False input: Input _actions: List = [] _post_cache: Dict[str, List[Dict]] = {} def __init__(self, user_name: str, password: str, client: ApiClient = None, delay_between_action: float = 2.0, delay_variance: float = 0.0) -> None: """Initiate a new `Bot` instance. Args: user_name: the username of the account password: the password of the account client: the `ApiClient` instance the Bot communicates with. If given, it will take precedence over credentials. delay_between_action: the amount of seconds to wait between actions (each like, follow, etc. is an action) delay_variance: the amount of variance to add to the delay. Delay will be random number between (delay - variance) - (delay + variance). """ if (client is not None): self._client = client else: self._initialize_client_from_credentials(user_name, password) self.input = Input(self._client) self._actions = [] self._delay = delay_between_action if (delay_between_action) else 0 self._delay_variance = abs(delay_variance) def _initialize_client_from_credentials(self, user_name: str, password: str) -> None: instauto_save_path = f'.{user_name}.instauto.save' if os.path.isfile(instauto_save_path): self._client = ApiClient.initiate_from_file(instauto_save_path) else: self._client = ApiClient(user_name=user_name, password=password) self._client.login() self._client.save_to_disk(instauto_save_path) def like(self, chance: int, amount: int) -> "Bot": """Like posts of users retrieved with the Input pipeline. Args: chance: integer between 0 and 100, represents a percentage between 0 and 100%. Defines the chance of this action being called for an account. Set to 25 to call on 1/4 of all accounts, 50 for 1/2 of all accounts, etc. amount: The amount of posts to like, if this action is being called for an account. """ self._actions.append({ 'func': like_post, 'chance': chance, 'amount': amount, 'args': ('POST_ID', ) }) return self def comment(self, chance: int, amount: int, comments: List[str]) -> "Bot": """Comment on posts of users retrieved with the Input pipeline. Args: chance: integer between 0 and 100, represents a percentage between 0 and 100%. Defines the chance of this action being called for an account. Set to 25 to call on 1/4 of all accounts, 50 for 1/2 of all accounts, etc. amount: The amount of posts to comment on, if this action is being called for an account. comments: A random selected entry out of this list will be used as text to comment. """ self._actions.append({ 'func': comment_post, 'chance': chance, 'amount': amount, 'args': ('POST_ID', (random.choice, comments)) }) return self def follow(self, chance: int) -> "Bot": """Follow users retrieved with the Input pipeline. Args: chance: integer between 0 and 100, represents a percentage between 0 and 100%. Defines the chance of this action being called for an account. Set to 25 to call on 1/4 of all accounts, 50 for 1/2 of all accounts, etc. """ self._actions.append({ 'func': follow_user, 'chance': chance, 'args': ('ACCOUNT_ID', ) }) return self def start(self): """Start the bot. Once the bot is started, it will run until it went through all retrieved accounts, or if the `stop` attribute is set to `True`.""" accounts = self.input.filtered_accounts while not self.stop: self._sleep_between_actions() account = accounts.pop(random.randint(0, len(accounts) - 1)) for action in self._actions: if random.randint(0, 100) > action['chance']: continue t = action['args'][0] if t == 'POST_ID': posts = self._get_posts(account['username']) for _ in range(action['amount']): if not posts: continue post = posts.pop(random.randint(0, len(posts) - 1)) args = self._resolve_args(action['args'], post=post) try: action['func'](self._client, *args) except Exception as e: logger.warning("Caught exception: ", e) elif t == 'ACCOUNT_ID': args = self._resolve_args(action['args'], account=account) try: action['func'](self._client, *args) except Exception as e: logger.warning("Caught exception: ", e) def _sleep_between_actions(self): min = (self._delay - self._delay_variance) if (self._delay - self._delay_variance) else 0 max = self._delay + self._delay_variance sleeptime = round(random.uniform(min, max), 2) sleep(sleeptime) def _get_posts(self, account_name: str, force: bool = False) -> List[Dict]: if account_name not in self._post_cache or force: try: self._post_cache[account_name] = retrieve_posts_from_user( self._client, 30, account_name) except AuthorizationError: logger.info( f"Can't retrieve posts from {account_name}. This is a private account." ) return self._post_cache.get(account_name) @staticmethod def _resolve_args(args: Tuple, post: Dict = None, account: Dict = None) -> List: a = list() for arg in args: if isinstance(arg, tuple) and callable(arg[0]): a.append(arg[0](*arg[1::])) else: a.append(arg) for i, arg in enumerate(a.copy()): if arg == 'POST_ID' and post is not None: a[i] = post['pk'] elif arg == 'ACCOUNT_ID' and account is not None: a[i] = account['pk'] return a @classmethod def from_client(cls, client: ApiClient, delay_between_action: float = 2.0, delay_variance: float = 0.0) -> "Bot": return cls("", "", client=client, delay_between_action=delay_between_action, delay_variance=delay_variance)
def test_login(self): client = ApiClient(user_name=os.environ['INSTAUTO_TESTS_USER_NAME'], password=os.environ['INSTAUTO_TESTS_PASSWORD']) client.login() self.assertIsNotNone(client.state.logged_in_account_data)
import os from instauto.api.client import ApiClient from instauto.api.actions.structs.direct import DirectPhoto from instauto.api.actions.structs.post import PostFeed as PhotoUpload if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(user_name=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.login() client.save_to_disk('./.instauto.save') # upload photo ph = PhotoUpload(path="/tmp/test.jpg", caption="") response = client._upload_image(ph, quality=70) upload_id = response['upload_id'] # send photo userid = "" # recipient of photo dp = DirectPhoto(upload_id=upload_id, recipients=[[userid]]) client.direct_send(dp)
def search_tags(client: ApiClient, tag: str, limit: int) -> List[dict]: s = se.Tag(tag, limit) resp: dict = client.search_tag(s).json() return resp['results']
import os import json from instauto.api.client import ApiClient if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(user_name=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.login() client.save_to_disk('./.instauto.save') # get inbox inbox = client.direct_inbox().json() print(json.dumps(inbox, indent=4)) # get latest thread latest_thread_id = inbox['inbox']['threads'][0]['thread_id'] thread = client.direct_thread(latest_thread_id).json() print(json.dumps(thread, indent=4))
import os from instauto.api.client import ApiClient if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "yourusername", password=os.environ.get("INSTAUTO_PASSWORD") or "yourpassword") client.log_in() client.save_to_disk("./.instauto.save") retrieved_data = client.post_get_likers("1770154859660826272") print(retrieved_data)
import os from instauto.api.client import ApiClient from instauto.api.actions import profile as pr from instauto.api import structs as st if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(user_name=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.login() client.save_to_disk('./.instauto.save') # FOR CUSTOM GENDER # p = ProfileSetGender.create( # gender=WhichGender.other, # custom_gender="Blue whale" # ) # FOR MALE / FEMALE / PREFER NOT TO SAY p = pr.SetGender.create(gender=st.WhichGender.male, ) client.profile_set_gender(p)
def test_Info(self): client = ApiClient(testing=True) s = pf.Info(1358549127) s.fill(client)
def test_setGender(self): client = ApiClient(testing=True) s = pf.SetGender("male") s.fill(client)
def test_setBiography(self): client = ApiClient(testing=True) s = pf.SetBiography("I am here") s.fill(client)
def test_media_likers(self): client = ApiClient(testing=True) s = ps.RetrieveLikers() s.fill(client) helper(s, self)
def test_media_commenters(self): client = ApiClient(testing=True) s = ps.RetrieveCommenters("test") s.fill(client) helper(s, self)
from instauto.api.client import ApiClient # There are multiple ways to authenticate in instauto, the first one, # is by creating a new session client = ApiClient(username="******", password="******") client.log_in() # This is simple and fast, but doing this too often, will get your account flagged. # That's why, instauto also supports saving sessions. client.save_to_disk('.instauto.save') # The above statement will save all important information that is necessary # for reconstructing your session. To reconstruct your session, you can # call the `initiate_from_file` class method. client = ApiClient.initiate_from_file('.instauto.save') # That covers simple authentication, but what if you have 2FA enabled? No worries, # that is also supported: def get_2fa_code(username: str) -> str: # do something that'll retrieve a valid 2fa code here return str(random.randint(100000, 999999)) client = ApiClient(username="******", password="******", _2fa_function=get_2fa_code) # Too much work to implement the `get_2fa_code` function? If it's not provided, instauto # will prompt you for a 2fa code in the terminal before it continues. # More information about authentication? Check out the authentication
def test_username(self): client = ApiClient(testing=True) s = sr.Username("test",1) s.fill(client)
import os from time import sleep import random from instauto.api.client import ApiClient from instauto.api.actions import friendships as fs from instauto.api.actions import search as se if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') s = se.Username("instagram", 1) resp = client.search_username(s).json() user_id = resp['users'][0]['pk'] f = fs.GetFollowing(user_id) obj, result = client.following_get(f) # grabs the first page while result: # paginate until all users are extracted parsed = result.json() print(f"Extracted {len(parsed['users'])} users following") print(f"The username of the first extracted user following is {parsed['users'][0]['username']}") obj, result = client.following_get(obj) sleep(random.randint(10, 60))
def test_tag(self): client = ApiClient(testing=True) s = sr.Tag('test',1) s.fill(client)
import os from instauto.api.client import ApiClient from instauto.api.actions import search as se from instauto.api.actions import friendships as fs if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') s = se.Username.create("stan058_", 1) resp = client.search_username(s).json() user_id = resp['users'][0]['pk'] a = fs.ApproveRequest(user_id) resp = client.follow_request_approve(a)
import os from instauto.api.client import ApiClient if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') client.change_password("new_password", "old_password")
def test_w_auth_details(self): ApiClient(user_name="test_username", password="******") ApiClient(state=DEFAULT_STATE_I, session_cookies={'test': 1})
import os from instauto.api.client import ApiClient from instauto.api.actions import friendships as fs if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') f = fs.Remove(user_id="38720650610") client.follower_remove(f)
def test_refresh_session(self): client = ApiClient(testing=True) now = client.state.session_id[::-1] client._refresh_session() self.assertNotEqual(now, client.state.session_id[::-1])
import os from instauto.api.client import ApiClient import instauto.api.actions.post as ps if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(user_name=os.environ.get("INSTAUTO_USER") or "username", password=os.environ.get("INSTAUTO_PASS") or "password") client.login() client.save_to_disk('./.instauto.save') p = ps.RetrieveCommenters client.post_get_commenters('1770154859660826272')
import os from instauto.api.client import ApiClient from instauto.api.actions.structs.profile import Info if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') # get user info by username i_uname = Info(username="") info_username = client.profile_info(i_uname) print(info_username) # get user info by user id i_id = Info(user_id=0) info_id = client.profile_info(i_id) print(info_id)
import os from instauto.api.client import ApiClient from instauto.api.actions import post as ps from instauto.api.actions import search as se if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username=os.environ.get("INSTAUTO_USER") or "your_username", password=os.environ.get("INSTAUTO_PASS") or "your_password") client.log_in() client.save_to_disk('./.instauto.save') s = se.Tag('instagram', 1) resp = client.search_tag(s).json() results = resp['results'][0] tag_name = results['name'] rbt = ps.RetrieveByTag(tag_name) obj, result = client.post_retrieve_by_tag(rbt) retrieved_items = [] # retrieve the first 20 posts while result and len(retrieved_items) < 20: retrieved_items.extend(result) obj, result = client.post_retrieve_by_tag(obj) print(f"Retrieved {len(result)} new posts!") print(f"Retrieved a total of {len(retrieved_items)} posts!")
from instauto.api.client import ApiClient from instauto.helpers.post import like_post client = ApiClient.initiate_from_file('.instauto.save') like_post(client, "media_id")
import os from instauto.api.client import ApiClient from instauto.api.actions.structs import friendships as fs if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(username="******", password="******") client.log_in() client.save_to_disk('./.instauto.save') p = fs.PendingRequests() users = client.follow_requests_get(p) for user in users: # approves all requests a = fs.ApproveRequest(str(user['pk'])) resp = client.follow_request_approve(a)
def test_1(self): """Test `_create_jazoest` produces the correct value""" client = ApiClient(testing=True) client.state.phone_id = "24db86d8-9946-4892-8556-63411c5cb5e8" self.assertEqual(client._create_jazoest(), '22211')
def test_get_post_likers(self): client = ApiClient(testing=True) s = ps.RetrieveLikers(media_id="test") s.fill(client) helper(s, self)