Advertisement
Guest User

Untitled

a guest
Jul 17th, 2013
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.66 KB | None | 0 0
  1. from grab import Grab, UploadFile
  2. import time, re, random
  3.  
  4. with open('Texts.txt') as f: full_texts = filter(lambda txt: txt != '', f.read().splitlines()) # Тайтлы и текста объявлений
  5.  
  6. class BOT(object):
  7.  
  8.     def __init__(self, login, pwd): # Объявляем данные для входа
  9.         self.login = login
  10.         self.pwd = pwd
  11.        
  12.     def Add_Teasers(self, g): # Метод добавления новых тизеров в таргет
  13.         sub = 1
  14.    
  15.         for i in range(10): # Будем создавать по 10 объявлений за проход
  16.             obv = False
  17.        
  18.             while not obv: # До тех пор пока не создали объявление
  19.                 try:
  20.            
  21.                     # title, text = random.choice(titles), random.choice(texts) # Текста и тайтлы берем рандомно
  22.                     full_text = random.choice(full_texts); title = full_text.split(':')[0].decode('cp1251').encode('utf-8'); text = full_text.split(':')[-1].decode('cp1251').encode('utf-8')
  23.                     print u"Начинаем создавать объявление ...\nЗаголовок - %s\nТекст - %s" % (title.decode('utf-8'), text.decode('utf-8'))
  24.                     g.go('http://fotostrana.ru/target/index/create/?default_campaign_id=929'); time.sleep(1) # Переходим в создание объявления
  25.                     g.go('http://fotostrana.ru/target/index/uploadImages/', multipart_post={'type' : '1', 'photo' : UploadFile(r'ССЫЛКА_ДО_ИЗОБРАЖЕНИЯ')}, headers={'Origin' : 'http://fotostrana.ru'}); time.sleep(1) # Заливаем нашу картинку
  26.                     photo_url = re.findall(r'photoLoaded\(\"(.+?)\"', g.response.body)[0]
  27.                     photo_id = re.findall(photo_url + r'\", \"(.+?)\"', g.response.body, re.S)[0]
  28.                     print u"Загрузили изображение, его ID в системе - %s, начинаем создавать объявление ..." % photo_id
  29.                     g.go('http://fotostrana.ru/target/index/savebanner/', post={'_ajax' : '1', 'banner[banner_type_pay]' : '1', 'banner[banner_type_content]' : '1', 'banner[site]' : 'ССЫЛКА_ДЛЯ_СЛИВА/FS_%s' % sub, 'banner[domain]' : 'landing.ubrr.ru', 'banner[app]' : '0', 'banner[title]' : title, 'banner[text]' : text, 'banner[image_crop]' : '0_0_181.3846153846154_131_181.3846153846154_131', 'banner[image_name]' : photo_id, 'banner[sex]' : '0', 'banner[age_from]' : '21', 'banner[age_to]' : str(random.randint(55, 65)), 'banner[country]' : '1', 'banner[cities]' : '', 'banner[regions]' : '', 'banner[marry]' : '', 'banner[browser]' : '', 'banner[pay]' : '0', 'banner[campaign_choose_type]' : '2', 'banner[campaign_title]' : '', 'banner[campaign_id]' : '929', 'banner[price]' : '5', 'type' : '1'}, headers={'Origin' : 'http://fotostrana.ru', 'X-Requested-With' : 'XMLHttpRequest', 'Referer' : 'http://fotostrana.ru/target/index/create/?default_campaign_id=929'}); time.sleep(1) # Создаем объявление
  30.                     banner_id = re.search(r'banner_id\"\:(\d+?),', g.response.body).group(1) # Тащим ID созданного объявления
  31.                     print u"Объявление создано, его ID - %s, запускаем ..." % banner_id
  32.                     with open('banner_ids.txt', 'a') as f: f.write('%s\n' % banner_id) # Записываем id баннера в файл
  33.                     g.go('http://fotostrana.ru/target/ajax/changebannerstatus/?_ajax=1&bannerId=%s&status=run&textstatus=false' % banner_id); time.sleep(1) # Запускам объявление
  34.                     print u"Объявление запущено, спим немного и продолжаем ...\n"; sub += 1; obv = True; time.sleep(random.randint(5, 10))
  35.                
  36.                 except Exception as err:
  37.                     with open('resp.html', 'w') as f: f.write(g.response.body)
  38.                     print u"Тизер создать не удалось, спим немного и пробуем заного ...\n"; time.sleep(random.randint(1, 1))
  39.    
  40.     def Login(self, g, last4): # Метод авторизации
  41.         print u"Авторизуемся, логин - %s, пароль - %s ...\n" % (self.login, self.pwd); self.last4 = last4
  42.         g.go('http://fotostrana.ru'); time.sleep(random.uniform(1, 1))
  43.         csrftkn = re.findall(r'name="csrftkn" value="(.+?)"', g.response.body)[0]; time.sleep(random.uniform(1, 1)) # Тащим токен
  44.         g.go('http://fotostrana.ru/signup/signup/auth/', post='csrftkn=%s&user_email=%s&user_password=%s&submitted=1&issetFields[]=csrftkn&issetFields[]=user_email&issetFields[]=user_password&issetFields[]=submitted&_fs2ajax=1' % (csrftkn, self.login, self.pwd), headers={'Referer' : 'http://fotostrana.ru/signup/login/?fromHeader=1'}); time.sleep(random.uniform(1, 1)) # Авторизуемся
  45.        
  46.         if re.search(r'is_login":1', g.response.body): # Проверяем авторизацию
  47.             g.go('http://fotostrana.ru'); time.sleep(random.uniform(1, 1)) # Переходим в свой профиль
  48.             if re.search(r'Лучшие фотографии', g.response.body): print u"Вход выполнен успешно, начинаем работу ...\n"; return g.clone() # Если авторизация успешна
  49.            
  50.         elif re.search(r'Защита профиля', g.response.body): # Если выпала защита профиля
  51.             print u"Вход с нового адреса - вводим последние 4 цифры ..."
  52.             g.go(g.response.url, post={'smscode' : last4, 'saveaccess' : '4'}); time.sleep(random.uniform(1, 1)) # Вводим последние 4 цифры
  53.             if re.search(r'Лучшие фотографии', g.response.body): # Если номер введен верно
  54.                 print u"Вход выполнен успешно, начинаем работу ...\n"; return g.clone()
  55.             else: return 0
  56.            
  57.         else:
  58.             with open('resp.html', 'w') as f: f.write(g.response.body)
  59.             print u"Вход не удался, текущий url - %s, пробуем заного ..." % g.response.url; return False
  60.  
  61. def start_bot():
  62.  
  63.     response, login_FS, auth = False, 0, 0
  64.  
  65.     while not response:
  66.    
  67.         if not login_FS: # Если еще нету куки авторизации
  68.             g = Grab(); login = 'ВАШ_ЛОГИН'; pwd = 'ВАШ_ПАРОЛЬ'
  69.             g.setup(headers={'Accept-Language' : 'en-us,en;q=0.8', 'Accept-Charset' : 'utf-8,windows-1251;q=0.7,*;q=0.5', 'X-Requested-With' : ''}) # Настраиваем прокси сервис
  70.             FS_Bot = BOT(login, pwd); time.sleep(random.uniform(1, 3))
  71.             login = FS_Bot.Login(g=g.clone(), last4='ПОСЛЕДНИЕ_4_ЦИФРЫ_ТЕЛЕФОНА'); time.sleep(random.uniform(1, 3)) # Логинимся
  72.        
  73.         if login:
  74.        
  75.             login_FS = 1 # Делаем пометку о том что есть нужные куки и заного авторизовываться не нужно
  76.             print u"\nЧто делаем дальше?\n\n1 - Добавить 10 новых тизеров"
  77.             resp = str(raw_input("\nPress your choice: "))
  78.  
  79.             if resp == '1':
  80.                 bt = FS_Bot.Add_Teasers(g=login) # Обновляем наши тизеры
  81.                
  82.             else: print u"До свиданья!"; response = True
  83.        
  84.         else: continue # Если не удалось залогиниться - начинаем все заного
  85.        
  86. start_bot(); raw_input('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement