示例#1
0
def main():
	m=Mailer()
	limit=0
	user="******"
	f="Log"
	logfile=open("/home/"+user+"/13_python/Log",'a')
	topptips=Tips("topptipset", user)
	topptips.get_data()
	tt=topptips.get_closing()
	while True:
		if topptips.get_closing()!=tt and topptips.internetERROR==False:
			logfile.write("-----------------"+time.ctime()+"topptipsupdate\n")
			topptips.log(tt)
			tt=topptips.get_closing()		
		topptips.get_data()
		
		if topptips.internetERROR==False:
			if topptips.zeroodds==True:
				logfile.write("Jaromir:TT - zero odds spotted!\n")
			else:
				j=Jaromir(topptips.ncrossed, topptips.nodds, topptips.oms)
				j.get_medel()
				Jaromir(topptips.ncrossed, topptips.nodds, topptips.oms).get_medel()
				logfile.write("Jaromir:TT - EXP(500): "+repr(j.exp)+" Chance: "+repr(j.s)+"%\n")
				if j.exp[0]>limit and m.ready()==True:
					#print tt
					m.send_mail(tt,j.exp,j.s)
		else:
			logfile.write("Jaromir:TT - InternetERROR spotted!\n")
		logfile.write("sleep "+time.ctime()+"\n")	
		logfile.close()
		
		time.sleep(60)
		logfile=open(f,'a')
示例#2
0
文件: ack.py 项目: gaccardo/stuff
   def __sendEmail(self, user, subject, type):
      self.m = Mailer('[email protected]', self.c.getValue('MAIL_TO'), self.c.getValue('RELAY'))
      self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type))
      self.l.addInfoLine('Email Sended to itnetworking')

      self.m = Mailer('[email protected]', user, self.c.getValue('RELAY'))
      self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type))
      self.l.addInfoLine('Email Sended to %s' % user)
示例#3
0
 def send(self, subject, content):
     config = ConfigObj("mail.conf", encoding='UTF8')
     mail = Mailer(config['mail.smtp']['addr'],
                   config['mail.smtp']['password'],
                   config['mail.smtp']['smtp'], config['mail.smtp']['port'],
                   '*****@*****.**')
     res = mail.mail(subject, content)
     print(res)
示例#4
0
 def test_send_registration(self):
     sms = Sms(5, "a Cimem: [email protected]\n", "+36209303349")
     mailer = Mailer()
     sender = FakeSender()
     mailer.doSend = sender.send
     mailer.registered(sms)
     with open("testdata/registration_msg") as f:
         expected = f.read()
     self.assertEquals(expected,sender.sent[0].as_string())
示例#5
0
 def test_send_delete(self):
     sms = Sms(5, "m: [email protected]\n", "+36209303349")
     mailer = Mailer()
     sender = FakeSender()
     mailer.doSend = sender.send
     mailer.deleted(sms, "*****@*****.**")
     with open("testdata/delete_msg") as f:
         expected = f.read()
     self.assertEquals(expected,sender.sent[0].as_string())
示例#6
0
 def __init__(self):
     with open("sitelog/log.pickle", "rb") as logfile:
         self.log = pickle.load(logfile)
     self.mailer = Mailer()
     self.url = "https://www.google.de/search?q={}#q={}&start={}"
     self.browser = webdriver.PhantomJS(desired_capabilities=dcap)
     self.headlines_xpath = ".//*[@class='r']"
     self.targets = {
         "Philipp Matthes: Imagination Realization": "philipp+matthes"
     }
示例#7
0
class Rankbot:
    def __init__(self):
        with open("sitelog/log.pickle", "rb") as logfile:
            self.log = pickle.load(logfile)
        self.mailer = Mailer()
        self.url = "https://www.google.de/search?q={}#q={}&start={}"
        self.browser = webdriver.PhantomJS(desired_capabilities=dcap)
        self.headlines_xpath = ".//*[@class='r']"
        self.targets = {
            "Philipp Matthes: Imagination Realization": "philipp+matthes"
        }

    def find_link(self, page, query, target):
        self.browser.get(self.url.format(query, query, page * 10))
        sleep(3)
        headlines = self.browser.find_elements_by_xpath(self.headlines_xpath)
        index = 0
        for headline in headlines:
            index += 1
            if headline.text == target:
                current_page_number = (page * 10) + index
                message = "Found \"" + target + "\" on position " + str(
                    current_page_number)
                print(message)

                self.log.append(current_page_number)
                with open("sitelog/log.pickle", "wb") as logfile:
                    pickle.dump(self.log, logfile)

                self.mailer.send(message)
                headline.click()
                message = "Clicked link. Current URL: " + self.browser.current_url
                sleep(10)
                return True

        return False

    def search_and_click(self):
        for target, query in self.targets.items():
            for page_number in range(15):
                message = "Current search page: " + str(page_number)
                print(message)
                if self.find_link(page=page_number, query=query,
                                  target=target):
                    sleep(60)
                    break
                sleep(60)

    def send_stats(self):
        fig = plt.figure()
        ax = plt.subplot(111)
        ax.plot(self.log)
        save = "sitelog/log.png"
        fig.savefig(save)
        self.mailer.send_image(save)
示例#8
0
def loop():
    session = Driver()
    mailer = Mailer()
    while True:
        message = mailer.get_current_message()
        if (message == "Start" or message == "Continue"):
            try:
                session.like_follow_loop()

            except KeyboardInterrupt:
                mailer.send("Keyboard Interrupt. Bot will exit now.")
                print("Exiting...")
                break
            except socket_error as err:
                raise err
            except Exception as err:
                for frame in traceback.extract_tb(sys.exc_info()[2]):
                    fname, lineno, fn, text = frame
                error = "Error in " + str(fname) + " on line " + str(
                    lineno) + ": " + str(err)
                print(error)
                mailer.send(error)
                pass
        else:
            if (message == "Stop" or message == "Exit"):
                mailer.send("Instagram Bot will exit now.")
                break
            sleep(1)
    def update(self, DownloadEvent):
        print " just got event " + DownloadEvent.name
        episode = DownloadEvent.data['episode']
        message = "Hello this is tvshow Downloader\n" + \
        "I found " + episode.get_name() + " for download\n From season: " + \
        str(episode.get_season()) + "\n Episode number: " + str(episode.get_episode_number()) + "\n"

        message += " the magnet url is:\n " + episode.get_magnet()

        mailer = Mailer( message, "New episode " + episode.get_name(), self.getConfig() )
        mailer.send()
示例#10
0
 def test_send_update(self):
     sms = Sms(5, "a Cimem: [email protected]\n", "+36209303349")
     mailer = Mailer()
     sender = FakeSender()
     mailer.doSend = sender.send
     mailer.updated(sms, "*****@*****.**")
     with open("testdata/update_registerer_msg") as f:
         expected_new = f.read()
     with open("testdata/update_oldaddress_msg") as f:
         expected_old = f.read()
     self.assertEquals(expected_new,sender.sent[0].as_string())
     self.assertEquals(expected_old,sender.sent[1].as_string())
示例#11
0
    def __init__(self):
        # Set up Telegram Message Client
        self.mailer = Mailer()
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')
        self.mailer.sendMessage("Initializing FacebookDriver.")

        Set up virtual display for Raspberry Pi compatibility
        self.display = Xvfb()
        self.display.start()

        # The following (xpath) classes need to be refreshed every now and then.
        # they define, where elements are located on Facebook.

        # Logging in
        self.loginXpath = "//input[@id='email']"
        self.passwordXpath = "//input[@id='pass']"
        # Elements on the hashtag page
        self.containerXpath = "//div[contains(@class, '_1dwg _1w_m')]"
        self.userNameSubXpath = "//span[contains(@class, 'fwb fcg')]"
        # Alias selection
        self.menuSubXpath = "//div[contains(@class, '_8g2')]"
        self.aliasSelectionSubXpath = ".//a[contains(@class, '_55pi _2agf _4o_4 _4jy0 _4jy3 _517h _51sy _59pe _42ft')]"
        self.companySelectionSubXpath = "//div[contains(@class, '_5ghu _alf')]"
        self.alldaycreativeSelectionSubXpath = "//div[contains(@class, ' _5dsl _alf clearfix')]"
        # Commenting
        self.commentButtonSubXpath = "//a[contains(@class, 'comment_link _5yxe')]"
        self.commentInputSubXpath = "//div[contains(@class, '_1p1v')]"
        # Liking
        self.likeButtonSubXpath = "//a[@class='UFILikeLink _4x9- _4x9_ _48-k']"
        self.likeButtonClickedSubXpath = "//a[contains(@class, 'UFILikeLink _4x9- _4x9_ _48-k UFILinkBright')]"


        self.login = input("E-Mail: ")
        self.password = input("Password: "******"render","cartoon","daily","art","design","cinema4d","animation","cg","illustration"]
        self.delay = 30
        self.startUrl = "https://www.facebook.com/login.php"
        self.hashtagPage = "https://www.facebook.com/hashtag/{}"

        # chrome_options = webdriver.ChromeOptions()
        # prefs = {"profile.default_content_setting_values.notifications" : 2}
        # chrome_options.add_experimental_option("prefs",prefs)
        # self.browser = webdriver.Chrome(chrome_options=chrome_options)
        self.browser = webdriver.PhantomJS()
        self.browser.set_window_size(1920,1080)
        self.log = []
示例#12
0
    def __init__(self):
        # Set up Telegram Message Client
        self.mailer = Mailer()

        # Set up virtual display
        if Config.headless_is_available:
            self.display = Xvfb()
            self.display.start()

        # Load history
        try:
            with open("log/followed_users_all_time.pickle", "rb") as f:
                self.followed_accounts = pickle.load(f)
        except:
            with open("log/followed_users_all_time.pickle", "wb") as f:
                self.followed_accounts = {}
                pickle.dump({}, f)
        try:
            with open("log/followed_users.pickle", "rb") as f:
                self.accounts_to_unfollow = pickle.load(f)
        except:
            with open("log/followed_users.pickle", "wb") as f:
                self.accounts_to_unfollow = []
                pickle.dump([], f)

        try:
            with open("log/instagram_username.pickle", "rb") as f:
                self.username = pickle.load(f)
        except:
            key = input("Please enter your username: "******"You must enter a username. Please try again: ")
            with open("log/instagram_username.pickle", "wb") as f:
                pickle.dump(key, f)
            self.username = key
        try:
            with open("log/instagram_pass.pickle", "rb") as f:
                self.password = pickle.load(f)
        except:
            key = input("Please enter your password: "******"You must enter a password. Please try again: ")
            with open("log/instagram_pass.pickle", "wb") as f:
                pickle.dump(key, f)
            self.password = key

        # Final setup
        if Config.headless_is_available:
            self.browser = webdriver.PhantomJS()
        else:
            self.browser = webdriver.Chrome()
        self.browser.set_window_size(1980, 1080)
示例#13
0
 def test_no_extra_lines_in_mail(self):
     with open ("testdata/errordump_utopszkij", "r") as myfile:
         self.utopszkij = myfile.readlines()
     allSms = SmsStorage(self.utopszkij)
     sms = allSms.getValids()[0]
     mailer = Mailer()
     sender = FakeSender()
     mailer.doSend = sender.send
     mailer.registered(sms)
     with open("testdata/utopszkij_msg") as f:
         expected = f.read()
     text = sender.sent[0].as_string()
     self.assertEquals(expected,sender.sent[0].as_string())
示例#14
0
class CertChecker( object ):

   def __init__( self ):
      self.ssh  = SSHConnector( )
      self.conf = Configurator( '/etc//cfg/cert-checker.cfg', 'cert-checker' )
      mailto    = self.conf.getValue('MAILTO').split(',')
      self.mail = Mailer( self.conf.getValue('MAILFROM'), mailto, self.conf.getValue('SMTPRELAY') )

   def __processDays( self ):
      files    = self.conf.getValue('REMOTE_FILES')
      files    = files.split(',')
      server   = self.conf.getValue('SERVER')
      server   = server.split(',')
      server   = Server( server[0], server[1], server[2], server[3], server[4] )
      tmp      = self.conf.getValue('TMP')
      contents = list()

      for file in files:
         self.ssh.getFile( server, file, "%s/" % tmp )
         cont_tmp = open("%s" % file, 'r' )
         expiring = list()

         for line in cont_tmp:
            line = line.strip()
            line = line.split( '|' )
            if int( line[1] ) < int( self.conf.getValue('DAYS') ):
               expiring.append( {'name':line[0], 'days':line[1]} )

         contents.append( { '%s' % (file): expiring } ) 

      return contents

   def startCheck( self ):
      expiring = self.__processDays()
      subject  = "Certificates expiration report"
      body     = "This is an automatic report of certificates that are about to expire\n\n"

      for exp in expiring:
         if len( exp[ exp.keys()[0] ] ) > 0:
            title = exp.keys()[0].split('-')[3].split('.')[0]
            body += "%s\n" % title
            for cert in exp[ exp.keys()[0] ]:
               if int( cert['days'] ) < 0:
                  body += " !! CERTIFICATE EXPIRED %s\n\n" % cert['name']
               else:
                  body += " W CERTIFICATE %s EXPIRES IN %s DAYS\n\n" % ( cert['name'], cert['days'] )

      body += "\n\n\n\nThis email will be sent every Monday at morning\n\n"
      body += "Recipients: %s\n" % self.conf.getValue('MAILTO')

      self.mail.sendMail( subject, body )
示例#15
0
    def __init__(self):

        self.log = logging.getLogger(__name__)

        self.http = urllib3.PoolManager()

        if not os.path.exists(os.path.dirname(self.save_folder)):
            os.mkdir(os.path.dirname(self.save_folder))

        self.log.info('current day is %s', datetime.now().isoformat())
        self.log.info('saving to folder : %s', os.path.abspath(self.save_folder))
        self.log.info('look_forward set to %d days', self.look_forward)

        self.mailer = Mailer(self.log)
示例#16
0
def main():
    server   = prompt('Enter server', 'klimlive.de')
    port     = int(prompt('Enter port', '587'))
    user     = input("Account: ")
    pwd      = getpass("Password: "******"Mail to: ")
    title    = input("Title: ")
    MyMail = Mailer(server, port, user, pwd)
    MyMail.head(toaddr, fromaddr, title)

    print ('To send double press >> Enter')

    while True:
        try:
            line = input()
        except EOFError:
            break
        if not line:
            break
        MyMail.message(line)

    print ('Message length is ' + str(len(line)))

    MyMail.connect()
    if (MyMail.send()):
        print ("Success!")
    else :
        print ("Failed!")

    del MyMail
示例#17
0
class SPSCrawler(object):

    save_folder = './sups/'
    look_forward = 3

    sps_url = 'https://is.sps-prosek.cz/suplovani/prosek/'

    def __init__(self):

        self.log = logging.getLogger(__name__)

        self.http = urllib3.PoolManager()

        if not os.path.exists(os.path.dirname(self.save_folder)):
            os.mkdir(os.path.dirname(self.save_folder))

        self.log.info('current day is %s', datetime.now().isoformat())
        self.log.info('saving to folder : %s', os.path.abspath(self.save_folder))
        self.log.info('look_forward set to %d days', self.look_forward)

        self.mailer = Mailer(self.log)

    def _worker(self):
        look = [(datetime.now() + timedelta(days=x)).strftime('%d%m%Y.pdf') for x in range(self.look_forward)]

        for f in look:
            self.log.debug('working with : %s', f)
            p = self.get_pdf(f)
            if p:
                if p.is_new():
                    self.log.debug('file is NEW')
                    self.mailer.send_mail(p)
                    p.save()

    def get_pdf(self, name: str) -> Union[bool, PDF]:

        url = self.sps_url + name

        self.log.debug('trying to download file: %s', url)

        r = self.http.request('GET', url)

        self.log.info('page status = %d', r.status)

        if r.status != 200:
            return False
        pdf = PDF(name.replace('.pdf', ''), r.data, self.save_folder, self.log)
        self.log.debug('file found with hex: %s', pdf.get_hex())
        return pdf
示例#18
0
文件: sender.py 项目: gaccardo/stuff
class Sender( object ):

   def __init__(self):
      self.logger = Logger(FILE_LOG)
      self.mailer = Mailer(MAIL_FROM, MAIL_TO, RELAY)

   def __hashDate(self):
      return base64.b64encode( time.asctime() )

   def __storeHashedDate(self, hash):
      file_pointer = open(HASH_FILE,'w')
      file_pointer.write(hash)
      file_pointer.close()

      self.logger.addLine('HASH: %s' % hash)

   def __sendEmail(self, hash):
      body = 'HASH: %s\n' % hash

      if self.mailer.sendMail('[CHECKER]', body):
         self.logger.addLine('Email sent')
      else:
         self.logger.addLine('Unable to sent email')

   def main(self):
      hash = self.__hashDate()
      self.__storeHashedDate(hash)
      self.__sendEmail(hash)
    def addMailerFor(self, title, 
                                    selected_transition, 
                                    selected_workflow, 
                                    mail_from_expression, 
                                    mail_header_dtml, 
                                    mail_head_css_dtml,
                                    mail_body_dtml,
                                    message_id_expression=None, 
                                    in_replay_to_expression=None,
                                    mail_to_expression='',
                                    mail_to_list=[], 
                                    mail_to_roles=[], 
                                    mail_to_groups=[], 
                                    mail_cc_expression='', 
                                    mail_cc_list=[], 
                                    mail_cc_roles=[], 
                                    mail_cc_groups=[], 
                                    mail_ccn_expression='', 
                                    mail_ccn_list=[], 
                                    mail_ccn_roles=[], 
                                    mail_ccn_groups=[] ):
                                            
        if not (title and selected_transition and selected_workflow):
            raise Exception("Parameters title, selected_transition, selected_workflow cannot be None ")
        mailer = Mailer(title)
        
        mailer.editMailerForm(mail_from_expression, mail_header_dtml, mail_head_css_dtml, mail_body_dtml,
                                            message_id_expression,in_replay_to_expression,
                                            mail_to_expression, mail_to_list, mail_to_roles, mail_to_groups, 
                                            mail_cc_expression, mail_cc_list, mail_cc_roles, mail_cc_groups, 
                                            mail_ccn_expression, mail_ccn_list, mail_ccn_roles, mail_ccn_groups )
        
        # put insede the dictionary the object
        if not hasattr(self, selected_workflow):            
            _addObject(self, Folder(selected_workflow) )
        
        workflowFolder = getattr(self, selected_workflow)
        if not hasattr(workflowFolder, selected_transition):
            _addObject(getattr(self,selected_workflow), Folder(selected_transition) )        
        
        transitionFolder = getattr(workflowFolder , selected_transition)

        _addObject(transitionFolder, mailer )
示例#20
0
class Driver:
    def __init__(self):
        self.timestep_secs = 10
        self.searcher = Searcher()
        self.composer = Composer()
        self.mailer = Mailer()

    def sleep(self):
        print('==================')
        print('Going to sleep')
        time.sleep(self.timestep_secs)
        print('Have woken up')

    def loop(self):
        while (True):
            self.sleep()

            data = self.searcher.search()
            data = self.composer.compose(data)
            self.mailer.send(data)
示例#21
0
def run():
    session = Driver()
    mailer = Mailer()
    while True:
        try:
            mailer.send(
                "Instagram Bot started. Please send >>Start<< to start")
            loop()
        except socket_error as err:
            if err.errno != errno.ECONNREFUSED:
                raise err
            else:
                session = Driver()
                mailer = Mailer()
    def __init__(self, 
            id, 
            title='',
            description='',
            topics='',
            mailFrom='',
            nameFrom='',
            disclaimer='',
            signature='',
            ):

        """ Initialize an instance of the class """		
        ## parents constructors 
        DefaultDublinCoreImpl.__init__(self, title, description = description)
        self.id = id
        self.topics = string.split(topics,'\n')
        self.disclaimer = disclaimer		
        self.mailer = Mailer(None, mailFrom, nameFrom, signature)
        self.spool = Spool()
        self.users = {}
示例#23
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
#; Copyright 2016 <Carlo>
#; https://github.com/Carelo/
#; Creation date [14.06.2016]

from Mailer import Mailer

server   = 'klimlive.de'
port     = 587
user     = '******'
pwd      = 'AKoBBoxyPkxX7Dk9SCn7'
fromaddr = user
toaddr   = "*****@*****.**"
title    = "test"
msg      = 'hallo test'
MyMail = Mailer(server, port, user, pwd)
MyMail.head(toaddr, fromaddr, title)
MyMail.message(msg)
MyMail.connect()
if (MyMail.send()):
    print ("Success!")
else :
    print ("Failed!")
del MyMail
示例#24
0
 def test_sendmail_fails(self):
     sms = Sms(5, "a Cimem: [email protected]\n", "+36209303349")
     mailer = Mailer()
     mailer.senderprog = ["tests/badscript"]
     with self.assertRaises(ValueError):
         mailer.registered(sms)
示例#25
0
 def test_sendmail_is_missing(self):
     sms = Sms(5, "a Cimem: [email protected]\n", "+36209303349")
     mailer = Mailer()
     mailer.senderprog = ["/nonexistent/binary"]
     with self.assertRaises(OSError):
         mailer.registered(sms)
示例#26
0
from Mailer import Mailer
from configobj import ConfigObj

config = ConfigObj("mail.conf", encoding='UTF8')
mail = Mailer(config['mail.smtp']['addr'], config['mail.smtp']['password'],
              config['mail.smtp']['smtp'], config['mail.smtp']['port'],
              '*****@*****.**')
res = mail.mail('test mail', 'i am a test mail')
print(res)
class Newsletter(PortalFolder,
        PortalContent,
        DefaultDublinCoreImpl,
        ):
	
    """ Plone NewsLetter Class """

    meta_type = 'Newsletter'
    portal_type = 'PloneNewsLetter'

    security = ClassSecurityInfo()
    security.declareObjectPublic()

    manage_options = PortalContent.manage_options
    meta_type = factory_type_information['meta_type'] 

    __implements__ = ( PortalContent.__implements__
                     , DefaultDublinCoreImpl.__implements__
                     )


    ## subscribe and ubsubscribe expressions
    SUB = 'Subscription'
    UNSUB = 'Unsubscription'
    MOD = 'Modify'

    def __init__(self, 
            id, 
            title='',
            description='',
            topics='',
            mailFrom='',
            nameFrom='',
            disclaimer='',
            signature='',
            ):

        """ Initialize an instance of the class """		
        ## parents constructors 
        DefaultDublinCoreImpl.__init__(self, title, description = description)
        self.id = id
        self.topics = string.split(topics,'\n')
        self.disclaimer = disclaimer		
        self.mailer = Mailer(None, mailFrom, nameFrom, signature)
        self.spool = Spool()
        self.users = {}

    def edit(self,
        title,
        description='',
        topics='',
        mailFrom='',
        nameFrom='',
        disclaimer='',
        signature='',
        ):

        """ Edit Newsletter Properties """
        self.editMetadata(title = title, description = description)
        self.topics = string.split(topics,'\n')
        self.disclaimer = disclaimer
        self.mailer.edit(mailFrom, nameFrom, signature)
        ## edit mailhost aswe can't do it in  __init__()
        if self.mailer.mailhost is None:
            self.mailer.mailhost = self.getMailHost()

    security.declarePrivate('manage_afterAdd')
    def manage_afterAdd(self, item, container):
         """ Add self to the workflow and catalog. """
         PortalFolder.manage_afterAdd(self, item, container)
         PortalContent.manage_afterAdd(self, item, container)

    security.declarePrivate('manage_beforeDelete')
    def manage_beforeDelete(self, item, container):
        """ Remove self from the workflow and catalog. """
    	if aq_base(container) is not aq_base(self):
            self.unindexObject()
        PortalFolder.manage_beforeDelete(self, item, container)

#    security.declareProtected(CMFCorePermissions.View, 'view')
#    def view(self, REQUEST):
#        """ List the contents og the newsletter """
#        return self.newsletter_view(self, REQUEST)

    security.declareProtected(CMFCorePermissions.AddPortalContent, 'invokeFactory')
    def invokeFactory( self
            , type_name
            , id
            , RESPONSE=None
            , *args
            , **kw
            ):

        """ Invokes the portal_types tool. """		
        pt = getToolByName( self, 'portal_types' )
        apply( pt.constructContent
            , (type_name, self, id, RESPONSE) + args
            , kw
        )

    def mailerAttr(self, attribute=None) :        
        """ Returns an attribute of mailer, as can't call mailer.attr in ZPT """ 
        return eval('self.mailer.%s' %attribute)

######################################
## User subscription/unsubscription ##
######################################

    def subscribe(
        self,
        firstName='',
        lastName='',
        email='',
        format='',
        ):

        """ User subscription """        
        if email in self.users.keys():
            return 0
        else:
            user = User(firstName, lastName, email, format)
            id = self.spool.addSubscription(user)
            self.confirmSubscription(user, id)
            return 1
        
    def unsubscribe(
        self,
        email='',
        ):
        
        """ User unsubscription """ 
        if email not in self.users.keys():
            return 0
        else:
            user = self.users[email]
            id = self.spool.addUnsubscription(user)
            self.confirmUnsubscription(user, id)
            return 1

    def deluser(self, id):
        """ Delete a user by email """
        if self.users.has_key(id):
            del self.users[id]
            self._p_changed = 1

    def adduser(self, REQUEST):
        """ Add a user """
        user = User(REQUEST['firstName'], REQUEST['lastName'], REQUEST['email'], REQUEST['format'])
        self.users[REQUEST['email']] = user
        self._p_changed = 1

    def moduserformat(self, email, format):
        """ Modify the format for a user """
        if self.users.has_key(email) and format != self.users[email].format:
            self.users[email].format = format
            self._p_changed = 1
	
    def listusers(self):
    	""" List users """
    	result = []
    	for user in self.users.values():
    	    l = [user.name[0], user.name[1], user.email, user.format]
    	    result.append(l)
    	return result

    def getallusers(self):
        """ List self users plus portal users """
        res = {}
        users = self.users
        for member in users.keys():
           res[member] = users[member]
        for member in self.portal_membership.listMembers():
           if member.newsletter:
                user = User(member.fullname, '', member.email, member.newsletter)
                res[member.email] = user
        return res                

#############################
## E-mail posting function ##
#############################

    def sendAll(self, publi, subject, message_txt, message_html):
        """ Send the newsletter to all subscribed members """
        self.mailer.sendAll(publi, self.getallusers(), self.addTitle(subject), message_txt, message_html)

    def sendValidate(self, subject, publication_url):
        """ Send email to reviewers when publication submited """
        roles = self.get_local_roles()
        to=[]
        for r in roles:
            if 'Owner' or 'Manager' or 'Reviewer' in r[1] :
                # Got error if user not defined on CMF acl_users (returns None object)
                try :
                    e = self.portal_membership.getMemberById(r[0]).getProperty('email')
                    to += [e]
                except: pass
        self.mailer.sendValidate(to, subject, publication_url)
              
##########################################
## E-mail (parsing + sending) functions ##
##########################################

    def parseMailSubject(self, mfrom, to, subject):
        """ Parse e-mail subject and eventually send to spool. """
        tokens = string.split(subject)
        ## case 1: mail to confirm unsubscription
        if self.UNSUB in tokens and 'id:' in tokens :
            email = self.spool.checkUnsubscription(subject)
            if email is not None:
                self.unsubscriptionDone(self.users[email])
        ## case 1b: mail to request an unsubscription
        elif self.UNSUB in tokens and 'mail:' in tokens :
            m = re.match(".*mail: ([^ ]*).*", subject)
            if m:
                email = m.group(1)
                self.unsubscribe(email)
            
        ## case 2: mail to confirm subscription 
        elif self.SUB in tokens and 'id:' in tokens :
            user = self.spool.checkSubscription(subject)
            if user is not None:
                self.subscriptionDone(user)
        ## case 3: mail format modification
        elif self.MOD in tokens and 'mail:' in tokens and 'format:' in tokens :
            m = re.match(".*mail: ([^ ]*).*format: ([0-9]).*", subject)
            if m:
                email = m.group(1)
                format = int(m.group(2))
		self.moduserformat(email, format)
		self.welcome(self.users[email])

    def confirmSubscription(self, user, id):
        """ Send e-mail to request user subscription confirmation """
        message = """
You have requested subscription to "%s".
Please confirm your subscription by replying to this mail (keep entire subject)

Thank you for your attention.
""" %self.title
        if hasattr(self, 'subscription_message'):
            message = self.subscription_message
        subject = self.formatConfirmSubject(self.SUB, user, id)
        self.mailer.mailSubscribe(user, subject, message)

    def confirmUnsubscription(self, user, id):
        """ Send e-mail to request user unsubscription confirmation """
        message = """
You have requested unsubscription from "%s".
Please confirm your unsubscription by replying to this mail (keep entire subject)

Thank you for your attention.
""" %self.title
        if hasattr(self, 'unsubscription_message'):
            message = self.unsubscription_message
        subject = self.formatConfirmSubject(self.UNSUB, user, id)
        self.mailer.mailUnsubscribe(user, subject, message)

    def welcome(self, user):
        """ send a welcome message to the newly subscribed user """
        if hasattr(self, 'welcome_release') and hasattr(self, self.welcome_release):
            release = self[self.welcome_release]
            [html, text] = release.getBodies()
            subject = self.addTitle(release.title_or_id())
            self.mailer.mailTo(user, subject, user.format and html or text)

    def subscriptionDone(self, user):
        """ Send e-mail to confirm user subscription """
        message = """
You have been added to "%s".

Thank you for your attention.
""" %self.title
        if hasattr(self, 'confirmation_message'):
            message = self.confirmation_message
        subject = self.formatDoneSubject(self.SUB, user)
        self.mailer.mailSubscribe(user, subject, message)
	self.users[user.email] = user
	self._p_changed = 1
        # Send the welcome release if set
        self.welcome(user)

    def unsubscriptionDone(self, user):
        """ Send e-mail to confirm user unsubscription """
        message = """
You have been removed from "%s".

Thank you for your attention.
""" %self.title
        if hasattr(self, 'rconfirmation_message'):
            message = self.rconfirmation_message
        subject = self.formatDoneSubject(self.UNSUB, user)
        self.mailer.mailUnsubscribe(user, subject, message)
	del self.users[user.email]
	self._p_changed = 1

    def formatConfirmSubject(self, type, user, id):
        """ Returns formated subject to confirm (un)subscription """
        return self.addTitle("""Confirm %s - user: %s - id: %s""" %(type, user.email, id))

    def formatDoneSubject(self, type, user):
        """ Returns formated subject when (un)subscription done """
        return self.addTitle("""%s Done - user: %s""" %(type, user.email))


######################
## Internal Methods ##
######################

    def addTitle(self, subject):
        """ add newsletter title to subject """
        return """[%s] %s""" %(self.title, subject)
        
    def getMailHost(self):
        """ returns mailhost instance """
        root = getToolByName(self, 'portal_url').getPortalObject()
        return getattr(root, 'MailHost') 
示例#28
0
class Driver(object):
    def __init__(self):
        # Set up Telegram Message Client
        self.mailer = Mailer()

        # Set up virtual display
        if Config.headless_is_available:
            self.display = Xvfb()
            self.display.start()

        # Load history
        try:
            with open("log/followed_users_all_time.pickle", "rb") as f:
                self.followed_accounts = pickle.load(f)
        except:
            with open("log/followed_users_all_time.pickle", "wb") as f:
                self.followed_accounts = {}
                pickle.dump({}, f)
        try:
            with open("log/followed_users.pickle", "rb") as f:
                self.accounts_to_unfollow = pickle.load(f)
        except:
            with open("log/followed_users.pickle", "wb") as f:
                self.accounts_to_unfollow = []
                pickle.dump([], f)

        try:
            with open("log/instagram_username.pickle", "rb") as f:
                self.username = pickle.load(f)
        except:
            key = input("Please enter your username: "******"You must enter a username. Please try again: ")
            with open("log/instagram_username.pickle", "wb") as f:
                pickle.dump(key, f)
            self.username = key
        try:
            with open("log/instagram_pass.pickle", "rb") as f:
                self.password = pickle.load(f)
        except:
            key = input("Please enter your password: "******"You must enter a password. Please try again: ")
            with open("log/instagram_pass.pickle", "wb") as f:
                pickle.dump(key, f)
            self.password = key

        # Final setup
        if Config.headless_is_available:
            self.browser = webdriver.PhantomJS()
        else:
            self.browser = webdriver.Chrome()
        self.browser.set_window_size(1980, 1080)

    # Returns nicely formatted timestamp
    def timestamp(self):
        return time.strftime('%a %H:%M:%S') + " "

    def focus(self, element):
        self.browser.execute_script("arguments[0].focus();", element)

    # Checks if a user was followed already
    def user_followed_already(self, user):
        if user in self.followed_accounts:
            return True
        else:
            return False

    # Logs into Instagram automatically
    def login(self):

        self.mailer.send("Logging in.")
        print("Logging in.")
        self.browser.get(Config.start_url)
        sleep(5)

        if (self.browser.current_url == "https://www.instagram.com/"):
            return
        if (self.mailer.get_current_message() == "Pause"):
            self.mailer.send("Bot paused.")
            raise Exception("Bot paused.")
        if (self.mailer.get_current_message() == "Stop"):
            self.mailer.send("Bot stopped.")
            raise Exception("Bot stopped.")

        try:
            username_field = self.browser.find_element_by_name("username")
            username_field.send_keys(self.username)
            password_field = self.browser.find_element_by_name("password")
            password_field.send_keys(self.password)
            password_field.send_keys(Keys.RETURN)
            sleep(10)
            return
        except KeyboardInterrupt:
            return
        except:
            sleep(1)
            self.login()
            return

    # Comments on a picture
    def comment(self):
        sleep(3)
        query = Config.comments[randint(0, len(Config.comments) - 1)]
        say = query.format(self.author(),
                           Config.smileys[randint(0,
                                                  len(Config.smileys) - 1)])
        try:
            comment_field = self.browser.find_element_by_xpath(
                Config.comment_xpath)
            comment_field.send_keys(say)
            comment_field.send_keys(Keys.RETURN)
            self.mailer.send("Commented on " + str(self.author()) +
                             "s picture with: " + say + "\n")
            print("Commented on " + str(self.author()) + "s picture with: " +
                  say)
            sleep(1)
        except KeyboardInterrupt:
            return
        except:
            self.mailer.send("Comment field not found.\n")
            print("Comment field not found.")

    # Searches for a certain topic
    def search(self, query):
        self.mailer.send("Searching for " + query + ".")
        print("Searching for " + query + ".")
        self.browser.get("https://www.instagram.com/explore/tags/" + query +
                         "/")

    # Checks for error which occurs when pictures are removed while
    # switching through
    def error(self):
        try:
            error_message = self.browser.find_element_by_xpath(
                Config.error_xpath)
            self.mailer.send("Page loading error.")
            print("Page loading error.")
            return True
        except KeyboardInterrupt:
            return
        except:
            return False

    # Selects the first picture in a loaded topic screen
    def select_first(self):
        try:
            pictures = self.browser.find_elements_by_xpath(
                Config.first_ele_xpath)
            first_picture = pictures[9]
            self.focus(first_picture)
            first_picture.click()
            return True
        except KeyboardInterrupt:
            return
        except:
            sleep(5)
            return False

    # Switches to the next picture
    def next_picture(self):
        try:
            sleep(1)
            next_button = self.browser.find_element_by_xpath(
                Config.next_button_xpath)
            next_button.click()
            return
        except KeyboardInterrupt:
            return
        except:
            self.browser.get(self.browser.current_url)
            sleep(1)
            if not self.error():
                self.select_first()
            return

    # Loads the authors name
    def author(self):
        try:
            author = self.browser.find_element_by_xpath(Config.author_xpath)
            return str(author.get_attribute("title"))
        except KeyboardInterrupt:
            return
        except:
            self.mailer.send("Author xpath not found.\n")
            print("Author xpath not found.")
            return ""

    # Checks if the post is already liked
    def already_liked(self):
        try:
            full = self.browser.find_element_by_xpath(
                Config.like_button_full_xpath)
            return True
        except:
            return False

    # Likes a picture
    def like(self, topic):
        count = 0
        while self.already_liked() and count < 10:
            self.mailer.send("Post already liked. Skipping.\n")
            print("Post already liked. Skipping.")
            self.next_picture()
            count = count + 1
            sleep(1)
        try:
            self.mailer.send("Liked picture/video by: " + self.author() +
                             ".\n")
            print("Liked picture/video by: " + self.author() + ".")
            like_button = self.browser.find_element_by_xpath(
                Config.like_button_xpath)
            like_button.click()
            sneaksleep = randint(0, 10) + Config.delay
            sleep(sneaksleep)
            return
        except KeyboardInterrupt:
            return
        except:
            sleep(Config.delay)
            self.search(topic)
            self.select_first()
            self.like(topic)
            return

    # Unfollows a user
    def unfollow(self, name):
        self.browser.get("https://www.instagram.com/" + name + "/")
        sleep(3)
        try:
            unfollow_button = self.browser.find_element_by_xpath(
                Config.unfollow_xpath)
            unfollow_button.click()
            self.mailer.send("Unfollowed: " + name + ".\n")
            print("Unfollowed: " + name)
            sleep(2)
        except KeyboardInterrupt:
            return
        except:
            self.mailer.send("Unfollow button not found.\n")
            print("Unfollow button not found.")
            sleep(1)

    # Follows a user
    def follow(self):
        sleep(3)
        try:
            follow = self.browser.find_element_by_xpath(Config.follow_xpath)
            follow.click()
            self.mailer.send("Followed: " + self.author() + "\n")
            print("Followed: " + self.author())
            with open("log/followed_users.pickle", "wb") as userfile:
                pickle.dump(self.accounts_to_unfollow, userfile)
            self.accounts_to_unfollow.append(self.author())
            self.followed_accounts.update({self.author(): self.timestamp()})
            with open("log/followed_users_all_time.pickle", "wb") as userfile:
                pickle.dump(self.followed_accounts, userfile)
            sleep(Config.delay + randint(0, 10))
        except:
            self.mailer.send("Follow button not found.\n")
            print("Follow button not found.")
            sleep(1)

    # Coordinates every function in an endless loop
    def like_follow_loop(self):
        self.login()
        while True:
            for topic_selector in range(len(Config.topics) - 1):
                if (self.mailer.get_current_message() == "Exit"
                        or self.mailer.get_current_message() == "Pause"
                        or self.mailer.get_current_message() == "Stop"):
                    raise Exception('Breaking out of inner loop')
                # Config.open_unfollow_screen()
                # Config.unfollow_via_unfollow_screen()
                self.search(Config.topics[topic_selector])
                self.select_first()
                if (topic_selector % 7 == 0):
                    if (self.mailer.get_current_message() == "Exit"
                            or self.mailer.get_current_message() == "Pause"
                            or self.mailer.get_current_message() == "Stop"):
                        raise Exception('Breaking out of inner loop')
                    if not self.error():
                        self.comment()
                        self.next_picture()
                for likes in range(3):
                    sleep(1)
                    if (self.mailer.get_current_message() == "Exit"
                            or self.mailer.get_current_message() == "Pause"
                            or self.mailer.get_current_message() == "Stop"):
                        raise Exception('Breaking out of inner loop')
                    if not self.error():
                        self.like(Config.topics[topic_selector])
                        self.next_picture()
                for follows in range(3):
                    sleep(1)
                    if not self.error():
                        if (self.mailer.get_current_message() == "Exit"
                                or self.mailer.get_current_message() == "Pause"
                                or self.mailer.get_current_message()
                                == "Stop"):
                            raise Exception('Breaking out of inner loop')
                        self.next_picture()
                        count = 0
                        sleep(3)
                        while self.user_followed_already(
                                self.author()) and count < 10:
                            if (self.mailer.get_current_message() == "Exit"
                                    or self.mailer.get_current_message()
                                    == "Pause"
                                    or self.mailer.get_current_message()
                                    == "Stop"):
                                raise Exception('Breaking out of inner loop')
                            self.mailer.send(
                                self.author() +
                                " was followed already. Skipping picture.")
                            print(self.author() +
                                  " was followed already. Skipping picture.")
                            self.next_picture()
                            count = count + 1
                            sleep(1)
                        self.follow()
                self.mailer.send("Accounts to unfollow: " +
                                 str(len(self.accounts_to_unfollow)))
                print("Accounts to unfollow: " +
                      str(len(self.accounts_to_unfollow)))
                if len(self.accounts_to_unfollow) > 50:
                    for unfollows in range(3):
                        if (self.mailer.get_current_message() == "Exit"
                                or self.mailer.get_current_message() == "Pause"
                                or self.mailer.get_current_message()
                                == "Stop"):
                            raise Exception('Breaking out of inner loop')
                        this_guy = self.accounts_to_unfollow[0]
                        self.unfollow(this_guy)
                        del self.accounts_to_unfollow[0]
