0

I have created a bot for Instagram and it works well when it likes an image but when it comments, the first few work in a set of images but then starts commenting 'None'. I cannot for the life of me find the error and assume it is a problem to do with commenting the same thing twice?

Here is the code. I know it is a massive chink but it will work out of the box and replicates the problem exactly.

import requests
import json
import random


def gen_comment():
    comment_list = ["great job!", "lb", "nice shot, take a look at mine!", "perfect!", "#beautiful", "nice shot!", "awesome!", "great photo!", "nice", ":)", "love this", "great shot! take a look at my account! ;)", "WOW!", "lol", "WoW!", 'lovely!', 'amazing']
    comment = random.choice(comment_list)
    return comment


def comment(media_id):
    """ Send http request to comment """
    comment_text = gen_comment()
    comment_post = {'comment_text': comment_text}
    url_comment = 'https://www.instagram.com/web/comments/%s/add/' % (media_id)
    try:
        comment = s.post(url_comment, data=comment_post)
        if comment.status_code == 200:
            return comment_text
        else:
            print comment.status_code
    except:
        print("error on comment")

def get_media_id_by_tag(tag):
    """ Get media ID set, by your hashtag """

    url_tag = '%s%s%s' % ('https://www.instagram.com/explore/tags/', tag, '/')
    try:
        r = s.get(url_tag)
        text = r.text
        finder_text_start = ('<script type="text/javascript">'
                             'window._sharedData = ')
        finder_text_start_len = len(finder_text_start) - 1
        finder_text_end = ';</script>'
        all_data_start = text.find(finder_text_start)
        all_data_end = text.find(finder_text_end, all_data_start + 1)
        json_str = text[(all_data_start + finder_text_start_len + 1) \
            : all_data_end]
        all_data = json.loads(json_str)
        return list(all_data['entry_data']['TagPage'][0]['tag']['media']['nodes'])
    except Exception as e:
        print("Except on get_media!")
        print(e)



username = raw_input("Username: ")
password = raw_input("Password: ")
tag = raw_input("Tag: ")

user_agent = ("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
              "(KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36")

s = requests.Session()
s.cookies.update({'sessionid': '', 'mid': '', 'ig_pr': '1',
                       'ig_vw': '1920', 'csrftoken': '',
                       's_network': '', 'ds_user_id': ''})
login_post = {'username': username,
                   'password': password}
s.headers.update({'Accept-Encoding': 'gzip, deflate',
                       'Accept-Language': 'en',
                       'Connection': 'keep-alive',
                       'Content-Length': '0',
                       'Host': 'www.instagram.com',
                       'Origin': 'https://www.instagram.com',
                       'Referer': 'https://www.instagram.com/',
                       'User-Agent': user_agent,
                       'X-Instagram-AJAX': '1',
                       'X-Requested-With': 'XMLHttpRequest'})
r = s.get('https://www.instagram.com/')
s.headers.update({'X-CSRFToken': r.cookies['csrftoken']})
login = s.post('https://www.instagram.com/accounts/login/ajax/', data=login_post,
                allow_redirects=True)
s.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
csrftoken = login.cookies['csrftoken']

media = get_media_id_by_tag(tag)
for i in media:
    c = comment(i['id'])
    print 'commented {} on media {}'.format(c, i['id'])

EDIT 1 I have edited my code and found that I am getting a 400 error on the comment function which stops the function returning the desired text. I don't know why i am getting this 400 error but i will research it. Any help is appreciated

Jonah Fleming
  • 1,187
  • 4
  • 19
  • 31
  • 1
    Your comment function does not return a value for the 'except' branch, so it will return None by default. Same potential problem for get_media_id_by_tag. Printing an error message is not the same as returning a value. – Brandin Feb 15 '17 at 08:04
  • `for i in media:` need change to : `for i in media: if more_birds_fly_on_sky : count_birds(); take_a_SIP_of_coffee();continue` – dsgdfg Feb 15 '17 at 08:26
  • @dsgdfg um whats that supposed to mean? – Jonah Fleming Feb 15 '17 at 09:44
  • @Brandin Thanks ill change that then take a look at the error. – Jonah Fleming Feb 15 '17 at 09:45
  • Did you you know latency time with server, maybe server detect you as bot ? – dsgdfg Feb 15 '17 at 13:14
  • I notice one of your generated comments has the character '#'. Depending on how the Requests library is sending your data, you may need to 'urlencode' the data before transmission. Maybe the server responds with 400 if you don't do it properly? More information here: http://stackoverflow.com/questions/6603928/should-i-url-encode-post-data – Brandin Feb 15 '17 at 19:26
  • @Brandin I don't believe it is that. I can send 5 comments and likes before it errors so i think its a server anti-bot thing. I'll see if playing with the timing does anything. – Jonah Fleming Feb 16 '17 at 08:38
  • @JonahFleming Read the official docs to avoid errors like these. The docs say only up to 4 hashtags, and # probably denotes a hashtag: https://www.instagram.com/developer/endpoints/comments/ – Brandin Feb 16 '17 at 09:10
  • @JonahFleming Are you working on instagram? May be, we can exchange email for communication? Url to add the comments https://www.instagram.com/web/comments/media-id/add/comment_text=comment right? – Delphian Feb 20 '17 at 10:06
  • @Delphian thanks for the comment but i have figured it out. my comments were too fast and were being detected as a bot so being blocked. – Jonah Fleming Feb 21 '17 at 07:25
  • @JonahFleming Rate limits it's serious https://www.instagram.com/developer/limits/. May be do you know how to get users which likes photo using https request? – Delphian Feb 21 '17 at 07:56

0 Answers0