コード例 #1
0
def send_update(log_file_path,
                program,
                email_params):
    try:
        subject = 'Daily ' + program + ' update'
        sender = email_params['sender']
        enc_pwd = email_params['enc_pwd']
        recipient = email_params['recipient']
        f = open(log_file_path, 'rb')
        data = [line for line in f]
        body = str(len(data)) + \
               ' lines of data in log, here are the last 10 lines:<br/>'
        body += '<br/>'.join([line for line in data[-10:]])
        f.close()
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        body = 'Error getting email body... ' + \
               ''.join('!! ' + line for line in lines)
    try:
        send_mail.mail(sender, enc_pwd, recipient, subject, body)
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        err = 'Error sending update email!: '  + \
              ''.join('!! ' + line for line in lines)
        log(log_file_path, program, subject, err, True)
コード例 #2
0
def read_excel():
    wb = load_workbook(dir_path + '/credentials/excel.xlsx')
    ws = wb.active
    print('Reading excel')
    for row in ws.iter_rows(min_row=2, values_only=True):
        try:

            if(row[4]==str(today)):
                fname = row[0]
                lname = row[1]
                name = fname + " " + lname
                mobile = row[2]
                email = row[3]
                whatapp_contact_list = []  # contacts to send message
                for i in range(5, len(row)):
                    whatapp_name = row[i].split('_')

                    whatapp_name = '"' + ' '.join(whatapp_name) + '"'

                    whatapp_contact_list.append(whatapp_name)

                print("It's " + fname + "'s Happy B'day ")

                try:
                    print('Sending SMS ...')
                    send_sms.sendPostRequest(str(mobile), fname)  # send sms
                    print('Sms sent.')
                except:
                    print('Unable to send Sms.')

                try:
                    print('Sending mail ...')
                    send_mail.mail(email, fname)  # send mail
                    print('Mail sent.')
                except:
                    print('Unable to send mail')

                try:
                    print('Sending wish on facebook ...')
                    fb_msg.send_fmsg(fname, lname, whatapp_contact_list)  # facebook message
                    print('Facebook message sent.')
                except:
                    print('Unable to send Facebook message')

                try:
                    print('Sending wish on whatsapp ...')
                    whatsapp_msg.send_wmsg(whatapp_contact_list, fname)  # whatsapp message
                    print('Whatsapp message sent.')
                except:
                    print('Unable to send Whatsapp message')

        except:
            print('Done Scanning Birthdays!')
コード例 #3
0
def read_csv():

    with open(dir_path + '/credentials/csv.csv') as f:
        reader = csv.reader(f, delimiter=',')

        for row in reader:
            try:
                if(row[4]==str(today)):
                    fname = row[0]
                    lname = row[1]
                    name = fname + " " + lname
                    mobile = row[2]
                    email = row[3]
                    whatapp_contact_list = []  # contacts to send message
                    for i in range(5, len(row)):
                        whatapp_name = row[i].split('_')

                        whatapp_name = '"' + ' '.join(whatapp_name) + '"'

                        whatapp_contact_list.append(whatapp_name)

                    print("It's " + fname + "'s Happy B'day ")

                    try:
                        print('Sending SMS ...')
                        send_sms.sendPostRequest(str(mobile), fname)  # send sms
                        print('Sms sent.')
                    except:
                        print('Unable to send Sms.')

                    try:
                        print('Sending mail ...')
                        send_mail.mail(email, fname)  # send mail
                        print('Mail sent.')
                    except:
                        print('Unable to send mail')

                    try:
                        print('Sending wish on facebook ...')
                        fb_msg.send_fmsg(fname, lname, whatapp_contact_list)  # facebook message
                        print('Facebook message sent.')
                    except:
                        print('Unable to send Facebook message')

                    try:
                        print('Sending wish on whatsapp ...')
                        whatsapp_msg.send_wmsg(whatapp_contact_list, fname)  # whatsapp message
                        print('Whatsapp message sent.')
                    except:
                        print('Unable to send Whatsapp message')
            except:
                print('No one have birthday today :(')