示例#29
0
 def actionListener_suite(self):
     if (self.mail.getDestinataires().__len__() > 0):
         self.destroy()
         Mailer(self.mail)
示例#30
0
 def __init__(self):
     self.timestep_secs = 10
     self.searcher = Searcher()
     self.composer = Composer()
     self.mailer = Mailer()
示例#31
0
bucket_name = raw_input("Enter Your Bucket Name: ")
s3_user = raw_input("Enter The S3 Username: "******"Bucket cannot be created or it already exists"
else:
    iam.create_user(s3_user)

user_info = iam.access_key(s3_user)

created_user = user_info[0]
created_access_key = user_info[1]
created_secret_key = user_info[2]

iam.attach_policy(s3_user, bucket_name)

filepath = FileCreator.create_s3_file(bucket_name, created_user, created_access_key, created_secret_key)

body = "Hello there.."
mailer = Mailer("*****@*****.**", "Your bucket details", body, filepath, "s3details.txt")
mailer.attach_attachment()
mailer.send_mail()

print "S3 Bucket: %s" % bucket_name
print "S3 Username: %s" % created_user
print "Access Key Id: %s" % created_access_key
print "Aws Secret Access Key: %s" % created_secret_key
示例#32
0
文件: sender.py 项目: gaccardo/stuff
 def __init__(self):
    self.logger = Logger(FILE_LOG)
    self.mailer = Mailer(MAIL_FROM, MAIL_TO, RELAY)
示例#33
0
文件: ack.py 项目: gaccardo/stuff
class ACK( object ):

   def __init__(self):
      self.c = Configurator('/etc//cfg/ack.conf', 'ack')
      self.l = Logger(self.c.getValue('FILE_LOG'), self.c.getValue('NAME'), self.c.getValue('DEBUG'))
      self.z = ZabbixDB(self.l, self.c.getValue('DB_HOST'), self.c.getValue('DB_USER'), self.c.getValue('DB_PASS'), self.c.getValue('DB_NAME'))

   def __checkUserPIN(self, pin, ffrom):
      users_raw = self.c.getValue('USERS')
      users_lines = users_raw.split(',')

      for user in users_lines:
         self.l.addInfoLine("%s :: %s" % ( user.split('|')[0], user.split('|')[1] ))
         if user.split('|')[0] == ffrom and user.split('|')[1] == pin:
             return True

      return False

   def __clearSubject(self, subject, pipes):
      if pipes:
          self.l.addInfoLine(subject)

          try:
             filtered = subject.split('|')
             self.l.addInfoLine(filtered[0])

             return filtered[1]
          except:
             self.l.addWarningLine('El subject esta mal formado')
         
          return "Mal formed subject"
      else:
          return subject

   def __sendEmail(self, user, subject, type):
      self.m = Mailer('[email protected]', self.c.getValue('MAIL_TO'), self.c.getValue('RELAY'))
      self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type))
      self.l.addInfoLine('Email Sended to itnetworking')

      self.m = Mailer('[email protected]', user, self.c.getValue('RELAY'))
      self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type))
      self.l.addInfoLine('Email Sended to %s' % user)

   def __isException(self, e_from):
      filtered = e_from.split('|')

      for email in filtered:
         if email == e_from:
            return True

      return False
      
   def main(self):
      stdin_raw   = sys.stdin.read()
      stdin_lines = stdin_raw.split('\n')
      KEY         = None
      PIN         = ""
      FROM        = ""
      ACK         = False

      self.l.addInfoLine('---------------------------------')
      for line in stdin_lines:

         if re.search('From ', line):
             FROM = line.split('From ')[1]
             FROM = FROM.split('  ')[0]
             self.l.addInfoLine("From: %s" % FROM)

         if re.search('Subject: ', line):
             SUBJECT = line.split('Subject: ')[1]
             self.l.addInfoLine("Subject: %s" % SUBJECT)
             ack_key = SUBJECT.split(' ')[0]

             if ack_key == 'ACK':
                PIN = SUBJECT.split(' ')[1]
                self.l.addInfoLine("ACK PIN: %s" % PIN)
                ACK = True

         if re.search('KEY: ', line):
             if KEY is None:
                 KEY = line.split('KEY: ')[1]
                 self.l.addInfoLine('KEY: %s' % KEY)

      if ACK:
         if not self.__checkUserPIN(PIN, FROM):
            self.l.addWarningLine('Invalid PIN/USER combination')
            self.l.addWarningLine('User %s has given an incorrect PIN %s' % (FROM, PIN))
            self.__sendEmail(FROM, "USER %s has given an incorrect PIN %s" % (FROM, PIN), False)
         else:
            self.l.addInfoLine('PIN/USER ACCEPTED')

            if self.z.ACK( KEY ):
               self.l.addInfoLine('ACK OK')
               self.__sendEmail(FROM, "ACK! %s" % SUBJECT, True)
            else:
               self.l.addErrorLine('ACK ERROR')

      else:
            if not self.__isException(FROM):
               self.__sendEmail(FROM, "WARNING USER %s MALFORMED EMAIL" % FROM, False)
         
      self.l.addInfoLine('---------------------------------')
示例#34
0
# Load detectors
print("[INFO] loading model...")
# net = cv2.dnn.readNetFromCaffe('models/face_detection/deploy.prototxt.txt, 'models/face_detection/res10_300x300_ssd_iter_140000.caffemodel')
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(
    'models/facial_landmark_prediction/shape_predictor_68_face_landmarks.dat')

# Create screenshots folders if not yet created
screenshots_folder_name = getenv('SCREENSHOTS_FOLDER')
if not os.path.isdir(screenshots_folder_name):
    os.mkdir(screenshots_folder_name)

show_help = False

# Set up SMTP for sending screenshots by email
mailer = Mailer(getenv("MAIL_ADDRESS"), getenv("MAIL_PW"))

# Cache list of drawables
categories = getCategoryNames()
current_category = categories[0]
current_category_index = 0
category_item_count = getCategoryItemCount(current_category)

# Change drawable based on blink count
drawableIndex = 0


def nextCategory():
    global current_category_index, current_category, category_item_count, drawableIndex
    current_category_index += 1
    if current_category_index >= len(categories):
