Advertisement
Guest User

Untitled

a guest
Oct 20th, 2017
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.34 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import atexit
  5. import datetime
  6. import itertools
  7. import json
  8. import logging
  9. import random
  10. import signal
  11. import sys
  12.  
  13. if 'threading' in sys.modules:
  14. del sys.modules['threading']
  15. import time
  16. import requests
  17. from unfollow_protocol import unfollow_protocol
  18. from userinfo import UserInfo
  19.  
  20.  
  21. class InstaBot:
  22. """
  23. Instagram bot v 1.1.0
  24. like_per_day=1000 - How many likes set bot in one day.
  25.  
  26. media_max_like=0 - Don't like media (photo or video) if it have more than
  27. media_max_like likes.
  28.  
  29. media_min_like=0 - Don't like media (photo or video) if it have less than
  30. media_min_like likes.
  31.  
  32. tag_list = ['cat', 'car', 'dog'] - Tag list to like.
  33.  
  34. max_like_for_one_tag=5 - Like 1 to max_like_for_one_tag times by row.
  35.  
  36. log_mod = 0 - Log mod: log_mod = 0 log to console, log_mod = 1 log to file,
  37. log_mod = 2 no log.
  38.  
  39. https://github.com/LevPasha/instabot.py
  40. """
  41.  
  42. url = 'https://www.instagram.com/'
  43. url_tag = 'https://www.instagram.com/explore/tags/%s/?__a=1'
  44. url_likes = 'https://www.instagram.com/web/likes/%s/like/'
  45. url_unlike = 'https://www.instagram.com/web/likes/%s/unlike/'
  46. url_comment = 'https://www.instagram.com/web/comments/%s/add/'
  47. url_follow = 'https://www.instagram.com/web/friendships/%s/follow/'
  48. url_unfollow = 'https://www.instagram.com/web/friendships/%s/unfollow/'
  49. url_login = 'https://www.instagram.com/accounts/login/ajax/'
  50. url_logout = 'https://www.instagram.com/accounts/logout/'
  51. url_media_detail = 'https://www.instagram.com/p/%s/?__a=1'
  52. url_user_detail = 'https://www.instagram.com/%s/?__a=1'
  53.  
  54. user_agent = ("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
  55. "(KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36")
  56. accept_language = 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4'
  57.  
  58. # If instagram ban you - query return 400 error.
  59. error_400 = 0
  60. # If you have 3 400 error in row - looks like you banned.
  61. error_400_to_ban = 3
  62. # If InstaBot think you are banned - going to sleep.
  63. ban_sleep_time = 2 * 60 * 60
  64.  
  65. # All counter.
  66. bot_mode = 0
  67. like_counter = 0
  68. follow_counter = 0
  69. unfollow_counter = 0
  70. comments_counter = 0
  71. current_user = 'hajka'
  72. current_index = 0
  73. current_id = 'abcds'
  74. # List of user_id, that bot follow
  75. bot_follow_list = []
  76. user_info_list = []
  77. user_list = []
  78. ex_user_list = []
  79. unwanted_username_list = []
  80. is_checked = False
  81. is_selebgram = False
  82. is_fake_account = False
  83. is_active_user = False
  84. is_following = False
  85. is_follower = False
  86. is_rejected = False
  87. is_self_checking = False
  88. is_by_tag = False
  89. is_follower_number = 0
  90.  
  91. self_following = 0
  92. self_follower = 0
  93.  
  94. # Log setting.
  95. log_file_path = ''
  96. log_file = 0
  97.  
  98. # Other.
  99. user_id = 0
  100. media_by_tag = 0
  101. media_on_feed = []
  102. media_by_user = []
  103. login_status = False
  104.  
  105. # For new_auto_mod
  106. next_iteration = {"Like": 0, "Follow": 0, "Unfollow": 0, "Comments": 0}
  107.  
  108. def __init__(self,
  109. login,
  110. password,
  111. like_per_day=1000,
  112. media_max_like=50,
  113. media_min_like=0,
  114. follow_per_day=0,
  115. follow_time=5 * 60 * 60,
  116. unfollow_per_day=0,
  117. comment_list=[["this", "the", "your"],
  118. ["photo", "picture", "pic", "shot", "snapshot"],
  119. ["is", "looks", "feels", "is really"],
  120. ["great", "super", "good", "very good", "good",
  121. "wow", "WOW", "cool", "GREAT", "magnificent",
  122. "magical", "very cool", "stylish", "beautiful",
  123. "so beautiful", "so stylish", "so professional",
  124. "lovely", "so lovely", "very lovely", "glorious",
  125. "so glorious", "very glorious", "adorable",
  126. "excellent", "amazing"],[".", "..", "...", "!",
  127. "!!", "!!!"]],
  128. comments_per_day=0,
  129. tag_list=['cat', 'car', 'dog'],
  130. max_like_for_one_tag=5,
  131. unfollow_break_min=15,
  132. unfollow_break_max=30,
  133. log_mod=0,
  134. proxy="",
  135. user_blacklist={},
  136. tag_blacklist=[],
  137. unwanted_username_list=[],
  138. unfollow_whitelist=[]):
  139.  
  140. self.bot_start = datetime.datetime.now()
  141. self.unfollow_break_min = unfollow_break_min
  142. self.unfollow_break_max = unfollow_break_max
  143. self.user_blacklist = user_blacklist
  144. self.tag_blacklist = tag_blacklist
  145. self.unfollow_whitelist = unfollow_whitelist
  146. self.comment_list = comment_list
  147.  
  148. self.time_in_day = 24 * 60 * 60
  149. # Like
  150. self.like_per_day = like_per_day
  151. if self.like_per_day != 0:
  152. self.like_delay = self.time_in_day / self.like_per_day
  153.  
  154. # Follow
  155. self.follow_time = follow_time
  156. self.follow_per_day = follow_per_day
  157. if self.follow_per_day != 0:
  158. self.follow_delay = self.time_in_day / self.follow_per_day
  159.  
  160. # Unfollow
  161. self.unfollow_per_day = unfollow_per_day
  162. if self.unfollow_per_day != 0:
  163. self.unfollow_delay = self.time_in_day / self.unfollow_per_day
  164.  
  165. # Comment
  166. self.comments_per_day = comments_per_day
  167. if self.comments_per_day != 0:
  168. self.comments_delay = self.time_in_day / self.comments_per_day
  169.  
  170. # Don't like if media have more than n likes.
  171. self.media_max_like = media_max_like
  172. # Don't like if media have less than n likes.
  173. self.media_min_like = media_min_like
  174. # Auto mod seting:
  175. # Default list of tag.
  176. self.tag_list = tag_list
  177. # Get random tag, from tag_list, and like (1 to n) times.
  178. self.max_like_for_one_tag = max_like_for_one_tag
  179. # log_mod 0 to console, 1 to file
  180. self.log_mod = log_mod
  181. self.s = requests.Session()
  182. # if you need proxy make something like this:
  183. # self.s.proxies = {"https" : "http://proxyip:proxyport"}
  184. # by @ageorgios
  185. if proxy != "":
  186. proxies = {
  187. 'http': 'http://' + proxy,
  188. 'https': 'http://' + proxy,
  189. }
  190. self.s.proxies.update(proxies)
  191. # convert login to lower
  192. self.user_login = login.lower()
  193. self.user_password = password
  194. self.bot_mode = 0
  195. self.media_by_tag = []
  196. self.media_on_feed = []
  197. self.media_by_user = []
  198. self.unwanted_username_list = unwanted_username_list
  199. now_time = datetime.datetime.now()
  200. log_string = 'Instabot v1.1.0 started at %s:\n' % \
  201. (now_time.strftime("%d.%m.%Y %H:%M"))
  202. self.write_log(log_string)
  203. self.login()
  204. self.populate_user_blacklist()
  205. signal.signal(signal.SIGTERM, self.cleanup)
  206. atexit.register(self.cleanup)
  207.  
  208. def populate_user_blacklist(self):
  209. for user in self.user_blacklist:
  210. user_id_url = self.url_user_detail % (user)
  211. info = self.s.get(user_id_url)
  212.  
  213. # prevent error if 'Account of user was deleted or link is invalid
  214. from json import JSONDecodeError
  215. try:
  216. all_data = json.loads(info.text)
  217. except JSONDecodeError as e:
  218. self.write_log('Account of user %s was deleted or link is '
  219. 'invalid' % (user))
  220. else:
  221. # prevent exception if user have no media
  222. id_user = all_data['user']['id']
  223. # Update the user_name with the user_id
  224. self.user_blacklist[user] = id_user
  225. log_string = "Blacklisted user %s added with ID: %s" % (user,
  226. id_user)
  227. self.write_log(log_string)
  228. time.sleep(5 * random.random())
  229.  
  230. def login(self):
  231. log_string = 'Trying to login as %s...\n' % (self.user_login)
  232. self.write_log(log_string)
  233. self.s.cookies.update({
  234. 'sessionid': '',
  235. 'mid': '',
  236. 'ig_pr': '1',
  237. 'ig_vw': '1920',
  238. 'csrftoken': '',
  239. 's_network': '',
  240. 'ds_user_id': ''
  241. })
  242. self.login_post = {
  243. 'username': self.user_login,
  244. 'password': self.user_password
  245. }
  246. self.s.headers.update({
  247. 'Accept-Encoding': 'gzip, deflate',
  248. 'Accept-Language': self.accept_language,
  249. 'Connection': 'keep-alive',
  250. 'Content-Length': '0',
  251. 'Host': 'www.instagram.com',
  252. 'Origin': 'https://www.instagram.com',
  253. 'Referer': 'https://www.instagram.com/',
  254. 'User-Agent': self.user_agent,
  255. 'X-Instagram-AJAX': '1',
  256. 'X-Requested-With': 'XMLHttpRequest'
  257. })
  258. r = self.s.get(self.url)
  259. self.s.headers.update({'X-CSRFToken': r.cookies['csrftoken']})
  260. time.sleep(5 * random.random())
  261. login = self.s.post(
  262. self.url_login, data=self.login_post, allow_redirects=True)
  263. self.s.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
  264. self.csrftoken = login.cookies['csrftoken']
  265. time.sleep(5 * random.random())
  266.  
  267. if login.status_code == 200:
  268. r = self.s.get('https://www.instagram.com/')
  269. finder = r.text.find(self.user_login)
  270. if finder != -1:
  271. ui = UserInfo()
  272. self.user_id = ui.get_user_id_by_login(self.user_login)
  273. self.login_status = True
  274. log_string = '%s login success!' % (self.user_login)
  275. self.write_log(log_string)
  276. else:
  277. self.login_status = False
  278. self.write_log('Login error! Check your login data!')
  279. else:
  280. self.write_log('Login error! Connection error!')
  281.  
  282. def logout(self):
  283. now_time = datetime.datetime.now()
  284. log_string = 'Logout: likes - %i, follow - %i, unfollow - %i, comments - %i.' % \
  285. (self.like_counter, self.follow_counter,
  286. self.unfollow_counter, self.comments_counter)
  287. self.write_log(log_string)
  288. work_time = datetime.datetime.now() - self.bot_start
  289. log_string = 'Bot work time: %s' % (work_time)
  290. self.write_log(log_string)
  291.  
  292. try:
  293. logout_post = {'csrfmiddlewaretoken': self.csrftoken}
  294. logout = self.s.post(self.url_logout, data=logout_post)
  295. self.write_log("Logout success!")
  296. self.login_status = False
  297. except:
  298. self.write_log("Logout error!")
  299.  
  300. def cleanup(self, *_):
  301. # Unfollow all bot follow
  302. if self.follow_counter >= self.unfollow_counter:
  303. for f in self.bot_follow_list:
  304. log_string = "Trying to unfollow: %s" % (f[0])
  305. self.write_log(log_string)
  306. self.unfollow_on_cleanup(f[0])
  307. sleeptime = random.randint(self.unfollow_break_min,
  308. self.unfollow_break_max)
  309. log_string = "Pausing for %i seconds... %i of %i" % (
  310. sleeptime, self.unfollow_counter, self.follow_counter)
  311. self.write_log(log_string)
  312. time.sleep(sleeptime)
  313. self.bot_follow_list.remove(f)
  314.  
  315. # Logout
  316. if (self.login_status):
  317. self.logout()
  318. exit(0)
  319.  
  320. def get_media_id_by_tag(self, tag):
  321. """ Get media ID set, by your hashtag """
  322.  
  323. if (self.login_status):
  324. log_string = "Get media id by tag: %s" % (tag)
  325. self.write_log(log_string)
  326. if self.login_status == 1:
  327. url_tag = self.url_tag % (tag)
  328. try:
  329. r = self.s.get(url_tag)
  330. all_data = json.loads(r.text)
  331.  
  332. self.media_by_tag = list(all_data['tag']['media']['nodes'])
  333. except:
  334. self.media_by_tag = []
  335. self.write_log("Except on get_media!")
  336. else:
  337. return 0
  338.  
  339. def like_all_exist_media(self, media_size=-1, delay=True):
  340. """ Like all media ID that have self.media_by_tag """
  341.  
  342. if self.login_status:
  343. if self.media_by_tag != 0:
  344. i = 0
  345. for d in self.media_by_tag:
  346. # Media count by this tag.
  347. if media_size > 0 or media_size < 0:
  348. media_size -= 1
  349. l_c = self.media_by_tag[i]['likes']['count']
  350. if ((l_c <= self.media_max_like and
  351. l_c >= self.media_min_like) or
  352. (self.media_max_like == 0 and
  353. l_c >= self.media_min_like) or
  354. (self.media_min_like == 0 and
  355. l_c <= self.media_max_like) or
  356. (self.media_min_like == 0 and
  357. self.media_max_like == 0)):
  358. for blacklisted_user_name, blacklisted_user_id in self.user_blacklist.items(
  359. ):
  360. if self.media_by_tag[i]['owner'][
  361. 'id'] == blacklisted_user_id:
  362. self.write_log(
  363. "Not liking media owned by blacklisted user: "
  364. + blacklisted_user_name)
  365. return False
  366. if self.media_by_tag[i]['owner'][
  367. 'id'] == self.user_id:
  368. self.write_log(
  369. "Keep calm - It's your own media ;)")
  370. return False
  371.  
  372. try:
  373. caption = self.media_by_tag[i][
  374. 'caption'].encode(
  375. 'ascii', errors='ignore')
  376. tag_blacklist = set(self.tag_blacklist)
  377. if sys.version_info[0] == 3:
  378. tags = {
  379. str.lower(
  380. (tag.decode('ASCII')).strip('#'))
  381. for tag in caption.split()
  382. if (tag.decode('ASCII')
  383. ).startswith("#")
  384. }
  385. else:
  386. tags = {
  387. unicode.lower(
  388. (tag.decode('ASCII')).strip('#'))
  389. for tag in caption.split()
  390. if (tag.decode('ASCII')
  391. ).startswith("#")
  392. }
  393.  
  394. if tags.intersection(tag_blacklist):
  395. matching_tags = ', '.join(
  396. tags.intersection(tag_blacklist))
  397. self.write_log(
  398. "Not liking media with blacklisted tag(s): "
  399. + matching_tags)
  400. return False
  401. except:
  402. self.write_log(
  403. "Couldn't find caption - not liking")
  404. return False
  405.  
  406. log_string = "Trying to like media: %s" % \
  407. (self.media_by_tag[i]['id'])
  408. self.write_log(log_string)
  409. like = self.like(self.media_by_tag[i]['id'])
  410. # comment = self.comment(self.media_by_tag[i]['id'], 'Cool!')
  411. # follow = self.follow(self.media_by_tag[i]["owner"]["id"])
  412. if like != 0:
  413. if like.status_code == 200:
  414. # Like, all ok!
  415. self.error_400 = 0
  416. self.like_counter += 1
  417. log_string = "Liked: %s. Like #%i." % \
  418. (self.media_by_tag[i]['id'],
  419. self.like_counter)
  420. self.write_log(log_string)
  421. elif like.status_code == 400:
  422. log_string = "Not liked: %i" \
  423. % (like.status_code)
  424. self.write_log(log_string)
  425. # Some error. If repeated - can be ban!
  426. if self.error_400 >= self.error_400_to_ban:
  427. # Look like you banned!
  428. time.sleep(self.ban_sleep_time)
  429. else:
  430. self.error_400 += 1
  431. else:
  432. log_string = "Not liked: %i" \
  433. % (like.status_code)
  434. self.write_log(log_string)
  435. return False
  436. # Some error.
  437. i += 1
  438. if delay:
  439. time.sleep(self.like_delay * 0.9 +
  440. self.like_delay * 0.2 *
  441. random.random())
  442. else:
  443. return True
  444. else:
  445. return False
  446. else:
  447. return False
  448. else:
  449. return False
  450. else:
  451. self.write_log("No media to like!")
  452.  
  453. def like(self, media_id):
  454. """ Send http request to like media by ID """
  455. if self.login_status:
  456. url_likes = self.url_likes % (media_id)
  457. try:
  458. like = self.s.post(url_likes)
  459. last_liked_media_id = media_id
  460. except:
  461. self.write_log("Except on like!")
  462. like = 0
  463. return like
  464.  
  465. def unlike(self, media_id):
  466. """ Send http request to unlike media by ID """
  467. if self.login_status:
  468. url_unlike = self.url_unlike % (media_id)
  469. try:
  470. unlike = self.s.post(url_unlike)
  471. except:
  472. self.write_log("Except on unlike!")
  473. unlike = 0
  474. return unlike
  475.  
  476. def comment(self, media_id, comment_text):
  477. """ Send http request to comment """
  478. if self.login_status:
  479. comment_post = {'comment_text': comment_text}
  480. url_comment = self.url_comment % (media_id)
  481. try:
  482. comment = self.s.post(url_comment, data=comment_post)
  483. if comment.status_code == 200:
  484. self.comments_counter += 1
  485. log_string = 'Write: "%s". #%i.' % (comment_text,
  486. self.comments_counter)
  487. self.write_log(log_string)
  488. return comment
  489. except:
  490. self.write_log("Except on comment!")
  491. return False
  492.  
  493. def follow(self, user_id):
  494. """ Send http request to follow """
  495. if self.login_status:
  496. url_follow = self.url_follow % (user_id)
  497. try:
  498. follow = self.s.post(url_follow)
  499. if follow.status_code == 200:
  500. self.follow_counter += 1
  501. log_string = "Followed: %s #%i." % (user_id,
  502. self.follow_counter)
  503. self.write_log(log_string)
  504. return follow
  505. except:
  506. self.write_log("Except on follow!")
  507. return False
  508.  
  509. def unfollow(self, user_id):
  510. """ Send http request to unfollow """
  511. if self.login_status:
  512. url_unfollow = self.url_unfollow % (user_id)
  513. try:
  514. unfollow = self.s.post(url_unfollow)
  515. if unfollow.status_code == 200:
  516. self.unfollow_counter += 1
  517. log_string = "Unfollow: %s #%i." % (user_id,
  518. self.unfollow_counter)
  519. self.write_log(log_string)
  520. return unfollow
  521. except:
  522. self.write_log("Exept on unfollow!")
  523. return False
  524.  
  525. def unfollow_on_cleanup(self, user_id):
  526. """ Unfollow on cleanup by @rjmayott """
  527. if self.login_status:
  528. url_unfollow = self.url_unfollow % (user_id)
  529. try:
  530. unfollow = self.s.post(url_unfollow)
  531. if unfollow.status_code == 200:
  532. self.unfollow_counter += 1
  533. log_string = "Unfollow: %s #%i of %i." % (
  534. user_id, self.unfollow_counter, self.follow_counter)
  535. self.write_log(log_string)
  536. else:
  537. log_string = "Slow Down - Pausing for 5 minutes so we don't get banned!"
  538. self.write_log(log_string)
  539. time.sleep(300)
  540. unfollow = self.s.post(url_unfollow)
  541. if unfollow.status_code == 200:
  542. self.unfollow_counter += 1
  543. log_string = "Unfollow: %s #%i of %i." % (
  544. user_id, self.unfollow_counter,
  545. self.follow_counter)
  546. self.write_log(log_string)
  547. else:
  548. log_string = "Still no good :( Skipping and pausing for another 5 minutes"
  549. self.write_log(log_string)
  550. time.sleep(300)
  551. return False
  552. return unfollow
  553. except:
  554. log_string = "Except on unfollow... Looks like a network error"
  555. self.write_log(log_string)
  556. return False
  557.  
  558. def auto_mod(self):
  559. """ Star loop, that get media ID by your tag list, and like it """
  560. if self.login_status:
  561. while True:
  562. random.shuffle(self.tag_list)
  563. self.get_media_id_by_tag(random.choice(self.tag_list))
  564. self.like_all_exist_media(random.randint \
  565. (1, self.max_like_for_one_tag))
  566.  
  567. def new_auto_mod(self):
  568. while True:
  569. # ------------------- Get media_id -------------------
  570. if len(self.media_by_tag) == 0:
  571. self.get_media_id_by_tag(random.choice(self.tag_list))
  572. self.this_tag_like_count = 0
  573. self.max_tag_like_count = random.randint(
  574. 1, self.max_like_for_one_tag)
  575. # ------------------- Like -------------------
  576. self.new_auto_mod_like()
  577. # ------------------- Follow -------------------
  578. self.new_auto_mod_follow()
  579. # ------------------- Unfollow -------------------
  580. self.new_auto_mod_unfollow()
  581. # ------------------- Comment -------------------
  582. self.new_auto_mod_comments()
  583. # Bot iteration in 1 sec
  584. time.sleep(3)
  585. # print("Tic!")
  586.  
  587. def new_auto_mod_like(self):
  588. if time.time() > self.next_iteration["Like"] and self.like_per_day != 0 \
  589. and len(self.media_by_tag) > 0:
  590. # You have media_id to like:
  591. if self.like_all_exist_media(media_size=1, delay=False):
  592. # If like go to sleep:
  593. self.next_iteration["Like"] = time.time() + \
  594. self.add_time(self.like_delay)
  595. # Count this tag likes:
  596. self.this_tag_like_count += 1
  597. if self.this_tag_like_count >= self.max_tag_like_count:
  598. self.media_by_tag = [0]
  599. # Del first media_id
  600. del self.media_by_tag[0]
  601.  
  602. def new_auto_mod_follow(self):
  603. if time.time() > self.next_iteration["Follow"] and \
  604. self.follow_per_day != 0 and len(self.media_by_tag) > 0:
  605. if self.media_by_tag[0]["owner"]["id"] == self.user_id:
  606. self.write_log("Keep calm - It's your own profile ;)")
  607. return
  608. log_string = "Trying to follow: %s" % (
  609. self.media_by_tag[0]["owner"]["id"])
  610. self.write_log(log_string)
  611.  
  612. if self.follow(self.media_by_tag[0]["owner"]["id"]) != False:
  613. self.bot_follow_list.append(
  614. [self.media_by_tag[0]["owner"]["id"], time.time()])
  615. self.next_iteration["Follow"] = time.time() + \
  616. self.add_time(self.follow_delay)
  617.  
  618. def new_auto_mod_unfollow(self):
  619. if time.time() > self.next_iteration["Unfollow"] and \
  620. self.unfollow_per_day != 0 and len(self.bot_follow_list) > 0:
  621. if self.bot_mode == 0:
  622. for f in self.bot_follow_list:
  623. if time.time() > (f[1] + self.follow_time):
  624. log_string = "Trying to unfollow #%i: " % (
  625. self.unfollow_counter + 1)
  626. self.write_log(log_string)
  627. self.auto_unfollow()
  628. self.bot_follow_list.remove(f)
  629. self.next_iteration["Unfollow"] = time.time() + \
  630. self.add_time(self.unfollow_delay)
  631. if self.bot_mode == 1:
  632. unfollow_protocol(self)
  633.  
  634. def new_auto_mod_comments(self):
  635. if time.time() > self.next_iteration["Comments"] and self.comments_per_day != 0 \
  636. and len(self.media_by_tag) > 0 \
  637. and self.check_exisiting_comment(self.media_by_tag[0]['code']) == False:
  638. comment_text = self.generate_comment()
  639. log_string = "Trying to comment: %s" % (self.media_by_tag[0]['id'])
  640. self.write_log(log_string)
  641. if self.comment(self.media_by_tag[0]['id'], comment_text) != False:
  642. self.next_iteration["Comments"] = time.time() + \
  643. self.add_time(self.comments_delay)
  644.  
  645. def add_time(self, time):
  646. """ Make some random for next iteration"""
  647. return time * 0.9 + time * 0.2 * random.random()
  648.  
  649. def generate_comment(self):
  650. c_list = list(itertools.product(*self.comment_list))
  651.  
  652. repl = [(" ", " "), (" .", "."), (" !", "!")]
  653. res = " ".join(random.choice(c_list))
  654. for s, r in repl:
  655. res = res.replace(s, r)
  656. return res.capitalize()
  657.  
  658. def check_exisiting_comment(self, media_code):
  659. url_check = self.url_media_detail % (media_code)
  660. check_comment = self.s.get(url_check)
  661. all_data = json.loads(check_comment.text)
  662. if all_data['graphql']['shortcode_media']['owner']['id'] == self.user_id:
  663. self.write_log("Keep calm - It's your own media ;)")
  664. # Del media to don't loop on it
  665. del self.media_by_tag[0]
  666. return True
  667. comment_list = list(all_data['graphql']['shortcode_media']['edge_media_to_comment']['edges'])
  668. for d in comment_list:
  669. if d['node']['owner']['id'] == self.user_id:
  670. self.write_log("Keep calm - Media already commented ;)")
  671. # Del media to don't loop on it
  672. del self.media_by_tag[0]
  673. return True
  674. return False
  675.  
  676. def auto_unfollow(self):
  677. chooser = 1
  678. current_user = 'abcd'
  679. current_id = '12345'
  680. checking = True
  681. self.media_on_feed = []
  682. if len(self.media_on_feed) < 1:
  683. self.get_media_id_recent_feed()
  684. if len(self.media_on_feed) != 0:
  685. chooser = random.randint(0, len(self.media_on_feed) - 1)
  686. current_id = self.media_on_feed[chooser]['node']["owner"]["id"]
  687. current_user = self.media_on_feed[chooser]['node']["owner"][
  688. "username"]
  689.  
  690. while checking:
  691. for wluser in self.unfollow_whitelist:
  692. if wluser == current_user:
  693. chooser = random.randint(0,
  694. len(self.media_on_feed) - 1)
  695. current_id = self.media_on_feed[chooser]['node'][
  696. "owner"]["id"]
  697. current_user = self.media_on_feed[chooser]['node'][
  698. "owner"]["username"]
  699. log_string = (
  700. "found whitelist user, starting search again")
  701. self.write_log(log_string)
  702. break
  703. else:
  704. checking = False
  705.  
  706. if self.login_status:
  707. now_time = datetime.datetime.now()
  708. log_string = "%s : Get user info \n%s" % (
  709. self.user_login, now_time.strftime("%d.%m.%Y %H:%M"))
  710. self.write_log(log_string)
  711. if self.login_status == 1:
  712. url_tag = self.url_user_detail % (current_user)
  713. try:
  714. r = self.s.get(url_tag)
  715. all_data = json.loads(r.text)
  716.  
  717. self.user_info = all_data['user']
  718. i = 0
  719. log_string = "Checking user info.."
  720. self.write_log(log_string)
  721.  
  722. while i < 1:
  723. follows = self.user_info['follows']['count']
  724. follower = self.user_info['followed_by']['count']
  725. media = self.user_info['media']['count']
  726. follow_viewer = self.user_info['follows_viewer']
  727. followed_by_viewer = self.user_info[
  728. 'followed_by_viewer']
  729. requested_by_viewer = self.user_info[
  730. 'requested_by_viewer']
  731. has_requested_viewer = self.user_info[
  732. 'has_requested_viewer']
  733. log_string = "Follower : %i" % (follower)
  734. self.write_log(log_string)
  735. log_string = "Following : %s" % (follows)
  736. self.write_log(log_string)
  737. log_string = "Media : %i" % (media)
  738. self.write_log(log_string)
  739. if follower / follows > 2:
  740. self.is_selebgram = True
  741. self.is_fake_account = False
  742. print(' >>>This is probably Selebgram account')
  743. elif follows / follower > 2:
  744. self.is_fake_account = True
  745. self.is_selebgram = False
  746. print(' >>>This is probably Fake account')
  747. else:
  748. self.is_selebgram = False
  749. self.is_fake_account = False
  750. print(' >>>This is a normal account')
  751.  
  752. if follows / media < 10 and follower / media < 10:
  753. self.is_active_user = True
  754. print(' >>>This user is active')
  755. else:
  756. self.is_active_user = False
  757. print(' >>>This user is passive')
  758.  
  759. if follow_viewer or has_requested_viewer:
  760. self.is_follower = True
  761. print(" >>>This account is following you")
  762. else:
  763. self.is_follower = False
  764. print(' >>>This account is NOT following you')
  765.  
  766. if followed_by_viewer or requested_by_viewer:
  767. self.is_following = True
  768. print(' >>>You are following this account')
  769.  
  770. else:
  771. self.is_following = False
  772. print(' >>>You are NOT following this account')
  773. i += 1
  774.  
  775. except:
  776. media_on_feed = []
  777. self.write_log("Except on get_info!")
  778. time.sleep(20)
  779. return 0
  780. else:
  781. return 0
  782.  
  783. if self.is_selebgram is not False or self.is_fake_account is not False or self.is_active_user is not True or self.is_follower is not True:
  784. print(current_user)
  785. self.unfollow(current_id)
  786. try:
  787. del self.media_on_feed[chooser]
  788. except:
  789. self.media_on_feed = []
  790. self.media_on_feed = []
  791.  
  792. def get_media_id_recent_feed(self):
  793. if self.login_status:
  794. now_time = datetime.datetime.now()
  795. log_string = "%s : Get media id on recent feed" % (self.user_login)
  796. self.write_log(log_string)
  797. if self.login_status == 1:
  798. url_tag = 'https://www.instagram.com/?__a=1'
  799. try:
  800. r = self.s.get(url_tag)
  801. all_data = json.loads(r.text)
  802.  
  803. self.media_on_feed = list(
  804. all_data['graphql']['user']['edge_web_feed_timeline'][
  805. 'edges'])
  806.  
  807. log_string = "Media in recent feed = %i" % (
  808. len(self.media_on_feed))
  809. self.write_log(log_string)
  810. except:
  811. self.media_on_feed = []
  812. self.write_log("Except on get_media!")
  813. time.sleep(20)
  814. return 0
  815. else:
  816. return 0
  817.  
  818. def write_log(self, log_text):
  819. """ Write log by print() or logger """
  820.  
  821. if self.log_mod == 0:
  822. try:
  823. print(log_text)
  824. except UnicodeEncodeError:
  825. print("Your text has unicode problem!")
  826. elif self.log_mod == 1:
  827. # Create log_file if not exist.
  828. if self.log_file == 0:
  829. self.log_file = 1
  830. now_time = datetime.datetime.now()
  831. self.log_full_path = '%s%s_%s.log' % (
  832. self.log_file_path, self.user_login,
  833. now_time.strftime("%d.%m.%Y_%H:%M"))
  834. formatter = logging.Formatter('%(asctime)s - %(name)s '
  835. '- %(message)s')
  836. self.logger = logging.getLogger(self.user_login)
  837. self.hdrl = logging.FileHandler(self.log_full_path, mode='w')
  838. self.hdrl.setFormatter(formatter)
  839. self.logger.setLevel(level=logging.INFO)
  840. self.logger.addHandler(self.hdrl)
  841. # Log to log file.
  842. try:
  843. self.logger.info(log_text)
  844. except UnicodeEncodeError:
  845. print("Your text has unicode problem!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement