-1
我幾乎所有的東西都在這個python腳本上工作,其中一個缺失。 該腳本根據給定的時間跟隨列表中的用戶,但是如何立即忽略列表中隨後(已經跟隨)的用戶?如何實現忽略代碼?
import datetime
import logging
import random
from urllib.request import urlopen
import json
import sys
import time
import requests
from datetime import datetime
from threading import Timer
class InstaBot:
url = 'https://www.instagram.com/'
url_follow = 'https://www.instagram.com/web/friendships/%s/follow/'
url_unfollow = 'https://www.instagram.com/web/friendships/%s/unfollow/'
url_login = 'https://www.instagram.com/accounts/login/ajax/'
url_logout = 'https://www.instagram.com/accounts/logout/'
url_media_detail = 'https://www.instagram.com/p/%s/?__a=1'
url_user_detail = 'https://www.instagram.com/%s/?__a=1'
user_agent = ("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36")
accept_language = 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4'
# If instagram ban you - query return 400 error.
error_400 = 0
# If you have 3 400 error in row - looks like you banned.
error_400_to_ban = 3
# Log setting.
log_file_path = ''
log_file = 0
# Other.
user_id = 0
# For new_auto_mod
next_iteration = {"Like": 0, "Follow": 0, "Unfollow": 0, "Comments": 0}
def __init__(self,
login,
password,
proxy="",
):
self.user_login = login.lower()
self.user_password = password
self.log_mod = 0
self.follow_counter=0
self.s = requests.Session()
# if you need proxy make something like this:
# self.s.proxies = {"https" : "http://proxyip:proxyport"}
# by @planet
if proxy != "":
proxies = {
'http': 'http://' + proxy,
'https': 'http://' + proxy,
}
self.s.proxies.update(proxies)
# convert login to lower
self.url_user_info = "https://www.instagram.com/%s/?__a=1"
def get_user_id_by_login(self, user_name):
url_info = self.url_user_info % (user_name)
info = self.s.get(url_info)
all_data = json.loads(info.text)
id_user = all_data['user']['id']
return id_user
def login(self):
log_string = 'Trying to login as %s...\n' % (self.user_login)
self.write_log(log_string)
self.s.cookies.update({
'sessionid': '',
'mid': '',
'ig_pr': '1',
'ig_vw': '1920',
'csrftoken': '',
's_network': '',
'ds_user_id': ''
})
self.login_post = {
'username': self.user_login,
'password': self.user_password
}
self.s.headers.update({
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': self.accept_language,
'Connection': 'keep-alive',
'Content-Length': '0',
'Host': 'www.instagram.com',
'Origin': 'https://www.instagram.com',
'Referer': 'https://www.instagram.com/',
'User-Agent': self.user_agent,
'X-Instagram-AJAX': '1',
'X-Requested-With': 'XMLHttpRequest'
})
r = self.s.get(self.url)
self.s.headers.update({'X-CSRFToken': r.cookies['csrftoken']})
time.sleep(5 * random.random())
login = self.s.post(
self.url_login, data=self.login_post, allow_redirects=True)
self.s.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
self.csrftoken = login.cookies['csrftoken']
time.sleep(5 * random.random())
if login.status_code == 200:
r = self.s.get('https://www.instagram.com/')
finder = r.text.find(self.user_login)
if finder != -1:
self.user_id = self.get_user_id_by_login(self.user_login)
self.login_status = True
log_string = '%s login success!' % (self.user_login)
self.write_log(log_string)
else:
self.login_status = False
self.write_log('Login error! Check your login data!')
else:
self.write_log('Login error! Connection error!')
def logout(self):
now_time = datetime.datetime.now()
log_string = 'Logout: likes - %i, follow - %i, unfollow - %i, comments - %i.' % \
(self.like_counter, self.follow_counter,
self.unfollow_counter, self.comments_counter)
self.write_log(log_string)
work_time = datetime.datetime.now() - self.bot_start
log_string = 'Bot work time: %s' % (work_time)
self.write_log(log_string)
try:
logout_post = {'csrfmiddlewaretoken': self.csrftoken}
logout = self.s.post(self.url_logout, data=logout_post)
self.write_log("Logout success!")
self.login_status = False
except:
self.write_log("Logout error!")
def follow(self, user_name):
""" Send http request to follow """
if self.login_status:
urlget_id="https://www.instagram.com/%s/?__a=1"%user_name
jsonurl = urlopen(urlget_id)
userinfo = json.loads(jsonurl.read().decode())
user_id=userinfo['user']['id']
url_follow = self.url_follow % (user_id)
try:
follow = self.s.post(url_follow)
if follow.status_code == 200:
self.follow_counter += 1
log_string = "Followed: %s #%i." % (user_name,
self.follow_counter)
self.write_log(log_string)
return follow
except:
self.write_log("Except on follow!")
return False
def write_log(self, log_text):
if self.log_mod == 0:
try:
print(log_text)
except UnicodeEncodeError:
print("Your text has unicode problem!")
elif self.log_mod == 1:
# Create log_file if not exist.
if self.log_file == 0:
self.log_file = 1
now_time = datetime.datetime.now()
self.log_full_path = '%s%s_%s.log' % (
self.log_file_path, self.user_login,
now_time.strftime("%d.%m.%Y_%H:%M"))
formatter = logging.Formatter('%(asctime)s - %(name)s '
'- %(message)s')
self.logger = logging.getLogger(self.user_login)
self.hdrl = logging.FileHandler(self.log_full_path, mode='w')
self.hdrl.setFormatter(formatter)
self.logger.setLevel(level=logging.INFO)
self.logger.addHandler(self.hdrl)
# Log to log file.
try:
self.logger.info(log_text)
except UnicodeEncodeError:
print("Your text has unicode problem!")
def followUsers(username,password,filepath,numberOfFollowersPerDay,followDelay):
instabot = InstaBot(login=username, password=password, proxy='')
instabot.login()
index=0
x = datetime.today()
y = x.replace(day=x.day + 1, hour=1, minute=0, second=0, microsecond=0)
delta_t = y - x
secs = 500 + 1
def follow(filepath,numberOfFollowersInADay,delay):
follower=0
with open(filepath) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
users = [x.strip() for x in content]
while((follower<numberOfFollowersInADay) and (follower<len(users))):
nonlocal index
instabot.follow(users[index])
time.sleep(delay)
follower=follower+1
index=index+1
print("done for today")
t = Timer(secs, follow(filepath,numberOfFollowersPerDay,followDelay))
t.start()
#call followUsers with parameteres username,password,filepath,totalnumbresOfFollowin a day, follow dealay in seconds
followUsers('username','pass','C:\\Users\\rocks\\PycharmProjects\\untitled\\usernames.txt',10,30)
請,使[MCVE(https://開頭stackoverflow.com/help/mcve) –
我不熟悉這一點,我正在尋求一些幫助。 – user8068759