示例#35
0
s3_user = raw_input("Enter The S3 Username: "******"Bucket cannot be created or it already exists"
else:
    iam.create_user(s3_user)

user_info = iam.access_key(s3_user)

created_user = user_info[0]
created_access_key = user_info[1]
created_secret_key = user_info[2]

iam.attach_policy(s3_user, bucket_name)

filepath = FileCreator.create_s3_file(bucket_name, created_user,
                                      created_access_key, created_secret_key)

body = "Hello there.."
mailer = Mailer("*****@*****.**", "Your bucket details", body,
                filepath, "s3details.txt")
mailer.attach_attachment()
mailer.send_mail()

print "S3 Bucket: %s" % bucket_name
print "S3 Username: %s" % created_user
print "Access Key Id: %s" % created_access_key
print "Aws Secret Access Key: %s" % created_secret_key
示例#36
0
class Driver(object):
    def __init__(self):
        # Set up Telegram Message Client
        self.mailer = Mailer()
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')
        self.mailer.sendMessage("Initializing FacebookDriver.")

        Set up virtual display for Raspberry Pi compatibility
        self.display = Xvfb()
        self.display.start()

        # The following (xpath) classes need to be refreshed every now and then.
        # they define, where elements are located on Facebook.

        # Logging in
        self.loginXpath = "//input[@id='email']"
        self.passwordXpath = "//input[@id='pass']"
        # Elements on the hashtag page
        self.containerXpath = "//div[contains(@class, '_1dwg _1w_m')]"
        self.userNameSubXpath = "//span[contains(@class, 'fwb fcg')]"
        # Alias selection
        self.menuSubXpath = "//div[contains(@class, '_8g2')]"
        self.aliasSelectionSubXpath = ".//a[contains(@class, '_55pi _2agf _4o_4 _4jy0 _4jy3 _517h _51sy _59pe _42ft')]"
        self.companySelectionSubXpath = "//div[contains(@class, '_5ghu _alf')]"
        self.alldaycreativeSelectionSubXpath = "//div[contains(@class, ' _5dsl _alf clearfix')]"
        # Commenting
        self.commentButtonSubXpath = "//a[contains(@class, 'comment_link _5yxe')]"
        self.commentInputSubXpath = "//div[contains(@class, '_1p1v')]"
        # Liking
        self.likeButtonSubXpath = "//a[@class='UFILikeLink _4x9- _4x9_ _48-k']"
        self.likeButtonClickedSubXpath = "//a[contains(@class, 'UFILikeLink _4x9- _4x9_ _48-k UFILinkBright')]"


        self.login = input("E-Mail: ")
        self.password = input("Password: "******"render","cartoon","daily","art","design","cinema4d","animation","cg","illustration"]
        self.delay = 30
        self.startUrl = "https://www.facebook.com/login.php"
        self.hashtagPage = "https://www.facebook.com/hashtag/{}"

        # chrome_options = webdriver.ChromeOptions()
        # prefs = {"profile.default_content_setting_values.notifications" : 2}
        # chrome_options.add_experimental_option("prefs",prefs)
        # self.browser = webdriver.Chrome(chrome_options=chrome_options)
        self.browser = webdriver.PhantomJS()
        self.browser.set_window_size(1920,1080)
        self.log = []

    def focus(self,element):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        # print("Focusing element on position: ("+str(element.location["x"])+","+str(element.location["y"])+")")
        self.browser.execute_script("arguments[0].focus();", element)

    def loginToFacebook(self):
        self.mailer.sendMessage("Logging in to facebook.")
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        print("Logging in to facebook")
        self.browser.get(self.startUrl)
        sleep(3)
        loginField = self.browser.find_element_by_xpath(self.loginXpath)
        loginField.send_keys(self.login)
        passField = self.browser.find_element_by_xpath(self.passwordXpath)
        passField.send_keys(self.password)
        passField.send_keys(Keys.RETURN)
        sleep(10)
        return

    def getPostsFromHashtagPage(self,topic):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        print("Getting posts from hashtag: #"+topic)
        self.browser.get(self.hashtagPage.format(topic))
        sleep(5)
        for scrollDownAmount in range(20):
            if self.mailer.getCurrentMessage() == "Stop":
                raise Exception('Stopped by telegram.')

            self.mailer.sendMessage("Getting posts from hashtag page. ("+str(scrollDownAmount)+"/20)")
            self.browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            sleep(5)
        return self.browser.find_elements_by_xpath(self.containerXpath)

    def sendStats(self):
        fig = plt.figure()
        ax = plt.subplot(111)
        ax.plot(self.log)
        save = "likelog/log.png"
        fig.savefig(save)
        self.mailer.send_image(save)

    def selectAlldaycreative(self,menu):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        self.focus(menu)
        menu.click()
        sleep(3)

        selection = menu.find_element_by_xpath(self.companySelectionSubXpath)
        selection.click()
        sleep(3)

        selections = menu.find_elements_by_xpath(self.alldaycreativeSelectionSubXpath)
        selection = selections[1]
        selection.click()
        sleep(3)

        return True

    def likeEverything(self):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')
        self.mailer.sendMessage("Liking everything on the hashtag page.")

        print("Liking everything on the hashtag page.")
        selections = self.browser.find_elements_by_xpath(self.likeButtonSubXpath)
        self.log.append(len(selections))
        totalSelections = len(selections)
        currentSelection = 1
        for selection in selections:
            self.mailer.sendMessage("Liking post: ("+str(currentSelection)+"/"+str(totalSelections)+")")
            self.focus(selection)
            selection.click()
            currentSelection += 1
            sleep(5)

    # def commentEverything(self):
    #     if self.mailer.getCurrentMessage() == "Stop":
    #         raise Exception('Stopped by telegram.')
    #
    #     print("Commenting everything on the hashtag page.")
    #     selections = self.browser.find_elements_by_xpath(self.commentButtonSubXpath)
    #     for selection in selections:
    #         self.focus(selection)
    #         selection.click()
    #         sleep(1)
    #     selections = self.browser.find_elements_by_xpath(self.commentInputSubXpath)
    #     for selection in selections:
    #         self.focus(selection)
    #         query = Tell.comment[randint(0,len(Tell.comment)-1)]
    #         say = query.format(Tell.smiley[randint(0,len(Tell.smiley)-1)])
    #         selection.send_keys(say)
    #         selection.send_keys(Keys.RETURN)
    #         sleep(10)

    # def author(self,post):
    #     return post.find_element_by_xpath(self.userNameSubXpath).text

    # def commentPost(self,post):
    #     print("Commenting post.")
    #     selection = post.find_element_by_xpath(self.commentButtonSubXpath)
    #     self.focus(selection)
    #     selection.click()
    #     sleep(1)
    #
    #     query = Tell.comment[randint(0,len(Tell.comment)-1)]
    #     say = query.format(self.author(post),Tell.smiley[randint(0,len(Tell.smiley)-1)])
    #
    #     selection = post.find_element_by_xpath(self.commentInputSubXpath)
    #     selection.send_keys(say)
    #     selection.send_keys(Keys.RETURN)

    def returnAvailableMenus(self):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        return self.browser.find_elements_by_xpath(self.aliasSelectionSubXpath)

    def doSomeMagic(self):
        if self.mailer.getCurrentMessage() == "Stop":
            raise Exception('Stopped by telegram.')

        self.loginToFacebook()
        while True:
            for topic in self.topics:
                self.mailer.sendMessage("Selecting next topic: "+topic)
                posts = self.getPostsFromHashtagPage(topic)
                # availableMenus = self.returnAvailableMenus()
                # currentmenu = 1
                # totalMenus = len(availableMenus)
                # for menu in availableMenus:
                #     self.mailer.sendMessage("Switching to Alldaycreative. ("+str(currentMenu)+"/"+str(totalMenus)+")")
                #     self.selectAlldaycreative(menu)
                #     currentMenu += 1
                self.likeEverything()
                self.sendStats()
示例#37
0
 def __init__( self ):
    self.ssh  = SSHConnector( )
    self.conf = Configurator( '/etc//cfg/cert-checker.cfg', 'cert-checker' )
    mailto    = self.conf.getValue('MAILTO').split(',')
    self.mail = Mailer( self.conf.getValue('MAILFROM'), mailto, self.conf.getValue('SMTPRELAY') )
示例#38
0
from Mailer import Mailer
import time

# python-os-environ-object
mail_configuration = {
    'from': '',  # From mail account
    'to': '',  # Receiver @dinahosting.com account
    'server': '',  # From mail server
    'pwd': '',  # From mail password
    'port': '',  # From port
    'subject': ''  # Mail subject
}

feng_configuration = {
    'user': '',  # Feng user
    'pwd': '',  # Feng password
    'domain': ''  # Feng domain
}

feng_client = Client(feng_configuration['user'], feng_configuration['pwd'],
                     feng_configuration['domain'])
mail_client = Mailer(mail_configuration['from'], mail_configuration['to'],
                     mail_configuration['server'], mail_configuration['pwd'],
                     mail_configuration['port'], mail_configuration['subject'])

while True:
    tasks = feng_client.getTasks()
    if tasks:
        mail_client.send(tasks)
    time.sleep(600)
示例#39
0
文件: main.py 项目: Michelin01jp/YMS
# -*- coding:utf-8 -*-
from PageComparer import PageComparer
from TwiBot import TwiBot
from Mailer import Mailer
import datetime

page = PageComparer("http://www.tomakomai-ct.ac.jp/i/urgency/index.php", "index.html")

if page.isChanged() == False:
    exit()

page.sync()

now = datetime.datetime.now()

mailer = Mailer("*****@*****.**")
body = now.strftime("%Y/%m/%d %H:%M:%S") + u"\n学生連絡ページの更新を検知しました。\n" + u"確認をお願いします。\n" + u"http://www.tomakomai-ct.ac.jp/i/urgency/index.php\n\n" + u"---\nYotedori Monitoring System by @mktakuya"

mailer.createMessage(u"Y-ALERT(緊急嵐闥ハり速報)", body)
mailer.sendMessage()

twibot = TwiBot("yotedori_bot")
twibot.post(body)

示例#40
0
文件: acs.py 项目: gaccardo/stuff
class ACSwitcher( object ):

   def __init__( self, acs, last ):
      self.acs  = acs
      self.last = last
      self.mail = Mailer( '', '', '')

   def __changeAC( self, new_ac ):
      f_pointer = open(self.last, 'w')
      f_pointer.write(new_ac)
      f_pointer.close()

   def __lastAC( self ):
      f_pointer = open(self.last, 'r')
      f_buffer  = f_pointer.read()
      f_pointer.close()

      last_ac = f_buffer.strip()

      for ac in self.acs:
         if ac.getHost() == last_ac:
            return last_ac

   def __newAC( self, last_ac ):
      for ac in self.acs:
         if ac.getHost() != last_ac:
            return ac.getHost()

   def __getName( self, host ):
      for ac in self.acs:
         if ac.getDeviceByHost( host ) is not None:
            return ac.getDeviceByHost( host )

   def __sendMail( self, result, last_ac, new_ac, errors ):
      subject = ""
      body    = ""

      if result == 0:
         subject = "AC Switch: Succesfull"
         body     = "###########################\n"
         body    += "#        AC Switch        #\n"
         body    += "###########################\n"
         body    += " * Result: Successfull\n"
         body    += " * Last AC: %s\n" % self.__getName(last_ac)
         body    += " * New AC: %s\n" % self.__getName(new_ac)
         body    += "###########################\n"
      else:
         subject = "AC Switch: Failed"
         body     = "###########################\n"
         body    += "#        AC Switch        #\n"
         body    += "###########################\n"
         body    += " * Result: Failed\n"
         body    += " * Last AC: %s\n" % self.__getName(last_ac)
         body    += " * New AC: %s\n" % self.__getName(new_ac)
         body    += "###########################\n"

         print 'ERRORS:' if len(errors) > 0 else ''
         for error in errors:
            body += " * %s\n" % error


      print subject
      print body

      self.mail.sendMail( subject, body )
      self.mall.sendMail( subject, body )

   def runCheck( self ):
      last_ac = self.__lastAC()
      new_ac  = self.__newAC( last_ac )
      bad     = 0
      errors  = list()

      for ac in self.acs:
         comp1 = True if ac.processOID(".1.3.6.1.4.1.9839.2.1.1.3.0")[0] == '1' else False
         comp2 = True if ac.processOID(".1.3.6.1.4.1.9839.2.1.1.2.0")[0] == '1' else False

         if ac.getHost() == last_ac:
            if comp1 == True or comp2 == True:
               bad += 1
               errors.append( "Prev AC shouldn't have any compressors working, but it have" )

         if ac.getHost() != last_ac:
            if not (comp1 == True or comp2 == True):
               errors.append( "New AC should have at least one of its compressors working, but it haven't" )
               bad += 1

      self.__sendMail( bad, last_ac, new_ac, errors )
      self.__changeAC( new_ac )
示例#41
0
from FacebookDriver import Driver
from Mailer import Mailer
from time import sleep
import traceback
import sys

if __name__ == "__main__":
    session = Driver()
    mailer = Mailer()
    mailer.sendMessage("Facebook Bot started. Please send >>Start<< to start")
    while True:
        message = mailer.getCurrentMessage()
        if (message == "Start" or message == "Continue"):
            try:
                session.doSomeMagic()
            # except Exception as err:
            #     for frame in traceback.extract_tb(sys.exc_info()[2]):
            #         fname, lineno, fn, text = frame
            #     error = "Error in "+str(fname)+" on line "+str(lineno)+": "+str(err)
            #     print(error)
            #     mailer.sendMessage(error)
            #     pass
            except KeyboardInterrupt:
                mailer.sendMessage("Keyboard Interrupt. Bot will exit now.")
                print("Exiting...")
                break
        else:
            if (message == "Stop" or message == "Exit"):
                mailer.sendMessage("Facebook Bot will exit now.")
                break
            sleep(1)
示例#42
0
from EmployeeDataReader import EmployeeDataReader
from MailBody import MailBody
from Mailer import Mailer
from Constants import Constants
import sys
import os

if __name__ == '__main__':
	empdata_reader = EmployeeDataReader(Constants.MAPPING_FILE)
	header, employee_data_list = empdata_reader.read()
	sender = raw_input("Enter mail_id of sender(Eg: <asdf>@thoughtworks.com) : ")
	mailer = Mailer(sender)
	e = None
	try:
		employees_without_bill_file = []
		for employee_data in employee_data_list:
			bill_file_name = Constants.BILLS_DIR + os.sep + "%s.pdf" % employee_data.mobile_number
			if os.path.exists(bill_file_name):
				mailer.send_mail(('*****@*****.**' % employee_data.employee_id), 'Your bill for the month between %s and %s' % (employee_data.start_date, employee_data.end_date), MailBody(header, employee_data).html(), bill_file_name)
			else:
				employees_without_bill_file.append(employee_data)
		new_header = ["employee_id", "name", "mobile_number"]
		if len(employees_without_bill_file) > 0:
			mailer.send_mail(sender, 'Employees who did not get their bill', MailBody(new_header, employees_without_bill_file).html())
	except Exception as exception:
		e = exception
	finally:
		mailer.close()
	if e != None:
		raise e
示例#43
0
文件: acs.py 项目: gaccardo/stuff
 def __init__( self, acs, last ):
    self.acs  = acs
    self.last = last
    self.mail = Mailer( '', '', '')
示例#44
0
from Mailer import Mailer
import urllib.request

mailer = Mailer()


class Parser:
    # Load data from enviromental variables, set the parse URL and load all the parsed URLs
    def __init__(self, parseURL):
        print('Initializing parser')
        self.ads = []
        file = open('url_list.txt', 'r')
        lines = file.readlines()
        file.close()
        for line in lines:
            url = line.strip('\n')
            if url:
                self.ads.append(url)

        self.url = parseURL
        self.adType = self.url.split('/')[3]
        print('Parser successfully initialized!')

    # Add URL to the list of URLs
    def addAd(self, adURL):
        print('Adding ad for {}'.format(adURL))
        self.ads.append(adURL)
        file = open('url_list.txt', 'a')
        file.write("{}\n".format(adURL))
        file.close
示例#45
0
from EmployeeDataReader import EmployeeDataReader
from MailBody import MailBody
from Mailer import Mailer
from Constants import Constants
import sys
import os

if __name__ == '__main__':
    empdata_reader = EmployeeDataReader(Constants.MAPPING_FILE)
    header, employee_data_list = empdata_reader.read()
    sender = raw_input(
        "Enter mail_id of sender(Eg: <asdf>@thoughtworks.com) : ")
    mailer = Mailer(sender)
    e = None
    try:
        employees_without_bill_file = []
        for employee_data in employee_data_list:
            bill_file_name = Constants.BILLS_DIR + os.sep + "%s.pdf" % employee_data.mobile_number
            if os.path.exists(bill_file_name):
                mailer.send_mail(
                    ('*****@*****.**' % employee_data.employee_id),
                    'Your bill for the month between %s and %s' %
                    (employee_data.start_date, employee_data.end_date),
                    MailBody(header, employee_data).html(), bill_file_name)
            else:
                employees_without_bill_file.append(employee_data)
        new_header = ["employee_id", "name", "mobile_number"]
        if len(employees_without_bill_file) > 0:
            mailer.send_mail(
                sender, 'Employees who did not get their bill',
                MailBody(new_header, employees_without_bill_file).html())
示例#46
0
class Driver(object):
    def __init__(self):
        # Set up Telegram Message Client
        self.mailer = Mailer()

        # Set up virtual display
        if Config.headless_is_available:
            self.display = Xvfb()
            self.display.start()

        # Load history
        try:
            with open("log/interacting_users.pickle", "rb") as f:
                self.interacting_users = pickle.load(f)
        except:
            with open("log/interacting_users.pickle", "wb") as f:
                self.interacting_users = []
                pickle.dump([], f)
        try:
            with open("log/hashtags.pickle", "rb") as f:
                self.hashtags = pickle.load(f)
        except:
            with open("log/hashtags.pickle", "wb") as f:
                self.hashtags = {}
                for h in Config.topics:
                    self.hashtags[h] = 2
                pickle.dump(self.hashtags, f)
        try:
            with open("log/actionList.pickle", "rb") as f:
                self.actionList = pickle.load(f)
        except:
            with open("log/actionList.pickle", "wb") as f:
                self.actionList = {}
                pickle.dump({}, f)
        try:
            with open("log/followed_users_all_time.pickle", "rb") as f:
                self.followed_accounts = pickle.load(f)
        except:
            with open("log/followed_users_all_time.pickle", "wb") as f:
                self.followed_accounts = {}
                pickle.dump({}, f)
        try:
            with open("log/followed_users.pickle", "rb") as f:
                self.accounts_to_unfollow = pickle.load(f)
        except:
            with open("log/followed_users.pickle", "wb") as f:
                self.accounts_to_unfollow = []
                pickle.dump([], f)

        try:
            with open("log/instagram_username.pickle", "rb") as f:
                self.username = pickle.load(f)
        except:
            key = input("Please enter your username: "******"You must enter a username. Please try again: ")
            with open("log/instagram_username.pickle", "wb") as f:
                pickle.dump(key, f)
            self.username = key
        try:
            with open("log/instagram_pass.pickle", "rb") as f:
                self.password = pickle.load(f)
        except:
            key = input("Please enter your password: "******"You must enter a password. Please try again: ")
            with open("log/instagram_pass.pickle", "wb") as f:
                pickle.dump(key, f)
            self.password = key

        # Final setup
        if Config.headless_is_available:
            # self.browser = webdriver.PhantomJS(desired_capabilities=dcap)
            self.browser = webdriver.PhantomJS()

        else:
            self.browser = webdriver.Chrome("./chromedriver")
        self.browser.set_window_size(1980, 1080)

    # Returns nicely formatted timestamp
    def timestamp(self):
        return time.strftime('%a %H:%M:%S') + " "

    def focus(self, element):
        self.browser.execute_script("arguments[0].focus();", element)

    # Checks if a user was followed already
    def user_followed_already(self, user):
        if user in self.followed_accounts:
            return True
        else:
            return False

    # Logs into Instagram automatically
    def login(self):

        self.mailer.send("Logging in.")
        print("Logging in.")
        self.browser.get(Config.start_url)
        sleep(5)

        if (self.browser.current_url == "https://www.instagram.com/"):
            return
        if (self.mailer.get_current_message() == "Pause"):
            self.mailer.send("Bot paused.")
            raise Exception("Bot paused.")
        if (self.mailer.get_current_message() == "Stop"):
            self.mailer.send("Bot stopped.")
            raise Exception("Bot stopped.")

        try:
            username_field = self.browser.find_element_by_name("username")
            username_field.send_keys(self.username)
            password_field = self.browser.find_element_by_name("password")
            password_field.send_keys(self.password)
            password_field.send_keys(Keys.RETURN)
            sleep(10)
            return
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.login')
            sleep(1)
            self.login()
            return

    # Comments on a picture
    def comment(self, topic):
        sleep(3)
        query = Config.comments[randint(0, len(Config.comments) - 1)]
        say = query.format(self.author(),
                           Config.smileys[randint(0,
                                                  len(Config.smileys) - 1)])
        try:
            comment_field = self.browser.find_element_by_xpath(
                Config.comment_xpath)
            comment_field.send_keys(say)
            comment_field.send_keys(Keys.RETURN)
            self.mailer.send("Commented on " + str(self.author()) +
                             "s picture with: " + say + "\n")
            print("Commented on " + str(self.author()) + "s picture with: " +
                  say)

            if self.author() not in self.actionList.keys():
                value = {
                    "type": "comment",
                    "time": self.timestamp(),
                    "topic": topic
                }
                self.actionList[self.author()] = [value]
            else:
                value = {
                    "type": "comment",
                    "time": self.timestamp(),
                    "topic": topic
                }
                authorActions = self.actionList[self.author()]
                authorActions.append(value)
                self.actionList[self.author()] = authorActions
            with open("log/actionList.pickle", "wb") as userfile:
                pickle.dump(self.actionList, userfile)

            sleep(1)
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.comment')
            self.mailer.send("Comment field not found.\n")
            print("Comment field not found.")

    # Searches for a certain topic
    def search(self, query):
        self.mailer.send("Searching for " + query + ".")
        print("Searching for " + query + ".")
        self.browser.get("https://www.instagram.com/explore/tags/" + query +
                         "/")

    # Checks for error which occurs when pictures are removed while
    # switching through
    def error(self):
        try:
            error_message = self.browser.find_element_by_xpath(
                Config.error_xpath)
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Page loading error')
            print("Page loading error.")
            return True
        except KeyboardInterrupt:
            return
        except:
            return False

    # Selects the first picture in a loaded topic screen
    def select_first(self):
        try:
            pictures = self.browser.find_elements_by_xpath(
                Config.first_ele_xpath)
            print("Found " + str(len(pictures)) + " pictures.")
            first_picture = None
            if len(pictures) > 9:
                first_picture = pictures[9]
            else:
                first_picture = pictures[len(pictures) - 1]
            self.focus(first_picture)
            first_picture.click()
            sleep(1)
            return True
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png',
                                   'Exception in self.select_first')
            sleep(5)
            return False

    # Switches to the next picture
    def next_picture(self):
        try:
            sleep(1)
            next_button = self.browser.find_element_by_xpath(
                Config.next_button_xpath)
            next_button.click()
            return
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png',
                                   'Exception in self.next_picture')
            self.browser.execute_script("window.history.go(-1)")
            sleep(5)
            self.select_first()
            sleep(1)

    # Loads the authors name
    def author(self):
        try:
            author = self.browser.find_element_by_xpath(Config.author_xpath)
            return str(author.get_attribute("title"))
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.author')
            self.mailer.send("Author xpath not found.\n")
            print("Author xpath not found.")
            return ""

    # Checks if the post is already liked
    def already_liked(self):
        try:
            full = self.browser.find_element_by_xpath(
                Config.like_button_full_xpath)
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Image was already liked.')
            return True
        except:
            return False

    def on_post_page(self):
        try:
            full = self.browser.find_element_by_xpath(Config.next_button_xpath)
            return False
        except:
            return True

    # Likes a picture
    def like(self, topic):
        count = 0
        while self.already_liked() and count < 10:
            self.mailer.send("Post already liked. Skipping.\n")
            print("Post already liked. Skipping.")
            self.next_picture()
            if self.on_post_page():
                self.browser.save_screenshot('error.png')
                self.mailer.send_image('error.png',
                                       'Accidently swapped to post page.')
                return
            count = count + 1
            sleep(1)
        try:
            self.mailer.send("Liked picture/video by: " + self.author() +
                             ".\n")
            print("Liked picture/video by: " + self.author() + ".")

            if self.author() not in self.actionList.keys():
                value = {
                    "type": "like",
                    "time": self.timestamp(),
                    "topic": topic
                }
                self.actionList[self.author()] = [value]
            else:
                value = {
                    "type": "like",
                    "time": self.timestamp(),
                    "topic": topic
                }
                authorActions = self.actionList[self.author()]
                authorActions.append(value)
                self.actionList[self.author()] = authorActions
            with open("log/actionList.pickle", "wb") as userfile:
                pickle.dump(self.actionList, userfile)

            like_button = self.browser.find_element_by_xpath(
                Config.like_button_xpath)
            like_button.click()
            sneaksleep = randint(0, 10) + Config.delay
            sleep(sneaksleep)
            return
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.like')
            sleep(Config.delay)
            self.search(topic)
            self.select_first()
            self.like(topic)
            return

    # Unfollows a user
    def unfollow(self, name):
        self.browser.get("https://www.instagram.com/" + name + "/")
        sleep(3)
        try:
            unfollow_button = self.browser.find_element_by_xpath(
                Config.unfollow_xpath)
            unfollow_button.click()
            self.mailer.send("Unfollowed: " + name + ".\n")
            print("Unfollowed: " + name)
            sleep(2)
        except KeyboardInterrupt:
            return
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.unfollow')
            self.mailer.send("Unfollow button not found.\n")
            print("Unfollow button not found.")
            sleep(1)

    # Follows a user
    def follow(self, topic):
        sleep(3)
        try:
            follow = self.browser.find_element_by_xpath(Config.follow_xpath)
            follow.click()
            self.mailer.send("Followed: " + self.author() + "\n")
            print("Followed: " + self.author())
            with open("log/followed_users.pickle", "wb") as userfile:
                pickle.dump(self.accounts_to_unfollow, userfile)

            if self.author() not in self.actionList.keys():
                value = {
                    "type": "follow",
                    "time": self.timestamp(),
                    "topic": topic
                }
                self.actionList[self.author()] = [value]
            else:
                value = {
                    "type": "follow",
                    "time": self.timestamp(),
                    "topic": topic
                }
                authorActions = self.actionList[self.author()]
                authorActions.append(value)
                self.actionList[self.author()] = authorActions
            with open("log/actionList.pickle", "wb") as userfile:
                pickle.dump(self.actionList, userfile)

            self.accounts_to_unfollow.append(self.author())
            self.followed_accounts.update({self.author(): self.timestamp()})
            with open("log/followed_users_all_time.pickle", "wb") as userfile:
                pickle.dump(self.followed_accounts, userfile)
            sleep(Config.delay + randint(0, 10))
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png', 'Exception in self.follow')
            self.mailer.send("Follow button not found.\n")
            print("Follow button not found.")
            sleep(1)

    def open_unfollow_screen(self):
        self.browser.get(Config.account_url)
        sleep(2)
        heart = self.browser.find_element_by_xpath(Config.following_xpath)
        heart.click()
        sleep(2)

    def check_follows(self):
        try:
            sections = self.browser.find_elements_by_xpath(
                Config.sections_xpath)
            print(str(len(sections)) + " Sections found.")
        except:
            print("Sections not found.")
            return
        users = []
        for element in sections:
            profile = element.find_element_by_xpath(Config.local_name_xpath)
            name = profile.get_attribute("title")
            users.append(name)
        for user in users:
            if user not in self.interacting_users:
                if user not in self.actionList.keys():
                    self.mailer.send("New interaction discovered with: " +
                                     user +
                                     ", but we have no further information.")
                    sleep(1)
                else:
                    actions = self.actionList[user]
                    self.mailer.send(
                        "New interaction discovered with: " + user +
                        ", and we have logged our interactions on him:")
                    sleep(1)
                    string = ""
                    for action in actions:
                        string += "Type: " + action[
                            "type"] + ", Time: " + action[
                                "time"] + ", Topic: " + action[
                                    "topic"] + " ... "
                        self.hashtags[action["topic"]] += 1
                    self.mailer.send(string)
                    sleep(1)
                self.interacting_users.append(user)
                with open("log/interacting_users.pickle", "wb") as userfile:
                    pickle.dump(self.interacting_users, userfile)
        return

    def store_hashtags(self):
        try:
            sections = self.browser.find_elements_by_xpath(
                Config.hashtags_xpath)
            for section in sections:
                all_hashtags = self.extract_hash_tags(section.text)
                for h in all_hashtags:
                    if h in self.hashtags:
                        self.hashtags[h] = self.hashtags[h] + 0.01
                    else:
                        self.hashtags[h] = 0.01
            with open("log/hashtags.pickle", "wb") as f:
                pickle.dump(self.hashtags, f)
        except:
            self.browser.save_screenshot('error.png')
            self.mailer.send_image('error.png',
                                   'Exception in self.store_hashtags')
            pass

    def extract_hash_tags(self, s):
        return set(part[1:] for part in s.split() if part.startswith('#'))

    # Coordinates every function in an endless loop
    def like_follow_loop(self):
        self.login()
        while True:
            self.open_unfollow_screen()
            self.check_follows()

            top_hashtags = sorted(self.hashtags.keys(),
                                  key=lambda k: self.hashtags[k],
                                  reverse=True)[:20]
            top_hashtags_values = []
            for hashtag in top_hashtags:
                top_hashtags_values.append(self.hashtags[hashtag])
            self.mailer.send_stats(top_hashtags_values,
                                   top_hashtags,
                                   caption="Top 20 hashtags")
            low_hashtags = sorted(self.hashtags.keys(),
                                  key=lambda k: self.hashtags[k],
                                  reverse=True)[-20:]
            low_hashtags_values = []
            for hashtag in low_hashtags:
                low_hashtags_values.append(self.hashtags[hashtag])
            self.mailer.send_stats(low_hashtags_values,
                                   low_hashtags,
                                   caption="Low 20 hashtags")
            sleep(1)

            for topic_selector in range(len(top_hashtags) - 1):
                if (self.mailer.get_current_message() == "Exit"
                        or self.mailer.get_current_message() == "Pause"
                        or self.mailer.get_current_message() == "Stop"):
                    raise Exception('Breaking out of inner loop')
                self.search(top_hashtags[topic_selector])
                print("Selecting first picture.")
                self.select_first()
                if (topic_selector % 7 == 2):
                    if (self.mailer.get_current_message() == "Exit"
                            or self.mailer.get_current_message() == "Pause"
                            or self.mailer.get_current_message() == "Stop"):
                        raise Exception('Breaking out of inner loop')
                    if not self.error():
                        self.comment(top_hashtags[topic_selector])
                        self.store_hashtags()
                        self.next_picture()
                for likes in range(3):
                    sleep(1)
                    if (self.mailer.get_current_message() == "Exit"
                            or self.mailer.get_current_message() == "Pause"
                            or self.mailer.get_current_message() == "Stop"):
                        raise Exception('Breaking out of inner loop')
                    if not self.error():
                        self.like(top_hashtags[topic_selector])
                        self.store_hashtags()
                        self.next_picture()
                for follows in range(3):
                    sleep(1)
                    if not self.error():
                        if (self.mailer.get_current_message() == "Exit"
                                or self.mailer.get_current_message() == "Pause"
                                or self.mailer.get_current_message()
                                == "Stop"):
                            raise Exception('Breaking out of inner loop')
                        self.next_picture()
                        count = 0
                        sleep(3)
                        while self.user_followed_already(
                                self.author()) and count < 10:
                            if (self.mailer.get_current_message() == "Exit"
                                    or self.mailer.get_current_message()
                                    == "Pause"
                                    or self.mailer.get_current_message()
                                    == "Stop"):
                                raise Exception('Breaking out of inner loop')
                            self.mailer.send(
                                self.author() +
                                " was followed already. Skipping picture.")
                            print(self.author() +
                                  " was followed already. Skipping picture.")
                            self.next_picture()
                            count = count + 1
                            sleep(1)
                        self.follow(top_hashtags[topic_selector])
                        self.store_hashtags()
                self.mailer.send("Accounts to unfollow: " +
                                 str(len(self.accounts_to_unfollow)))
                print("Accounts to unfollow: " +
                      str(len(self.accounts_to_unfollow)))
                if len(self.accounts_to_unfollow) > 50:
                    for unfollows in range(3):
                        if (self.mailer.get_current_message() == "Exit"
                                or self.mailer.get_current_message() == "Pause"
                                or self.mailer.get_current_message()
                                == "Stop"):
                            raise Exception('Breaking out of inner loop')
                        this_guy = self.accounts_to_unfollow[0]
                        self.unfollow(this_guy)
                        del self.accounts_to_unfollow[0]
示例#47
0
from Rankbot import Rankbot
from Mailer import Mailer
from time import sleep
import traceback
import sys
import pickle

if __name__=="__main__":
    rankbot = Rankbot()
    mailer = Mailer()
    mailer.send("Ranking Bot started. Please send >>Start<< to start")
    while True:
        message = mailer.get_current_message()

        if (message == "Start" or message == "Continue" or message == ""):
            try:
                rankbot.search_and_click()
            except KeyboardInterrupt:
                mailer.send("Keyboard Interrupt. Bot will exit now.")
                print("Exiting...")
                break
            except Exception as err:
                for frame in traceback.extract_tb(sys.exc_info()[2]):
                    fname, lineno, fn, text = frame
                error = "Error in "+str(fname)+" on line "+str(lineno)+": "+str(err)
                mailer.send(error)
                print(error)
                sleep(1)
                pass

        elif (message == "Stats"):