コード例 #4
0
def read_txt():

    with open(dir_path + '/credentials/text.txt', mode='r') as f:
        readContent = f.readlines()
    for j in range(len(readContent)):
        if(readContent[j].split()[4] == str(today)):
            Person = readContent[j].split()
            fname = Person[0]
            lname = Person[1]
            name = Person[0] + " " + Person[1]
            mobile = Person[2]
            email = Person[3]
            whatapp_contact_list = []  # contacts to send message
            for i in range(5, len(Person)):
                whatapp_name = Person[i].split('_')

                whatapp_name = '"' + ' '.join(whatapp_name) + '"'

                whatapp_contact_list.append(whatapp_name)

            print("It's " + fname + "'s Happy B'day ")

            try:
                print('Sending SMS ...')
                send_sms.sendPostRequest(str(mobile), fname)  # send sms
                print('Sms sent.')
            except:
                print('Unable to send Sms.')

            try:
                print('Sending mail ...')
                send_mail.mail(email, fname)  # send mail
                print('Mail sent.')
            except:
                print('Unable to send mail')

            try:
                print('Sending wish on facebook ...')
                fb_msg.send_fmsg(fname, lname, whatapp_contact_list)  # facebook message
                print('Facebook message sent.')
            except:
                print('Unable to send Facebook message')

            try:
                print('Sending wish on whatsapp ...')
                whatsapp_msg.send_wmsg(whatapp_contact_list, fname)  # whatsapp message
                print('Whatsapp message sent.')
            except:
                print('Unable to send Whatsapp message')

        else:
            print('No one have birthday today :(')
コード例 #5
0
def perform(operation):
    if operation == 1:
        # read from camera
        capture_image.start()
        text = image_to_text.text_from_image('temp/captureCropped.jpg')
        print(text)
        text_to_speech.speak(text)

    elif operation == 2:
        # send mail
        os.system("say 'waht is the mail id'")
        sendto = speech_to_text.get_text()
        sendto = sendto.replace(" ", "")

        os.system("say 'waht is the subject of the mail?'")
        subject = speech_to_text.get_text()

        os.system("say 'waht should i write in the mail?'")
        mailtext = speech_to_text.get_text()

        send_mail.mail(sendto, subject, mailtext)

    elif operation == 3:
        # what am i looking at => object identification
        capture_image.capture()
        captioning.dense_cap('temp/capture.jpg')

    elif operation == 4:
        # where am I? scene captionong
        capture_image.capture()
        captioning.scene_cap('temp/capture.jpg')

    elif operation == 5:
        # Wikipedia search
        os.system("say 'waht should i search about on the web'")
        subject = speech_to_text.get_text()
        subject = subject.rstrip()
        article = wiki_search.get_article(subject)
        article = article.rstrip()
        text_to_speech.speak(article)

    elif operation == 6:
        # who is in the frame
        face_recognisation.recognise()

    elif operation == 7:
        play.playmp3()

    # TODO add news apikey
    else:
        "do nothing, return to app loop"
コード例 #6
0
def start_item():
    i = 0
    while (i < int(days_text.get())):

        i += 1
        new_bot = AmazonBot()
        current_price = new_bot.start_scrape(link_text.get())

        if (float(current_price.replace(',', '.')) <
                float(price_text.get()) / 1000):
            send_mail.mail(email_text.get(), link_text.get())

            #Alert
            alert_label = Label(root,
                                text='Price Dropped! Mail Sent!!',
                                font=('bold', 14),
                                pady=20)
            alert_label.place(x=110, y=320)
            break
        time.sleep(60 * 60 * 24)
