insta-logger/index.py

69 lines
2.2 KiB
Python
Raw Normal View History

2021-09-28 08:09:09 -04:00
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import json
2021-09-28 10:52:09 -04:00
from os.path import exists
# add needed libraries
2021-09-28 08:09:09 -04:00
with open('login.json', 'r') as file:
json_object = json.load(file)
username = json_object['username']
password = json_object['password']
2021-09-28 10:52:09 -04:00
# get account credentials from json file
2021-09-28 08:09:09 -04:00
browser = webdriver.Firefox()
browser.implicitly_wait(5)
browser.get('https://www.instagram.com/')
sleep(2)
2021-09-28 10:52:09 -04:00
# start browser and go to site
2021-09-28 08:09:09 -04:00
browser.find_element_by_css_selector("input[name='username']").send_keys(username)
browser.find_element_by_css_selector("input[name='password']").send_keys(password)
browser.find_element_by_xpath("//button[@type='submit']").click()
sleep(5)
2021-09-28 10:52:09 -04:00
# login
2021-09-28 08:09:09 -04:00
browser.get('https://www.instagram.com/direct/inbox/')
sleep(2)
2021-09-28 10:52:09 -04:00
# go to dms
2021-09-28 08:09:09 -04:00
browser.find_element_by_css_selector("button.aOOlW:nth-child(2)") .click()
sleep(2)
2021-09-28 10:52:09 -04:00
# close notification pop up
2021-09-28 08:09:09 -04:00
2021-09-28 10:52:09 -04:00
browser.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[2]/div/div/div/div/div[1]/a").click()
2021-09-28 08:09:09 -04:00
sleep(2)
2021-09-28 10:52:09 -04:00
# open first direct message chat
2021-09-28 08:09:09 -04:00
2021-09-28 10:52:09 -04:00
if exists('messages.txt'):
pass
else:
open('messages.txt', "a+").writelines("##### LOG FILE #####")
# if log file does not exist create it
2021-09-28 08:09:09 -04:00
2021-09-28 10:52:09 -04:00
while True:
last_message = str(browser.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[last()]/div[2]/div").text)
# get last message from site
2021-09-28 11:18:00 -04:00
try:
l_message_author = str(browser.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[last()]/div[1]/div/a").get_attribute("href"))[26:-1]
except NoSuchElementException as exception:
l_message_author = username
2021-09-28 10:52:09 -04:00
last_line = ''
with open('messages.txt', "r") as f:
for line in f:
pass
last_line = line
print(last_line)
f.close()
#get last entry from log file
if last_message == last_line:
pass
else:
with open('messages.txt', "a+") as f:
2021-09-28 11:18:00 -04:00
f.writelines('\n' + l_message_author + ':\n')
2021-09-28 10:52:09 -04:00
f.writelines(last_message)
f.close()
# if last dm is already logged, do nothing, else log it
2021-09-28 11:18:00 -04:00
#? probably better to log to a json file