ohld / igbot

🐙 Free scripts, bots and Python API wrapper. Get free followers with our auto like, auto follow and other scripts!
https://hikerapi.com/p/N2P6iqiM
Apache License 2.0
4.69k stars 1.47k forks source link

How use 'Like medias by location' #979

Closed disayner closed 5 years ago

disayner commented 5 years ago

Purpose of your issue?

Code:

# coding=utf-8
"""
    instabot example
    Workflow:
        Like medias by location.
"""

import argparse
import codecs
import os
import sys

from tqdm import tqdm

stdout = sys.stdout
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

sys.path.append(os.path.join(sys.path[0], '../'))
from instabot import Bot

try:
    input = raw_input
except NameError:
    pass

def like_location_feed(new_bot, new_location, amount=0):
    counter = 0
    max_id = ''
    with tqdm(total=amount) as pbar:
        while counter < amount:
            if new_bot.api.get_location_feed(new_location['location']['pk'], max_id=max_id):
                location_feed = new_bot.api.last_json
                for media in new_bot.filter_medias(location_feed["items"][:amount], quiet=True):
                    if bot.like(media):
                        counter += 1
                        pbar.update(1)
                if location_feed.get('next_max_id'):
                    max_id = location_feed['next_max_id']
                else:
                    return False
    return True

parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('-u', type=str, help="username")
parser.add_argument('-p', type=str, help="password")
parser.add_argument('-amount', type=str, help="amount")
parser.add_argument('-proxy', type=str, help="proxy")
parser.add_argument('locations', type=str, nargs='*', help='locations')
args = parser.parse_args()

try:
    print(u'Like medias by location')
except TypeError:
    sys.stdout = stdout

bot = Bot()
bot.login(username=args.u, password=args.p,
          proxy=args.proxy)

if args.locations:
    for location in args.locations:
        print(u"Location: {}".format(location))
        bot.api.search_location(location)
        finded_location = bot.api.last_json['items'][0]
        if finded_location:
            print(u"Found {}".format(finded_location['title']))

            if not args.amount:
                nlikes = input(u"How much likes per location?\n")
            else:
                nlikes = args.amount
            like_location_feed(bot, finded_location, amount=int(nlikes))
else:
    location_name = input(u"Write location name:\n").strip()
    bot.api.search_location(location_name)
    if not bot.api.last_json['items']:
        print(u'Location was not found')
        exit(1)
    if not args.amount:
        nlikes = input(u"How much likes per location?\n")
    else:
        nlikes = args.amount
    ans = True
    while ans:
        for n, location in enumerate(bot.api.last_json["items"], start=1):
            print(u'{0}. {1}'.format(n, location['title']))
        print(u'\n0. Exit\n')
        ans = int(input(u"What place would you want to choose?\n").strip())
        if ans == 0:
            exit(0)
        try:
            ans -= 1
            if 0 <= ans < len(bot.last_json["items"]):
                like_location_feed(bot, bot.api.last_json["items"][ans], amount=int(nlikes))
        except ValueError:
            print(u"\n Not valid choice. Try again")

Error/Debug Log:

Write location name:
Moscow
How much likes per location?
1000
1. Moscow, Russia
2. Moscow
3. Moscow Oblast
4. Московский государственный университет имени М.В.Ломоносова
5. Moscow, Russia
6. Moscow, Russia
7. Moscow Conservatory
8. THE MOSCOW CITY
9. Mátcơva
10. Moscow Kremlin
11. Музеи Московского Кремля. The Moscow Kremlin Museums
12. Moscow Sheremetyevo International Airport, Terminal D
13. Moscow Metro
14. Four Seasons Hotel Moscow
15. Москва-Сити
16. Multimedia Art Museum, Moscow
17. Metropol Hotel Moscow
18. Московский Зоопарк/ Moscow zoo
19. Kremlin Palace Moscow
20. Moscow , Red Square
21. Europe/Moscow
22. Moscow Raceway
23. Moskovsky, Moscow
24. The Moscow Times
25. Moscow, Idaho
26. Korolyov, Moscow Oblast
27. Gorky Park (Moscow)
28. Hotel Baltschug Kempinski Moscow    Отель «Балчуг Кемпински Москва»
29. SKOLKOVO - Moscow School of Management
30. Moscow, Pennsylvania
31. Kremlin  Moscow
32. The Moscow City
33. TSUM Department Store Moscow
34. Moscow Botanical Garden of Academy of Sciences
35. Mozhaysky District, Moscow
36. Krasnogorsk, Moscow Oblast
37. Moscow Cinema
38. Moscow Museum of Modern Art
39. NOOR BAR
40. Swissotel Krasnye Holmy Moscow
41. Moscow, Tennessee
42. Хамовники
43. Elektrosal, Moscow Oblast, Russia
44. Radisson Collection Hotel Moscow
45. New Arbat Street Moscow
46. Propaganda (Moscow)
47. Рихтер
48. МГУ - Moscow State University
49. PFC CSKA MOSCOW
50. Moscow Marriott Grand Hotel
51. أنوار الثقافة
52. РИА Новости
53. Moscow, Russian SFSR
54. Басманный район
55. The Ritz-Carlton, Moscow
56. Red Square, Moscow
57. Taste of Moscow
58. Bolshoi Theatre Moscow
59. Флотилия Рэдиссон Ройал, Москва
60. RT Play
61. FC Lokomotiv Moscow
62. Red Square Moscow
63. Community Moscow
64. Radisson Moscow River Cruise
65. The St. Regis Moscow Nikolskaya
66. Ararat Park Hyatt Moscow - Арарат Парк Хаятт Москва
67. U.S. Embassy Moscow
68. Chekhov, Russia
69. Ozëry
70. Krasnogorsky District, Moscow Oblast
71. LOTTE HOTEL MOSCOW
72. Crowne Plaza Moscow - World Trade Centre
73. Москва глазами инженера
74. Depo.moscow
75. Hard Rock Cafe Moscow
76. WTC Moscow Congress Center | Конгресс-центр ЦМТ
77. Golden Ring Hotel Moscow
78. Moscow State Circus
79. The Great Moscow Circus
80. India in Russia (Embassy of India, Moscow)
81. Moscow Mills, Missouri
82. BigTimeMoscow
83. Sputnik France
84. Hilton Moscow Leningradskaya
85. Тверской район
86. Живая Земля
87. Цифровое Деловое Пространство
88. Aeroflot Airlines
89. Международный аэропорт Шереметьево
90. ТРЦ Чайна Таун
91. Holiday Inn Moscow Sokolniki Hotel
92. Renaissance Moscow Monarch Centre Hotel
93. Hotel Cosmos, Moscow Russia
94. Hotel National, a Luxury Collection Hotel, Moscow
95. Гагаринский район
96. RT Play en Español
97. Study in Russia. Study in Moscow
98. Фонд "Сколково"
99. Hyatt Regency Moscow Petrovsky Park
100. Единая Россия Москва

0. Exit

What place would you want to choose?
1
  0%|          | 0/1000 [00:00<?, ?it/s]
2019-07-16 16:52:24,431 - INFO - Bot stopped. Worked: 7 days, 3:15:49.152930
2019-07-16 16:52:24,431 - INFO - Total requests: 16

Process finished with exit code 0

Describe your issue

Hello to all. Tell me please somebody. How to use this script. What am I doing wrong? Whatever the city, the result is the same. Nothing likes.

dangell7 commented 5 years ago

You should break that script up....

Also don't use arguments until you know it's working. Or at least I wouldn't. I would break that script up to find out what your error is.

I would change this:

except ValueError:
    print(u"\n Not valid choice. Try again")

To:

except Exception as e:
    print(e)
    raise

I would also just test this piece of code.

try:
bot = Bot()
username = ''
password = ''
proxy = ''
bot.login(username=username, password=password, proxy=proxy)
bot.api.search_location('Moscow')
result = like_location_feed(bot, bot.api.last_json["items"][1], amount=int(1))
print(result)
except Exception as e:
print(e)
raise

If you're still getting an error, then you know its not pebcak and something wrong with the repo.

disayner commented 5 years ago

You should break that script up....

Also don't use arguments until you know it's working. Or at least I wouldn't. I would break that script up to find out what your error is.

I would change this:

except ValueError:
    print(u"\n Not valid choice. Try again")

To:

except Exception as e:
    print(e)
    raise

I would also just test this piece of code.

try:
bot = Bot()
username = ''
password = ''
proxy = ''
bot.login(username=username, password=password, proxy=proxy)
bot.api.search_location('Moscow')
result = like_location_feed(bot, bot.api.last_json["items"][1], amount=int(1))
print(result)
except Exception as e:
print(e)
raise