コード例 #7
0
def compute():
    # take URL from user (temporary, later to be modified to able to work with a database)
    #ebay_URL 
    #amazon_URL
    #flipkart_URL

    with open('amazon.txt','r') as obj:
        amazon_URL = obj.readline()
        amazon_product_name = obj.readline()

    with open('flipkart.txt','r') as obj:
        flipkart_URL = obj.readline()
        flipkart_product_name = obj.readline()

    with open('ebay.txt','r') as obj:
        ebay_URL = obj.readline()
        ebay_product_name = obj.readline()


    # take user price requirement (temporary, later to be modified to able to work with a database)
    # user_price

    amazon_product_req_price = float(2900)
    flipkart_product_req_price = float(2100)
    ebay_product_req_price = float(700)


    ##-----------------------------------------------------------------------------------------------------
    # compare user price with scrapped price 
    # if condition is met "SEND EMAIL"

    amz = compare(amazon_product_req_price,amazon_price.amazon_price(amazon_URL))
    flp = compare(flipkart_product_req_price,flipkart_price.flipkart_price(flipkart_URL))
    eby = compare(ebay_product_req_price,ebay_price.ebay_price(ebay_URL))

    if amz[0]:
        send_mail.mail('*****@*****.**','Hari',amazon_product_name,'Amazon','₹' + str(amz[1]),amazon_URL)
    if flp[0]:
        send_mail.mail('*****@*****.**','Hari',flipkart_product_name,'Flipkart','₹' + str(flp[1]),flipkart_URL)
    if eby[0]:
        send_mail.mail('*****@*****.**','Hari',ebay_product_name,'Ebay',str(eby[1]) + '$',ebay_URL)
    

    global duration

    #updates duration for next time 
    duration = calc_time.time_diff()

    #writes back the current time to keep track for next time 
    with open('time.txt','w') as obj:
        obj.write(datetime.now().strftime("%d/%m/%Y, %H:%M:%S"))
コード例 #8
0
import smtplib

speech=pyttsx3.init()
speech.say("say something")
speech.runAndWait()
r1=sr.Recognizer()
r2=sr.Recognizer()
with sr.Microphone() as source:
    print('what would you like to do?')
    audio=r1.listen(source)
    try:
        command=r1.recognize_google(audio)
        print(command)
        if 'mail' in command:
            from send_mail import mail
            mail()
        elif 'whatsapp' in command:
            from whatsapp_with_python import whatsapp_msg
           
        elif 'news' in command:
            from news_headlines import news
            
        elif 'events' in command:
            from events import events
            
        elif 'youtube' in command:
            from youtube import youtube
            
        elif 'music' in command:
            from music import music
        elif 'assistant' in command:
コード例 #9
0
ファイル: subscriber.py プロジェクト: sayansil/kamwali-pi
        print("Subscribed.")

    def start_listening(self):
        self.client.loop_start()
        print("Listening...")
           
    def stop_listening(self):
        self.client.loop_stop()
        self.client.disconnect()
        print("Stopped Listening")

new_sub = subscriber()
new_sub.start_listening()

while True:
    try:
        while True:
            pass
    except KeyboardInterrupt:
        new_sub.stop_listening()
        print("Exiting")
        break
    except Exception as e:
        new_sub.stop_listening()
        del(new_sub)
        mail("Abnormal exit | MQTT service", str(e))
        time.sleep(10)
        new_sub = subscriber()
        new_sub.start_listening()
    
コード例 #10
0
ファイル: task2.py プロジェクト: CaiMingRui/Seeing_WEIBOCOM
    try:
        browser.find_element_by_xpath(
            '//a[@suda-uatrack="key=click comments&value=click:singl_weibo:1"]'
        )
        print "找到更多评论"
        return True
    except:
        try:
            browser.find_element_by_link_text(u'下一页')
            return True
        except:
            return False


def star():
    global trytime
    if (trytime <= 5):
        trytime = trytime + 1
        try:
            init_spider()
            load_req()
        except Exception, error:
            star()
    else:
        send_mail.mail(Title='task2有问题',
                       message=Exception + ':' + error + '\n' + '尽快维护')


if __name__ == '__main__':
    star()
コード例 #11
0
ファイル: main.py プロジェクト: sayansil/kamwali-pi
def round2(val):
    return str(round(float(val), 2))


