<reponame>GutiNicolas/twitterbot
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from sys import argv
from datetime import date
from datetime import datetime
import os
import random
import time



class TwitterBot:
    def __init__(self, username, password, hashtag, waittime):
        self.username = username
        self.password = password
        self.hashtag = hashtag
        self.waittime = waittime
        self.bot = webdriver.Firefox()
        self.log = None

    def internal_do_random_number(self):
        return random.randint(self.waittime-2,self.waittime+2)

    def internal_start_log(self):
        today = date.today()
        now = datetime.now()
        logdate = today.strftime("%B %d, %Y")
        logtime = now.strftime("%H:%M:%S")
        self.log = open("TwitterBOT.log","a")
        self.log.write("\r\n ############### TWITTER BOT started at "+logtime+" on "+logdate+" ############### \r")
        self.log.write(" ##### DEVELOPED BY @GutiNicolas1 AKA @DeveloperGuti for academic use ONLY. ##### \r\n")

    def internal_stop_log(self):
        self.log.close()

    def internal_do_log(self, tologstr):
        now = datetime.now()
        logtime = now.strftime("%H:%M:%S")
        self.log.write(" "+tologstr+" "+logtime+"\r")

    def login(self):
        print('-- LOGIN START --')
        bot = self.bot
        bot.get('https://twitter.com/')
        time.sleep(2)
        emailbox = bot.find_element_by_class_name('email-input')
        passwordbox = bot.find_element_by_name('session[password]')
        emailbox.clear()
        passwordbox.clear()
        emailbox.send_keys(self.username)
        passwordbox.send_keys(self.password)
        passwordbox.send_keys(Keys.RETURN)
        time.sleep(4)
        try:
            bot.find_element_by_name('session[password]')
            print('--------------------- EXCEPTION START ---------------------')
            print('Ops, Something went really wrong!')
            print('[ Sorry, cannot login, password might be wrong ]')
            print(' > Verify it and try again ')
            print('--------------------- EXCEPTION END ---------------------')
            re = False
        except Exception as e:
            print('-- LOGEDIN --')
            time.sleep(3)
            re = True
        return re
        

    def target_do_likes(self):
        bot = self.bot
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if link == None:
                    break
                bot.get('https://twitter.com'+link)
                try:
                    bot.find_element_by_class_name('HeartAnimation').click()
                    print('// Tweet Liked //')
                    self.internal_do_log(" + Tweet liked [ twitter.com"+link+" ] at")
                    time.sleep(self.internal_do_random_number())
                except Exception as e:
                    print('--------------------- EXCEPTION START ---------------------')
                    print('Ops, Something went really wrong!')
                    print(e)
                    print('--------------------- EXCEPTION END ---------------------')
                    print('Dont worry, its just a twitter-side problem')
                    print('Resuming...')
                    time.sleep(1)

    def target_do_likes_timed(self, timed):
        bot = self.bot
        timeout = time.time() + 60*timed   # X minutes from now
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if time.time() > timeout:
                    break
                if link == None:
                    break
                else:
                    bot.get('https://twitter.com'+link)
                    try:
                        bot.find_element_by_class_name('HeartAnimation').click()
                        print('// Tweet Liked //')
                        self.internal_do_log(" + Tweet liked [ twitter.com"+link+" ] at")
                        time.sleep(self.internal_do_random_number())
                    except Exception as e:
                        print('--------------------- EXCEPTION START ---------------------')
                        print('Ops, Something went really wrong!')
                        print(e)
                        print('--------------------- EXCEPTION END ---------------------')
                        print('Dont worry, its just a twitter-side problem')
                        print('Resuming...')
                        time.sleep(1)
        print('Times up, see ya next time!')

    def target_do_follows(self):
        bot = self.bot
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if link == None:
                    break
                bot.get('https://twitter.com'+link)
                try:
                    bot.find_element_by_class_name('follow-text').click()
                    print('// Following //')
                    self.internal_do_log(" + Accout Followed [ @"+link.split('/')[1]+" ] at")
                    time.sleep(self.internal_do_random_number())
                except Exception as e:
                    print('--------------------- EXCEPTION START ---------------------')
                    print('Ops, Something went really wrong!')
                    print(e)
                    print('--------------------- EXCEPTION END ---------------------')
                    print('Dont worry, its just a twitter-side problem')
                    print('Resuming...')
                    time.sleep(1)


    def target_do_follows_timed(self, timed):
        bot = self.bot
        timeout = time.time() + 60*timed   # X minutes from now
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if time.time() > timeout:
                    break
                if link == None:
                    break
                else:
                    bot.get('https://twitter.com'+link)
                    try:
                        bot.find_element_by_class_name('follow-text').click()
                        print('// Following //')
                        self.internal_do_log(" + Accout Followed [ @"+link.split('/')[1]+" ] at")
                        time.sleep(self.internal_do_random_number())
                    except Exception as e:
                        print('--------------------- EXCEPTION START ---------------------')
                        print('Ops, Something went really wrong!')
                        print(e)
                        print('--------------------- EXCEPTION END ---------------------')
                        print('Dont worry, its just a twitter-side problem')
                        print('Resuming...')
                        time.sleep(1)
        print('Times up, see ya next time!')

    def target_do_retweets(self):
        bot = self.bot
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if link == None:
                    break
                bot.get('https://twitter.com'+link)
                try:
                    bot.find_element_by_xpath("//button[@data-modal='ProfileTweet-retweet']").click()
                    time.sleep(1)
                    bot.find_element_by_class_name('retweet-action').click()
                    print('// Retweeted //')
                    self.internal_do_log(" + Retweeted [ twitter.com"+link+" ] at")
                    time.sleep(self.internal_do_random_number())
                except Exception as e:
                    print('--------------------- EXCEPTION START ---------------------')
                    print('Ops, Something went really wrong!')
                    print(e)
                    print('--------------------- EXCEPTION END ---------------------')
                    print('Dont worry, its just a twitter-side problem')
                    print('Resuming...')
                    time.sleep(1)
                
    def target_do_retweets_timed(self, timed):
        bot = self.bot
        timeout = time.time() + 60*timed   # X minutes from now
        for ha in self.hashtag:
            if ha == None:
                break
            print(' Searching for Hashtag: '+ha)
            bot.get('https://twitter.com/search?f=tweets&vertical=default&q='+ha+'&src=typd')
            time.sleep(2)
            for i in range(1,2):
                bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                time.sleep(1)
                tweets = bot.find_elements_by_class_name('tweet')
                tweetslinks = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print('Hey, good news, seems like '+ str(tweetslinks.__len__())+' tweets were found!, Happy botting :)')
            for link in tweetslinks:
                if time.time() > timeout:
                    break
                if link == None:
                    break
                else:
                    bot.get('https://twitter.com'+link)
                    try:
                        bot.find_element_by_xpath("//button[@data-modal='ProfileTweet-retweet']").click()
                        time.sleep(1)
                        bot.find_element_by_class_name('retweet-action').click()
                        print('// Retweeted //')
                        self.internal_do_log(" + Retweeted [ twitter.com"+link+" ] at")
                        time.sleep(self.internal_do_random_number())
                    except Exception as e:
                        print('--------------------- EXCEPTION START ---------------------')
                        print('Ops, Something went really wrong!')
                        print(e)
                        print('--------------------- EXCEPTION END ---------------------')
                        print('Dont worry, its just a twitter-side problem')
                        print('Resuming...')
                        time.sleep(1)
        print('Times up, see ya next time!')