If you're still getting an error, then you know its not pebcak and something wrong with the repo.

Thanks for the answer. I created a test script:

from instabot import Bot

try:
    bot = Bot()

    username = 'user'
    password = 'pass'

    bot.login(username=username, password=password)

    bot.api.search_location('Moscow')
    result = bot.like_location_feed(bot, bot.api.last_json["items"][1], amount=int(1))
    print(result)
except Exception as e:
    print(e)
    raise

and got an error:

2019-07-18 11:00:03,720 - INFO - Instabot Started
2019-07-18 11:00:06,121 - INFO - Logged-in successfully as 'user'!
Traceback (most recent call last):
  File "J:/scripts/test.py", line 12, in <module>
    result = bot.like_location_feed(bot, bot.api.last_json["items"][1], amount=int(1))
IndexError: list index out of range
list index out of range
2019-07-18 11:00:07,666 - INFO - Bot stopped. Worked: 1 day, 19:31:26.032402
2019-07-18 11:00:07,667 - INFO - Total requests: 334

Then I deleted instabot using PIP pip uninstall instabot Checked that it was deleted by re-entering the command for deletion. And removed the python and installed the latest version.

Downloaded the latest version instabot: https://github.com/instagrambot/instabot/archive/master.zip unpacked, moved to the instabot-master folder and executed the command setup.py install after installation, restarted the script. Nothing has changed, the same mistake.

Then I deleted instabot using PIP pip uninstall instabot And install instabot using PIP pip install -U instabot after installation, restarted the script. Nothing has changed, the same mistake.

Tell me please, what other options might there be?

dangell7 commented 5 years ago

Are you familiar with what the error response “list index out of range” means? You could also google that and get some good info...

dangell7 commented 5 years ago

It means that when you try “list[1]”, that there are not “2” items in the list... 0,1 = 2 items. So can you infer what your next debug step is?

disayner commented 5 years ago

Thank you for taking part in my problem.

It means that when you try “list[1]”, that there are not “2” items in the list... 0,1 = 2 items. So can you infer what your next debug step is?

I understand what that means. I do not understand why you asked this.

In the first message you wrote:

If you're still getting an error, then you know its not pebcak and something wrong with the repo.

I still getting an error. Therefore, I did not write other steps that I did.

I tried to change the index. bot.api.last_json["items"][0] #0 bot.api.last_json["items"] #no second index it changed nothing

Then I tried immediately after searching for a location. See what returns [item]: bot.api.search_location('Moscow') print (bot.api.last_json["items"]) # Out - [] - There is nothing print (bot.api.last_json) # Out - {'items': [], 'has_more': True, 'rank_token': '6421777250_bcd846a6-f215-412c-bd5b-e98925032438', 'status': 'ok'}

Apparently the method bot.api.search_location ('Moscow') does not return location.

That's what's interesting. There is no Moscow in this list. https://www.instagram.com/explore/locations/RU/russia/

But she is. https://www.instagram.com/explore/locations/359545221/moscow/

If we just beat the city and change the example as follows. That works like users posting story. bot.like_location_feed("Omsk", 10)

dangell7 commented 5 years ago

Did you try

bot.api.search_location('Moscow')
print (bot.api.last_json)

What is that result?

dangell7 commented 5 years ago

What you need to do is fork the repo and go to work on debugging.....

Enter print statements everywhere until you find the moment where the error exists. Maybe the endpoint changed, or it returns "locations" not "items". idk

Go into the api.py and add print statements. Make sure you're getting a 200 response. Check to see if maybe a lower case is required. There is plenty more you can do to debug this issue.

If you continue to post your stacktrace and error logs I'll ty to help you.

disayner commented 5 years ago

Did you try

bot.api.search_location('Moscow')
print (bot.api.last_json)

What is that result?

bot.api.search_location('Moscow') print (bot.api.last_json) # Out - {'items': [], 'has_more': True, 'rank_token': '6421777250_bcd846a6-f215-412c-bd5b-e98925032438', 'status': 'ok'}

What you need to do is fork the repo and go to work on debugging.....

Enter print statements everywhere until you find the moment where the error exists. Maybe the endpoint changed, or it returns "locations" not "items". idk

Go into the api.py and add print statements. Make sure you're getting a 200 response. Check to see if maybe a lower case is required. There is plenty more you can do to debug this issue.

If you continue to post your stacktrace and error logs I'll ty to help you.

Thank. I'll try