try:
    while (True):
        time.sleep(5)
        diagnostics = ""

        ip = "IP address: " + os.popen('hostname -I').readline().strip()
        ping = "Network status: " + "Active" if os.system(
            "ping -c 1 8.8.8.8 >/dev/null 2>&1") == 0 else "Inactive"
        tot_mem, used_mem, free_mem = map(
            int,
            os.popen('free -t -m').readlines()[-1].split()[1:])
        ram = "RAM Usage: " + round2(100 * used_mem / tot_mem) + "%"
        cpu = "CPU Usage: " + round2(
            os.popen(
                "grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }'"
            ).readline()) + "%"
        timestamp = datetime.datetime.now().strftime("%A, %d %B %Y %I:%M%p")
        diagnostics = timestamp + '\n' + ip + '\n' + ping + '\n' + ram + '\n' + cpu + '\n'

        print(diagnostics + '\n')
except KeyboardInterrupt:
    print("Exited normally.")
except Exception as e:
    print("Exiting...")
    mail("Abnormal exit | Diagnostics", str(e))
コード例 #12
0
        return iio


if __name__ == '__main__':
    try:
        erro = star()
        times = 0
        rangetime = 10
        while ('Connection refused' in erro or 'Timeout' in erro
               or 'Timeout loading page after 300000ms' in erro):
            browser.quit()
            times = times + 1
            if (times > 3):
                rangetime = 30
            if (time > 4):
                send_mail.mail(Title='task1-5出现问题',
                               message='mmp,我睡了一个小时,试了4次都失败了,你来搞一下吧')
                sys.exit()
            print "我睡" + str(rangetime) + "分钟"
            for i in range(0, rangetime):
                time.sleep(60)
                print "还有" + str(rangetime - i) + "分钟"
            try:
                erro = star()
            finally:
                print 'again'
                # send_mail.mail(Title='task1-5出现问题', message='未知错误,错误内容为:'+str(erro))
    except Exception, erro:
        print Exception, "xiaxiaxia:xiaxiaxia", erro
        send_mail.mail(Title='task1-5出现问题', message='未知错误,错误内容为:' + str(erro))
コード例 #13
0
def mailer():
    user_email = request.args.get('user_email')
    complain_details = request.args.get('complain_details')
    response = mail(complain_details, user_email)
    return jsonify(response)