os.system('cls')
print(' TWITTER BOT v1.0 by @GutiNicolas1 ')
print('[ for academic use only ]')        
print('** BOOTING **')
print('---------------------------------------------------------')


if argv.__len__() != 4:
    print('Please, init me like this: python app.py [username] [password] [hashtag]')
else:
    u = argv[1]
    p = argv[2]
    h = argv[3]
    harr = []
    w = 15 #DEFAULT VALUE FOW WAIT-TIME

    # LOADING FROM CONFIG

    configfile = open("TwitterBOT.ini","r")
    for line in configfile:
        if "#" in line:
            pass
        elif "," in line:
            #DO SMTH WITH ARRAY
            variable = line.split('=')[0]
            i = 0
            if "hashtags" in variable:
                rawstring = line.split('=')[1]
                continueloading = True
                while continueloading:
                    if (rawstring.split(',').__len__()-1) < i:
                        continueloading = False
                    else:
                        harr.append(rawstring.split(',')[i])
                        print("Added "+rawstring.split(',')[i]+" to targeted hashtags")
                        i=i+1
                print(harr)
        elif "=" in line:
            variable = line.split('=')[0]
            value = line.split('=')[1]
            if variable == "username":
                u = value
            elif variable == "waittime":
                w = int(value,10)
                print("Wait time set to: "+str(w))

    # END OF LOADING FROM CONFIG

    notwannaquit = True
    while notwannaquit:
        print('** MAIN MENU **')
        print('[ 1 ] Do Follows')
        print('[ 2 ] Do Likes')
        print('[ 3 ] Do Retweets')
        print('[ 4 ] Do Unfollows')
        print('[ 5 ] Do Unlikes')
        print('[ 6 ] Do Unretweets')
        print('[ 7 ] Do Unfollow accounts not following me')
        print('================')
        print('[ Any Key to Exit ]')
        print('================')
        sw = input('waiting for an option to be chosen...')
        try:
            sw = int(sw,10)
        except Exception as e:
            print('** QUITING **')
            quit()
        notpassing = True
        while notpassing:
            print('** OPTION TIME MENU **')
            print('You want the bot to: ')
            print('[ 1 ] non-stop ')
            print('[ 2 ] run for X minutes')
            opt = input('waiting for an option to be chosen...')
            try:
                opt = int(opt,10)
                notpassing = False
            except Exception as e:
                print('Invalid Option.')
        print('---------------------------------------------------------')
        if sw == 1:
            print
            print('** DOING FOLLOWS **')
            if opt == 1:
                print(' # NON-STOP MODE # ')
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: <PASSWORD>, your password is secure ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] NON-STOP FOLLOWS MODE on [ @"+u+" ] STARTED at")
                if ri.login():
                    while True:
                        ri.target_do_follows()
            elif opt == 2:
                print(' # TIMED MODE # ')
                xtime = input('Please enter the amount of time in MINUTES')
                realtime = int(xtime,10)
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: <PASSWORD> password is <PASSWORD> ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] TIMED FOLLOWS MODE for "+str(realtime)+" minutes on [ @"+u+" ] STARTED at")
                timeout = time.time() + 60*realtime   # X minutes from now time.time() > timeout
                #print('Actual time: '+str(time.time())+'. Stop time: '+str(timeout))
                if ri.login():
                    while time.time() < timeout:
                        doforxmore = (timeout-time.time())/60
                        print('** RUNNING FOR '+str(doforxmore)+' MINUTES **')
                        ri.target_do_follows_timed(doforxmore)
            else:
                #QUIT
                print('Invalid Option.')
        elif sw == 2:
            print('** DOING LIKES **')
            if opt == 1:
                print(' # NON-STOP MODE # ')
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: just kidding, your password is secure ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] NON-STOP LIKES MODE on [ @"+u+" ] STARTED at")
                if ri.login():
                    while True:
                        ri.target_do_likes()
            elif opt == 2:
                print(' # TIMED MODE # ')
                xtime = input('Please enter the amount of time in MINUTES')
                realtime = int(xtime,10)
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: <PASSWORD>, your password is secure ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] TIMED LIKES MODE for "+str(realtime)+" minutes on [ @"+u+" ] STARTED at")
                timeout = time.time() + 60*realtime   # X minutes from now time.time() > timeout
                #print('Actual time: '+str(time.time())+'. Stop time: '+str(timeout))
                if ri.login():
                    while time.time() < timeout:
                        doforxmore = (timeout-time.time())/60
                        print('** RUNNING FOR '+str(doforxmore)+' MINUTES **')
                        ri.target_do_likes_timed(doforxmore)
            else:
                #QUIT
                print('Invalid Option.')
        elif sw == 3:
            print('** DOING RETWEETS **')
            if opt == 1:
                print(' # NON-STOP MODE # ')
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: <PASSWORD>, your password is secure ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] NON-STOP RETWEETS MODE on [ @"+u+" ] STARTED at")
                if ri.login():
                    while True:
                        ri.target_do_retweets()
            elif opt == 2:
                print(' # TIMED MODE # ')
                xtime = input('Please enter the amount of time in MINUTES')
                realtime = int(xtime,10)
                print('** ACCOUT INFO **')
                print('username: '+u)
                print('password: <PASSWORD>, your password is secure ;)')
                print('** TARGETED HASHTAGS **')
                print('[ '+str(harr)+' ]')
                print('---------------------------------------------------------')
                ri = TwitterBot(u,p,harr,w)
                ri.internal_start_log()
                ri.internal_do_log("[-] TIMED RETWEETS MODE for "+str(realtime)+" minutes on [ @"+u+" ] STARTED at")
                timeout = time.time() + 60*realtime   # X minutes from now time.time() > timeout
                #print('Actual time: '+str(time.time())+'. Stop time: '+str(timeout))
                if ri.login():
                    while time.time() < timeout:
                        doforxmore = (timeout-time.time())/60
                        print('** RUNNING FOR '+str(doforxmore)+' MINUTES **')
                        ri.target_do_retweets_timed(doforxmore)
            else:
                #QUIT
                print('Invalid Option.')            
        elif sw == 4:
            print('** DOING UNFOLLOWS **')
        elif sw == 5:
            print('** DOING UNLIKES **')
        elif sw == 6:
            print('** DOING UNRETWEETS **')
        elif sw == 7:
            print('** DOING UNFOLLOW ACCOUNTS NOT FOLLOWING ME **')            
        else:
            print('** QUITING **')



   