コード例 #14
0
ファイル: task3.py プロジェクト: CaiMingRui/Seeing_WEIBOCOM
def get_page(year,name,url,id):

    print "开始进入"+str(id),url
    browser.get(url)
    home={}
    follow={}
    info={}
    Wuser = {}
    Wuser["Uid"] = id
    try:
        WebDriverWait(browser, 30, 3).until(lambda browser:browser.find_element_by_xpath('//div[@class="PCD_counter"]/div[@class="WB_innerwrap"]/table[@class="tb_counter"]/tbody/tr/td/a[@class="t_link S_txt1"]'))
    except:
        try:
            infoBtn = browser.find_element_by_xpath("//a[contains(@href,'info?mod=pedit_more')]/span")
        except:
            infoBtn = browser.find_element_by_xpath("//a[contains(@href,'about')]/span")
        infoBtn.click()
        try:
            browser.refresh()
            WebDriverWait(browser, 30, 3).until(lambda browser: browser.find_element_by_xpath("//a[contains(@href,'follow?from=page')]"))
        except:
            print '??'
        browser.back()
        try:
            browser.refresh()
            WebDriverWait(browser, 30, 3).until(lambda browser:browser.find_element_by_xpath('//div[@class="PCD_counter"]/div[@class="WB_innerwrap"]/table[@class="tb_counter"]/tbody/tr/td/a[@class="t_link S_txt1"]'))
        except:
            print '???'
    try:
        allckick = browser.find_element_by_link_text(u'全部')
    except:
        try:
            allckick = browser.find_element_by_link_text('全部')
            allckick.click()
        except:
            try:
                browser.refresh()
                WebDriverWait(browser, 30, 3).until(lambda browser: browser.find_element_by_xpath('//a[@suda-data="key=tblog_profile_new&value=weibo_all"]'))
                allckick = browser.find_element_by_link_text('全部')
                allckick.click()
            except:
                try:
                    allckick = browser.find_element_by_xpath('//a[@suda-data="key=tblog_profile_new&value=weibo_all"]')
                    allckick.click()
                except:
                    url_all = url+'?profile_ftype=1&is_all=1#_0'
                    browser.get(url_all)

    try:
        browser.refresh()
        WebDriverWait(browser, 30, 3).until(lambda browser:browser.find_element_by_xpath('//div[@class="PCD_counter"]/div[@class="WB_innerwrap"]/table[@class="tb_counter"]/tbody/tr/td/a[@class="t_link S_txt1"]'))
    except:
        print '????'
    print "进入主页..."

    time.sleep(random.random()+10*random.random())
    homepage = browser.page_source
    homeurl = browser.current_url
    try:
        Wuser["follow_num"] = browser.find_element_by_xpath("//a[contains(@href,'follow?from=page')]/strong").text
        Wuser["fans_num"] = browser.find_element_by_xpath("//a[contains(@href,'follow?relate=fans')]/strong").text
        Wuser["weibo_num"] = browser.find_element_by_xpath("//a[contains(@href,'home?from=page')]/strong").text
    except:
        send_mail.mail()
        print '有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒有毒'
        Wuser["follow_num"] = 'none'
        Wuser["fans_num"] = 'none'
        Wuser["weibo_num"] = 'none'
    if(id.isdigit()):
        Wuser["is_bigV"] = 'N'
    else:
        Wuser["is_bigV"] = 'Y'
    Wuser["repo_num"] = 0
    Wuser["comment_num"] = 0
    Wuser["like_num"] = 0
    repos = browser.find_elements_by_xpath("//span[@node-type='forward_btn_text']/span/em[2]")
    for r in repos:
        print 'r:',r
        if(r.text.isdigit()):
            Wuser["repo_num"] = Wuser["repo_num"]+int(r.text)
        else:
            Wuser["repo_num"] = Wuser["repo_num"]+0

    comments = browser.find_elements_by_xpath("//span[@node-type='comment_btn_text']/span/em[2]")
    for c in comments:
        print 'c:',c
        if(c.text.isdigit()):
            Wuser["comment_num"] = Wuser["comment_num"]+int(c.text)
        else:
            Wuser["comment_num"] = Wuser["comment_num"]+0

    like = browser.find_elements_by_xpath("//span[@node-type='like_status']/span/em[2]")
    for l in like:
        print "l:",l
        if(l.text.isdigit()):
            Wuser["like_num"] = Wuser["like_num"]+int(l.text)
        else:
            Wuser["like_num"] = Wuser["like_num"]+0
    print "主页获取完毕..."
    try:
        infoBtn = browser.find_element_by_xpath("//a[contains(@href,'info?mod=pedit_more')]/span")
    except:
        infoBtn = browser.find_element_by_xpath("//a[contains(@href,'about')]/span")
    infoBtn.click()
    try:
        browser.refresh()
        WebDriverWait(browser, 30, 3).until(lambda browser:browser.find_element_by_xpath("//a[contains(@href,'follow?from=page')]"))
    except:
        print '?????'
    print "进入资料页..."
    time.sleep(random.random()+10*random.random())
    infopage = browser.page_source
    infourl = browser.current_url
    print "资料页获取完毕..."
    try:
        followBtn = browser.find_element_by_xpath("//a[contains(@href,'follow?from=page')]")
        followBtn.click()
    except:
        browser.get(infourl.replace('about','follow'))
    try:
        browser.refresh()
        WebDriverWait(browser, 30, 3).until(lambda browser:browser.find_element_by_xpath('//div[@class="WB_frame"]/div[@id="plc_main"]'))
    except:
        print "??????"
    print "进入关注页..."
    time.sleep(random.random()+10*random.random())
    followpage = browser.page_source
    followurl = browser.current_url
    print "关注获取完毕..."
    home['page']=homepage
    home['url']=homeurl
    follow['page']=followpage
    follow['url']=followurl
    info['page']=infopage
    info['url']=infourl
    print Wuser
    with open("./weibo_user/"+str(id)+".json",'w') as hh:
        oo = json.dumps(Wuser,ensure_ascii=False)
        hh.write(oo)
        print id,"写入完毕"
    if(Downloadpage != '-1'):
        if not os.path.exists("./user_page/"+str(id)+"/"):
            os.mkdir("./user_page/"+str(id))
        with open("./user_page/"+str(id)+"/home.json",'w') as h:
            baby1 = json.dumps(home,ensure_ascii=False)
            h.write(baby1)
        with open("./user_page/"+str(id)+"/info.json",'w') as i:
            baby2 = json.dumps(info,ensure_ascii=False)
            i.write(baby2)
        with open("./user_page/"+str(id)+"/follow.json",'w') as f:
            baby3 = json.dumps(follow,ensure_ascii=False)
            f.write(baby3)
コード例 #15
0
ファイル: task3.py プロジェクト: CaiMingRui/Seeing_WEIBOCOM


def star(choose = '-1'):
    Downloadpage = choose
    init_spider()
    load_req()

if __name__ == '__main__':
    try:
        star()
    except Exception,error:
        times = 0
        rangetime = 10
        while ('Connection refused' in erro or 'Timeout' in erro or 'Timeout loading page after 300000ms' in erro):
            browser.quit()
            times = times + 1
            if (times > 3):
                rangetime = 30
            if (time > 4):
                send_mail.mail(Title='task3出现问题', message='mmp,我睡了一个小时,试了4次都失败了,你来搞一下吧')
                sys.exit()
            print "我睡" + str(rangetime) + "分钟"
            for i in range(0, rangetime):
                time.sleep(60)
                print "还有" + str(rangetime - i) + "分钟"
            try:
                erro = star()
            finally:
                print 'again'
コード例 #16
0
 def book_seat(self,
               seat_id: str,
               room,
               number,
               start,
               end,
               date=str(datetime.date.today())):
     """
     提交预定座位表单
     :param seat_id: 座位ID
     :param room: 房间名称
     :param number: 座位编号
     :param start: 使用开始时间
     :param end:  使用结束时间
     :param date: 预定日期, 默认为当日
     :return: 预定到座位或已经有预约导致无法下单返回False其他情况返回True
     """
     post_data = {
         'SYNCHRONIZER_TOKEN': self.book_token,
         'SYNCHRONIZER_URI': '/',
         'date': date,
         "seat": seat_id,
         "start": str(start),  # 480 ---> 8:00
         "end": str(end)  # 1320 ---> 22:00
     }
     try:
         resp = self.s.post(url=book_seat_self_url,
                            data=post_data,
                            headers=self.headers,
                            timeout=30.0)
     except Exception as err:
         self.log.logger.critical('预定座位请求发送失败 ERROR_MSG: {}'.format(err))
         return True
     else:
         if resp.status_code != 200:
             self.log.logger.error('预定失败, 请求错误! HTTP_CODE: {}'.format(
                 resp.status_code))
         html = resp.content.decode("utf-8")
         root = etree.HTML(html)
         try:
             temp_book_status = root.xpath(
                 '''//div[@class="layoutSeat"]/dl''')
             book_status = temp_book_status[0][0].text
         except Exception as err:
             self.log.logger.error('获取预定信息错误 ERROR_MSG: {}'.format(err))
             return True
         else:
             if book_status == '系统已经为您预定好了':
                 self.log.logger.info('预定成功, 请登录系统查看预约信息!')
                 mail(subject='预定成功',
                      content='座位信息: {R} - {N} 请登陆系统核查确认!'.format(R=room,
                                                                  N=number))
                 return False
             else:
                 fail_msg = temp_book_status[0].xpath(
                     '//span/text()[last()]')[-1]
                 if fail_msg == '已有1个有效预约,请在使用结束后再次进行选择':
                     self.log.logger.error('预定失败: < {} >'.format(fail_msg))
                     mail(subject='预定失败', content=fail_msg)
                     return False
                 else:
                     self.log.logger.error(
                         '预定失败: < {} >, 继续尝试其他座位!'.format(fail_msg))
                     return True