示例#1
0
def handle_request(r):
    ftp.init(r)
    buildlogs.init(r)
    build.build_all(r, build_rpm)
    report.send_report(r, is_src=False)
    ftp.flush()
    notify.send(r)
示例#2
0
def handle_request(r):
    ftp.init(r)
    buildlogs.init(r)
    build.build_all(r, build_rpm)
    report.send_report(r, is_src = False)
    ftp.flush()
    notify.send(r)
示例#3
0
def check_cloud():
    url_list = [
        'aHR0cDovLzQzLjEzNS45MC4yMy8=', 'aHR0cHM6Ly9zaGl6dWt1Lm1sLw==',
        'aHR0cHM6Ly9jZi5zaGl6dWt1Lm1sLw=='
    ]
    for i in url_list:
        url = str(base64.b64decode(i).decode())
        try:
            requests.get(url=url, verify=False, timeout=10)
        except Exception as err:
            logger.debug(str(err))
            continue
        else:
            info = ['Default', 'HTTPS', 'CloudFlare']
            logger.info(
                str(info[url_list.index(i)]) +
                " Server Check OK\n--------------------\n")
            return i
    logger.info("\n云端地址全部失效, 请检查网络!")
    try:
        send('WSKEY转换', '云端地址失效. 请联系作者或者检查网络.')
    except Exception as err:
        logger.debug(str(err))
        logger.info("通知发送失败")
    sys.exit(1)
示例#4
0
def check_cloud():  # 方法 云端地址检查
    url_list = [
        'aHR0cDovLzQzLjEzNS45MC4yMy8=', 'aHR0cHM6Ly9zaGl6dWt1Lm1sLw==',
        'aHR0cHM6Ly9jZi5zaGl6dWt1Lm1sLw=='
    ]  # URL list Encode
    for i in url_list:  # for循环 url_list
        url = str(base64.b64decode(i).decode())  # 设置 url地址 [str]
        try:  # 异常捕捉
            requests.get(url=url, verify=False,
                         timeout=10)  # HTTP[GET]请求 超时 10秒
        except Exception as err:  # 异常捕捉
            logger.debug(str(err))  # 调试日志输出
            continue  # 循环继续
        else:  # 分支判断
            info = ['Default', 'HTTPS', 'CloudFlare']  # 输出信息[List]
            logger.info(
                str(info[url_list.index(i)]) +
                " Server Check OK\n--------------------\n")  # 标准日志输出
            return i  # 返回 ->i
    logger.info("\n云端地址全部失效, 请检查网络!")  # 标准日志输出
    try:  # 异常捕捉
        send('WSKEY转换', '云端地址失效. 请联系作者或者检查网络.')  # 推送消息
    except Exception as err:  # 异常捕捉
        logger.debug(str(err))  # 调试日志输出
        logger.info("通知发送失败")  # 标准日志输出
    sys.exit(1)  # 脚本退出
示例#5
0
def get_qltoken(username, password):  # 方法 用于获取青龙 Token
    logger.info("Token失效, 新登陆\n")  # 日志输出
    url = "http://127.0.0.1:{0}/api/user/login".format(
        port)  # 设置青龙地址 使用 format格式化自定义端口
    payload = {'username': username, 'password': password}  # HTTP请求载荷
    payload = json.dumps(payload)  # json格式化载荷
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }  # HTTP请求头 设置为 Json格式
    try:  # 异常捕捉
        res = requests.post(url=url, headers=headers,
                            data=payload)  # 使用 requests模块进行 HTTP POST请求
        token = json.loads(
            res.text)["data"]['token']  # 从 res.text 返回值中 取出 Token值
    except Exception as err:  # 异常捕捉
        logger.debug(str(err))  # Debug日志输出
        logger.info("青龙登录失败, 请检查面板状态!")  # 标准日志输出
        text = '青龙面板WSKEY转换登陆面板失败, 请检查面板状态.'  # 设置推送内容
        try:  # 异常捕捉
            send('WSKEY转换', text)  # 消息发送
        except Exception as err:  # 异常捕捉
            logger.debug(str(err))  # Debug日志输出
            logger.info("通知发送失败")  # 标准日志输出
        sys.exit(1)  # 脚本退出
    else:  # 无异常执行分支
        return token  # 返回 token值
示例#6
0
def notify_upload_file():
    # __import__('rpdb').set_trace()
    if current_user.is_authenticated:
        if request.method == "POST":

            # check if the post request has the recipient email
            if "email" not in request.form:
                flash("No recipient email")
                return redirect(request.url)
            email = request.form.get("email")

            # check if the post request has the file part
            if "file" not in request.files:
                flash("No file part")
                return redirect(request.url)
            file = request.files["file"]
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == "":
                flash("No selected file")
                return redirect(request.url)
            if file and allowed_file(file.filename):
                notify.send(file.stream, email)
                return """
                <!doctype html>
                <title>Uploaded File</title>
                <h1>Uploaded File</h1>
                URL has been sent via email
            """
        return input_form()
    else:
        return '<a class="button" href="/login">Google Login</a>'
示例#7
0
    def new_mail_notify(self, mail_path):
        mail_id, *_ = mail_path.split(':')
        mail = self.maildir.get(mail_id)
        assert mail is not None

        mail_from = decode_header(mail.get('From'))
        mail_subject = decode_header(mail.get('Subject'))

        notify.send('New Mail', 'From: {}\nSubject: {}'.format(mail_from, mail_subject))
示例#8
0
def get_token() -> str or None:
    try:
        with open("/ql/config/auth.json", "r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception:
        logger.info(f"❌无法获取 token!!!\n{traceback.format_exc()}")
        send("💔禁用重复任务失败", "无法获取 token!!!")
        exit(1)
    return data.get("token")
示例#9
0
def handle_request(r):
    os.mkdir(path.srpms_dir + '/' + r.id)
    os.chmod(path.srpms_dir + '/' + r.id, 0755)
    ftp.init(r)
    buildlogs.init(r)
    build.build_all(r, build_srpm)
    report.send_report(r, is_src = True)
    report.send_cia_report(r, is_src = True)
    store_binary_request(r)
    ftp.flush()
    notify.send(r)
示例#10
0
def handle_request(r):
    os.mkdir(path.srpms_dir + '/' + r.id)
    os.chmod(path.srpms_dir + '/' + r.id, 0755)
    ftp.init(r)
    buildlogs.init(r)
    build.build_all(r, build_srpm)
    report.send_report(r, is_src=True)
    report.send_cia_report(r, is_src=True)
    store_binary_request(r)
    ftp.flush()
    notify.send(r)
示例#11
0
def run():
    print(
        f"喜马拉雅极速版 (https://github.com/Zero-S1/xmly_speed/blob/master/xmly_speed.md ) ,欢迎打赏¯\(°_o)/¯"
    )
    mins, date_stamp, _datatime, _notify_time = get_time()
    title = '⏰ 喜马拉雅极速版'
    table = []
    for k, v in enumerate(cookiesList):
        print(f">>>>>>>【账号开始{k+1}】\n")
        cookies = str2dict(v)
        if XMLY_ACCUMULATE_TIME == 1:
            saveListenTime(cookies, date_stamp)
            listenData(cookies, date_stamp)
        read(cookies)  # 阅读
        bubble(cookies)  # 收金币气泡
        # continue
        continuousDays = checkin(cookies, _datatime)  # 自动签到
        # lottery_info(cookies)  # 大转盘4次
        answer(cookies)  # 答题赚金币
        cardReportTime(cookies, mins, date_stamp, _datatime)  # 卡牌
        getOmnipotentCard(cookies, mins, date_stamp, _datatime)  # 领取万能卡
        card(cookies, _datatime)  # 抽卡
        index_baoxiang_award(cookies)  # 首页、宝箱奖励及翻倍
        total, todayTotal, historyTotal = account(cookies)
        try:
            device = devices[k]
        except IndexError:
            device = cookies['device_model']
        else:
            device = f"设备{k+1}"

        table.append((
            device,
            total,
            todayTotal,
            historyTotal,
            continuousDays,
        ))

        print("###" * 20)
        print("\n" * 4)
    if int(_notify_time.split()[0]) == notify_time and int(
            _notify_time.split()[1]) < 30:
        # if 1:
        message = ''
        for i in table:
            message += f"【设备】:{i[0].replace(' ',''):<9}\n"
            message += f"【当前剩余】:{i[1]:<6.2f}\n"
            message += f"【今天】:+{i[2]:<4.2f}\n"
            message += f"【历史】:{i[3]:<7.2f}\n"
            message += f"【连续签到】:{i[4]}/30\n"
            message += f"\n"

        send(title=title, content=message)
示例#12
0
def update():
    up_ver = int(cloud_arg['update'])
    if ver >= up_ver:
        logger.info("当前脚本版本: " + str(ver))
        logger.info("--------------------\n")
    else:
        logger.info("当前脚本版本: " + str(ver) + "新版本: " + str(up_ver))
        logger.info("存在新版本, 请更新脚本后执行")
        logger.info("--------------------\n")
        text = '当前脚本版本: {0}新版本: {1}, 请更新脚本~!'.format(ver, up_ver)
        try:
            send('WSKEY转换', text)
        except:
            logger.info("通知发送失败")
示例#13
0
文件: netuse.py 项目: sbouii/netuse
def noti():
    """Send notification about usage and the data remaining."""

    _, _, data_left, _, _, suggested = calculate_monthly_stats()

    # TODO: If end date is today, add a line about that too
    # or maybe a custom alert?

    title = "Remaining Data: %d MB" % data_left
    body = "\n".join([
        "You've downloaded %d MB in the last hour.",
        "Suggested usage is %d MB per day."
    ]) % (hourly(), suggested)

    notify.send(title, body)
示例#14
0
def update():  # 方法 脚本更新模块
    up_ver = int(cloud_arg['update'])  # 云端参数取值 [int]
    if ver >= up_ver:  # 判断版本号大小
        logger.info("当前脚本版本: " + str(ver))  # 标准日志输出
        logger.info("--------------------\n")  # 标准日志输出
    else:  # 判断分支
        logger.info("当前脚本版本: " + str(ver) + "新版本: " + str(up_ver))  # 标准日志输出
        logger.info("存在新版本, 请更新脚本后执行")  # 标准日志输出
        logger.info("--------------------\n")  # 标准日志输出
        text = '当前脚本版本: {0}新版本: {1}, 请更新脚本~!'.format(ver, up_ver)  # 设置发送内容
        try:  # 异常捕捉
            send('WSKEY转换', text)  # 推送消息
        except Exception as err:  # 异常捕捉
            logger.debug(str(err))  # 调试日志输出
            logger.info("通知发送失败")  # 标准日志输出
示例#15
0
def run_command(cmd, **kwargs):
    try:
        output = envoy.run(cmd, **kwargs)
        std_err = output.std_err
    except Exception as e:
        status_code = 1
        std_err = traceback.format_exc()
    else:
        status_code = output.status_code
    if status_code:
        notify.send("Failure in Jinja-Static command", cmd,
                    icon='gtk-dialog-critical', urgency='CRITICAL')
        sys.stderr.write("Error while running command: {0}\n".format(cmd))
        sys.exit(1)
    return output
示例#16
0
def noti():
    """Send notification about usage and the data remaining."""

    _, _, data_left, _, _, suggested = calculate_monthly_stats()

    # TODO: If end date is today, add a line about that too
    # or maybe a custom alert?

    title = "Remaining Data: %d MB" % data_left
    body = "\n".join([
        "You've downloaded %d MB in the last hour.",
        "Suggested usage is %d MB per day."
    ]) % (hourly(), suggested)

    notify.send(title, body)
示例#17
0
文件: cli.py 项目: blieberman/pension
def main(completed, dry_run, config, quiet):
    config_names = [config] if config else ['pension.toml', '~/.pension.toml']

    try:
        config = get_config(config_names)
    except:
        click.echo('Failed to parse config', err=True)
        return -1

    if config is None:
        click.echo('No usable config file, trying environment vars', err=True)
        config = {'notify': {'json': {}}}

    if completed:
        config['output'] = 'completed'
    else:
        config['output'] = 'normal'

    data = {'instances': [], 'profiles': {}}
    instance_map = {}

    for prof, session in get_profiles(config).iteritems():
        ec2_client = session.client('ec2')
        ec2 = session.resource('ec2')

        statuses = get_instance_statuses(ec2_client, config)

        data['profiles'][prof] = {
            'region': session._session.get_config_variable('region'),
            'instances': [s['InstanceId'] for s in statuses]
        }
        data['instances'].extend(statuses)

        if statuses:
            # Keep track of boto ec2 instances
            instance_list = ec2.instances.filter(
                InstanceIds=[s['InstanceId'] for s in statuses])

            instance_map.update({i.instance_id: i for i in instance_list})

    click.echo('%d instance(s) have reported issues' % len(data['instances']),
               err=True)

    if dry_run:
        config['notify'] = {} if quiet else {'json': {}}

    notify.send(data, instance_map, config['notify'])
示例#18
0
    def takePicture(self, dt):
        self.count += 1
        vc = cv2.VideoCapture(-1)
        rval, img = vc.read()
        if not rval:
            notify.send("Posture Tracker", "Webcam is not working")
            return
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        bBox = self.faceRec.getBoundingBox(img)
        diff = self.faceRec.compareFacePosition(bBox, self.refBBox)
        if bBox:  #face found
            self.badPictureCount = 0
            self.badPositionCount += 1
            #leaned backwards
            if diff[0] < -30 or diff[2] > 20:
                self.image.source = "textures/leanedback.png"
            #leaned forwards
            elif diff[0] > 40:
                self.image.source = "textures/crouch.png"
            #leaning to the side, only checked when checkSidewaysMovements is true
            elif self.checkSidewaysMovement and abs(diff[1]) > 50:
                self.image.source = "textures/side.png"
            #higher than normal position
            elif diff[2] < -20:
                self.image.source = "textures/high.png"
            #good posture
            else:
                self.image.source = "textures/good.png"
                self.badPositionCount = 0
                self.multiplier = 1
        #face not found on 10th time
        elif self.count == 10:
            self.badPictureCount += 1
            self.image.source = "textures/notfound.png"

        if self.badPictureCount > 2:
            notify.send(
                "Posture Tracker",
                "I can't see you! Are you still there? Brighter lighting might be necessary"
            )
        elif self.badPositionCount == self.notificationInterval * self.multiplier:
            notify.send(
                "Posture Tracker", "You have been sitting badly for " +
                str(self.badPositionCount) + " minutes")
        elif self.badPositionCount > self.notificationInterval * self.multiplier:
            notify.send(
                "Posture Tracker",
                "It seems you're still sitting badly. Or maybe you should take a new reference picture?"
            )
            self.multiplier += 1

        if bBox or self.count == 10:
            self.image.reload()
            self.count = 0
            return False
示例#19
0
def get_qltoken(username, password):
    logger.info("Token失效, 新登陆\n")
    url = "http://127.0.0.1:{0}/api/user/login".format(port)
    payload = {'username': username, 'password': password}
    payload = json.dumps(payload)
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    try:
        res = requests.post(url=url, headers=headers, data=payload)
        token = json.loads(res.text)["data"]['token']
    except:
        logger.info("青龙登录失败, 请检查面板状态!")
        te_xt = '青龙面板WSKEY转换登陆面板失败, 请检查面板状态.'
        try:
            send('WSKEY转换', te_xt)
        except:
            logger.info("通知发送失败")
        sys.exit(1)
    else:
        return token
        os.makedirs(base_path)
    index=1
    with open(base_path+"Cartesian_product.txt", "w+") as writer:
        for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers, batch_size, learning_rate):
            writer.write(str(index)+":"+"\n")
            writer.write('ks={}, num_layer={}, bs={}, lr={}'.format(ks, num_layer, bs, lr)+"\n")
            index = index + 1
        del index

    index=1
    for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers, batch_size, learning_rate):
        print("Index "+str(index))
        path = base_path+str(index)
        if not os.path.exists(path):
            os.makedirs(path)

        model = tools.create_model(lr, bs, ks, num_layer)
        print(model.summary())
        if model:
            run(bs, path, lr, ks, num_layer)
        else:
            overflow_model = overflow_model + 1
        del model
        index = index + 1

    print("Training finished! Overflow model: ", overflow_model)
except:
    
    notify.send('Exception occurred')
    
notify.send('Finish training!')
示例#21
0
             if return_ws[0]:  # bool: True
                 nt_key = str(return_ws[1])
                 # logger.info("wskey转pt_key成功", nt_key)
                 logger.info("wskey转换成功")
                 eid = return_serch[2]  # 从 return_serch 拿到 eid
                 ql_update(eid, nt_key)  # 函数 ql_update 参数 eid JD_COOKIE
             else:
                 # logger.info(str(wspin) + "wskey失效\n")
                 eid = return_serch[2]
                 logger.info(str(wspin) + "账号禁用")
                 ql_disable(eid)
                 # dd = serch_ck(ws)[2]
                 # ql_disable(dd)
                 text = "账号: {0} WsKey失效, 已禁用Cookie".format(wspin)
                 try:
                     send('WsKey转换脚本', text)
                 except:
                     logger.info("通知发送失败")
         else:
             logger.info(str(wspin) + "账号有效")
             eid = return_serch[2]
             ql_enable(eid)
             logger.info("--------------------\n")
     else:
         logger.info("\n新wskey\n")
         return_ws = getToken(ws)  # 使用 WSKEY 请求获取 JD_COOKIE bool jd_ck
         if return_ws[0]:
             nt_key = str(return_ws[1])
             logger.info("wskey转换成功\n")
             ql_insert(nt_key)
 else:
示例#22
0
def run():
    title = f'📚中青看点'
    content = ''
    result = ''
    beijing_datetime = get_standard_time()
    print(f'\n【中青看点】{beijing_datetime.strftime("%Y-%m-%d %H:%M:%S")}')
    hour = beijing_datetime.hour
    for account in COOKIELIST:
        headers = account['YOUTH_HEADER']
        readBody = account['YOUTH_READBODY']
        redBody = account['YOUTH_REDBODY']
        readTimeBody = account['YOUTH_READTIMEBODY']
        rotaryBody = f'{headers["Referer"].split("&")[15]}&{headers["Referer"].split("&")[8]}'
        sign_res = sign(headers=headers)
        if sign_res and sign_res['status'] == 1:
            content += f'【签到结果】成功 🎉 明日+{sign_res["nextScore"]}青豆'

        sign_info = signInfo(headers=headers)
        if sign_info:
            content += f'\n【账号】: {sign_info["user"]["nickname"]}'
            content += f'\n【签到】+{sign_info["sign_score"]}青豆 已连签{sign_info["sign_day"]}天'
            result += f'【账号】: {sign_info["user"]["nickname"]}'
        friendList(headers=headers)
        if hour > 12:
            punch_card_res = punchCard(headers=headers)
            if punch_card_res:
                content += f'\n【打卡报名】打卡报名{punch_card_res["msg"]} ✅'
        if hour >= 5 and hour <= 8:
            do_card_res = doCard(headers=headers)
            if do_card_res:
                content += f'\n【早起打卡】{do_card_res["card_time"]} ✅'
        luck_draw_res = luckDraw(headers=headers)
        if luck_draw_res:
            content += f'\n【七日签到】+{luck_draw_res["score"]}青豆'
        visit_reward_res = visitReward(body=readBody)
        if visit_reward_res:
            content += f'\n【回访奖励】+{visit_reward_res["score"]}青豆'
        shareArticle(headers=headers)
        open_box_res = openBox(headers=headers)
        if open_box_res:
            content += f'\n【开启宝箱】+{open_box_res["score"]}青豆 下次奖励{open_box_res["time"] / 60}分钟'
        watch_ad_video_res = watchAdVideo(headers=headers)
        if watch_ad_video_res:
            content += f'\n【观看视频】+{watch_ad_video_res["score"]}个青豆'
        watch_game_video_res = watchGameVideo(body=readBody)
        if watch_game_video_res:
            content += f'\n【激励视频】+{watch_game_video_res["score"]}个青豆'
        article_red_res = articleRed(body=redBody)
        if article_red_res:
            content += f'\n【惊喜红包】+{article_red_res["score"]}个青豆'
        read_time_res = readTime(body=readTimeBody)
        if read_time_res:
            content += f'\n【阅读时长】共计{read_time_res["time"] // 60}分钟'
        for i in range(0, 5):
            time.sleep(5)
            rotary_res = rotary(headers=headers, body=rotaryBody)
            if rotary_res:
                if rotary_res['status'] == 0:
                    break
                elif rotary_res['status'] == 1:
                    content += f'\n【转盘抽奖】+{rotary_res["data"]["score"]}个青豆 剩余{rotary_res["data"]["remainTurn"]}次'
                    if rotary_res['data']['doubleNum'] != 0:
                        double_rotary_res = doubleRotary(headers=headers,
                                                         body=rotaryBody)
                        if double_rotary_res:
                            content += f'\n【转盘双倍】+{double_rotary_res["score"]}青豆 剩余{double_rotary_res["doubleNum"]}次'

        rotaryChestReward(headers=headers, body=rotaryBody)
        stat_res = incomeStat(headers=headers)
        if stat_res['status'] == 0:
            for group in stat_res['history'][0]['group']:
                content += f'\n【{group["name"]}】+{group["money"]}青豆'
            result += f'\n【今日收益】+{stat_res["user"]["today_score"]}青豆'
            content += f'\n【今日收益】+{stat_res["user"]["today_score"]}青豆'
            result += f'\n【账户剩余】+{stat_res["user"]["score"]}青豆'
            content += f'\n【账户剩余】+{stat_res["user"]["score"]}青豆'
            result += f'\n【历史收益】+{stat_res["user"]["total_score"]}青豆\n\n'
            content += f'\n【历史收益】+{stat_res["user"]["total_score"]}青豆\n'

    print(content)

    # 每天 23:00 发送消息推送
    if beijing_datetime.hour == 23 and beijing_datetime.minute >= 0 and beijing_datetime.minute < 5:
        send(title=title, content=result)
    elif not beijing_datetime.hour == 23:
        print('未进行消息推送,原因:没到对应的推送时间点\n')
    else:
        print('未在规定的时间范围内\n')
示例#23
0
import notify
notify.init('test')
notify.send('test title', 'test message')
示例#24
0
def qq_read():
    # 确定脚本是否开启执行模式
    title = f'📚企鹅读书'
    content = ''
    result = ''
    beijing_datetime = get_standard_time()
    print(f'\n【企鹅读书】{beijing_datetime.strftime("%Y-%m-%d %H:%M:%S")}\n')
    for account in COOKIELIST:
        book_url = account['QQREAD_TIMEURL']
        headers = account['QQREAD_TIMEHD']
        body = account['QQREAD_BODY']
        withdraw = account['WITHDRAW']
        hosting_mode = account['HOSTING_MODE']

        start_time = time.time()
        error_catch = 0

        # 调用 track 接口,为保证输出结果美观,输出信息写在后面
        track_result = track(headers=headers, body=body)
        # 获取用户信息(昵称)
        user_info = get_user_info(headers=headers)
        guid = re.search(r'ywguid\=(\d+)\;', headers['Cookie'])
        result += f'【账号】:{guid.group(1)}'
        # model = re.sub(r'<.*$', "", body['common']['model'])
        if user_info:
            content += f'【用户昵称】{user_info["user"]["nickName"]}'
        # 获取任务列表,查询金币余额
        daily_tasks = get_daily_tasks(headers=headers)
        if daily_tasks:
            content += f'\n【金币余额】剩余{daily_tasks["user"]["amount"]}金币,可提现{daily_tasks["user"]["amount"] // 10000}元'
            result += f'\n【当前剩余】:{"{:4.2f}".format(daily_tasks["user"]["amount"] / 10000)}'
        # 查询今日获得金币数量
        beijing_datetime_0 = beijing_datetime.strftime(
            '%Y-%m-%d') + ' 00:00:00'
        today_coins_total = 0
        is_today_red_packet = True
        for pn in range(1, 15):
            red_packets = get_red_packets(headers=headers, pn=pn)
            if red_packets and is_today_red_packet:
                for red_packet in red_packets['list']:
                    if red_packet['content'] >= beijing_datetime_0:
                        today_coins_total += red_packet['amount']
                    else:
                        is_today_red_packet = False
                        break
            elif not red_packets:
                content += f'\n【今日收益】请求接口错误!'
                result += f'\n【今日收益】:请求接口错误!'
                break
            else:
                content += f"\n【今日收益】{today_coins_total}金币,约{'{:4.2f}'.format(today_coins_total / 10000)}元"
                result += f"\n【今日收益】:{'{:4.2f}'.format(today_coins_total / 10000)}"
                break
        # 查询本周阅读时长
        week_read_time = get_week_read_time(headers=headers)
        if week_read_time:
            content += f'\n【本周阅读】{week_read_time["readTime"] // 60}小时{week_read_time["readTime"] % 60}分钟'
        # 查询今日阅读时长
        today_read_time = get_today_read_time(headers=headers)
        if today_read_time:
            content += f'\n【今日阅读】{today_read_time["todayReadSeconds"] // 3600}小时{today_read_time["todayReadSeconds"] // 60 % 60}分钟'
        # 输出任务列表中的信息
        if daily_tasks:
            content += f'\n【{daily_tasks["taskList"][0]["title"]}】{daily_tasks["taskList"][0]["amount"]}金币,{daily_tasks["taskList"][0]["actionText"]}'
            content += f'\n【{daily_tasks["taskList"][1]["title"]}】{daily_tasks["taskList"][1]["amount"]}金币,{daily_tasks["taskList"][1]["actionText"]}'
            content += f'\n【{daily_tasks["taskList"][2]["title"]}】{daily_tasks["taskList"][2]["amount"]}金币,{daily_tasks["taskList"][2]["actionText"]}'
            content += f'\n【{daily_tasks["taskList"][3]["title"]}】{daily_tasks["taskList"][3]["amount"]}金币,{daily_tasks["taskList"][3]["actionText"]}{daily_tasks["taskList"][3]["subTitle"]}'
            content += f'\n【邀请任务】{daily_tasks["invite"]["month"]}月第{daily_tasks["invite"]["issue"]}期({daily_tasks["invite"]["dayRange"]}),已邀{daily_tasks["invite"]["inviteCount"]}人,再邀请{daily_tasks["invite"]["nextInviteConfig"]["count"]}人可获{daily_tasks["invite"]["nextInviteConfig"]["amount"]}金币'
            content += f'\n【粉丝分成】已有{daily_tasks["fans"]["fansCount"]}个粉丝,今日获得分成{daily_tasks["fans"]["todayAmount"]}金币'
            content += f'\n【宝箱任务】已开{daily_tasks["treasureBox"]["count"]}个宝箱,下一个宝箱{daily_tasks["treasureBox"]["tipText"]}'

        # 每日签到
        daily_beans = get_daily_beans(headers=headers)
        if daily_beans and daily_beans['takeTicket'] > 0:
            content += f"\n【阅豆签到】获得{daily_beans['takeTicket']}阅豆"

        # 阅读奖励,好像每个账号只能领一次
        if not today_read_time['readTimeRewardTask'][
                len(today_read_time['readTimeRewardTask']) - 1]['doneFlag']:
            seconds = [60, 180, 360, 600, 900, 1200, 1500]
            for i in seconds:
                read_time_reward = read_time_reward_tasks(headers=headers,
                                                          seconds=i)
                if read_time_reward:
                    content += f"\n【阅读奖励】阅读{i}秒,获得金币{read_time_reward['amount']}"
                    error_catch = read_time_reward['amount']

        # 立即阅读《xxx》
        if daily_tasks['taskList'][0]['enableFlag']:
            read_now_reward = read_now(headers=headers)
            if read_now_reward:
                content += f'\n【{daily_tasks["taskList"][0]["title"]}】获得{read_now_reward["amount"]}金币'
                error_catch = read_now_reward['amount']

        # 阅读任务
        if daily_tasks['taskList'][1]['enableFlag']:
            for task in daily_tasks['taskList'][1]['config']:
                if task['enableFlag'] and not task['doneFlag']:
                    read_reward = read_tasks(headers=headers,
                                             seconds=task['seconds'])
                    if read_reward and read_reward['amount'] > 0:
                        content += f"\n【阅读任务】阅读{task['timeStr']},获得{read_reward['amount']}金币"
                        error_catch = read_reward['amount']

        # 今日打卡
        if daily_tasks['taskList'][2]['enableFlag']:
            sign_reward = daily_sign(headers=headers)
            if sign_reward:
                content += f"\n【{daily_tasks['taskList'][2]['title']}】获得{sign_reward['todayAmount']}金币,已连续签到{sign_reward['clockInDays']}天"
            # 打卡翻倍
            if sign_reward['videoDoneFlag'] == 0:
                sign_ads_reward = watch_daily_sign_ads(headers=headers)
                if sign_ads_reward:
                    content += f"\n【打卡翻倍】获得{sign_ads_reward['amount']}金币"

        # 看视频
        if daily_tasks['taskList'][3]['enableFlag']:
            finish_count = int(daily_tasks["taskList"][3]["subTitle"][1:2])
            total_count = int(daily_tasks["taskList"][3]["subTitle"][3:4])
            # for i in range(1, total_count+1):
            watch_videos_reward = watch_videos(headers=headers)
            if watch_videos_reward:
                content += f"\n【视频奖励】获得{watch_videos_reward['amount']}金币({finish_count + 1}/{total_count})"
                error_catch = watch_videos_reward['amount']

        # 周阅读时长奖励查询
        week_read_rewards = get_week_read_tasks(headers=headers)
        # 当周阅读时间 >= 最大奖励所需要的时间(1200分钟),领取奖励
        if week_read_time['readTime'] >= week_read_rewards[
                len(week_read_rewards) - 1]['readTime']:
            for week_read_reward in week_read_rewards:
                if not week_read_reward['isPick']:
                    reward = get_week_read_reward(
                        headers=headers,
                        read_time=week_read_reward['readTime'])
                    if reward:
                        content += f"\n【周时长奖励】领取{week_read_reward['readTime']}时长奖励成功"

        # 开宝箱领金币
        if daily_tasks['treasureBox']['doneFlag'] == 0:
            treasure_box_reward = open_treasure_box(headers=headers)
            if treasure_box_reward:
                content += f"\n【开启第{treasure_box_reward['count']}个宝箱】获得{treasure_box_reward['amount']}金币"
                error_catch = treasure_box_reward['amount']

        # 宝箱金币奖励翻倍
        daily_tasks = get_daily_tasks(headers=headers)
        if daily_tasks['treasureBox']['videoDoneFlag'] == 0:
            treasure_box_ads_reward = watch_treasure_box_ads(headers=headers)
            if treasure_box_ads_reward:
                content += f"\n【宝箱奖励翻倍】获得{treasure_box_ads_reward['amount']}金币"
                error_catch = treasure_box_ads_reward['amount']

        # 读书刷时长
        if max_read_time > today_read_time["todayReadSeconds"] // 60:
            read_book = read_books(headers=headers,
                                   book_url=book_url,
                                   upload_time=upload_time)
            if read_book:
                content += f'\n【阅读时长】成功增加{upload_time}分钟阅读时长'
        else:
            content += f'\n【阅读时长】已达到设置的对大阅读时长,故不增加阅读时长'

        # track(headers, body)的输出信息
        if track_result:
            content += f'\n【数据跟踪】跟踪成功!'
        else:
            content += f'\n【数据跟踪】跟踪失败!请重新抓取你的参数 body '

        if withdraw:
            # 获取提现信息
            withdraw_info = get_withdraw_info(headers=headers)
            transform_info = []
            if withdraw_info:
                for i in withdraw_info:
                    if i['amount'] == 6000:
                        transform_info.append({
                            'amount': i['amount'],
                            'withdraw_time': 1
                        })
                    elif i['amount'] == 10000 or i['amount'] == 20000:
                        withdraw_time = re.findall('\d+', i['tipText'])
                        transform_info.append({
                            'amount':
                            i['amount'],
                            'withdraw_time':
                            int(withdraw_time[0])
                        })
                    else:
                        transform_info.append({
                            'amount': i['amount'],
                            'withdraw_time': 999
                        })

            # 提现
            if withdraw and beijing_datetime.hour == 23:
                if hosting_mode:
                    # 先把0.6元提现了
                    if daily_tasks["user"]["amount"] >= 6000 and transform_info[0]['amount'] == 6000 and \
                            transform_info[0]['withdraw_time'] > 0:
                        withdraw_result = withdraw_to_wallet(headers=headers,
                                                             amount=6000)
                        if withdraw_result == True:
                            content += f'\n【托管提现】提现0.6元成功!'
                            # 提现成功后,如果 notify 打开就发推送
                            send(title=title, content=f"【托管提现】提现0.6元成功!")
                        else:
                            content += f'\n【托管提现】提现失败!原因:{withdraw_result}'
                    elif daily_tasks["user"]["amount"] >= 10000:
                        transform_info.reverse()  # 提现尝试 大额度->小额度
                        for i in transform_info:
                            if daily_tasks["user"]["amount"] >= i[
                                    'amount'] and i['withdraw_time'] > 0:
                                withdraw_result = withdraw_to_wallet(
                                    headers=headers, amount=i['amount'])
                                if withdraw_result == True:
                                    content += f"\n【托管提现】提现{i['amount'] // 10000}元成功!"
                                    send(title=title,
                                         content=
                                         f"【托管提现】提现{i['amount'] // 10000}元成功!")
                                else:
                                    content += f'\n【托管提现】提现失败!原因:{withdraw_result}'
                                break
                    else:
                        content += f'\n【托管提现】余额不足或低金额提现次数耗尽,无法提现!'
                else:
                    if daily_tasks["user"]["amount"] >= 100000:
                        withdraw_result = withdraw_to_wallet(headers=headers,
                                                             amount=100000)
                        if withdraw_result == True:
                            content += f'\n【满额提现】提现10元成功!'
                            send(title=title, content=f"【满额提现】提现10元成功!")
                        else:
                            content += f'\n【满额提现】提现失败!原因:{withdraw_result}'
                    else:
                        content += f'\n【满额提现】余额不足10元,未打开托管模式,不提现!'
            else:
                content += f'\n【自动提现】未到23点'
        else:
            content += f'\n【自动提现】未启用该功能'

        # 历史收益
        history_coins_total = daily_tasks["user"]["amount"]
        withdraw_list = get_withdraw_list(headers=headers)
        if withdraw_list:
            for with_draw in withdraw_list['withdrawList']:
                history_coins_total -= with_draw['amount']
            content += f"\n【历史收益】{history_coins_total}金币,约{'{:4.2f}'.format(history_coins_total / 10000)}元"
            result += f"\n【历史收益】:{'{:4.2f}'.format(history_coins_total / 10000)}\n\n"
        else:
            content += f'\n【历史收益】请求接口错误!\n'
            result += f'\n【历史收益】:请求接口错误!\n\n'

        content += f'\n🕛耗时:%.2f秒\n\n' % (time.time() - start_time)

        if error_catch == 1:
            send(title=title, content=f'【账号】:{guid.group(1)} 数据异常')

    print(content)

    # 每天 23:00 发送消息推送
    if beijing_datetime.hour == 23 and beijing_datetime.minute >= 0 and beijing_datetime.minute <= 10:
        send(title=title, content=result)
    elif not beijing_datetime.hour == 23:
        print('未进行消息推送,原因:没到对应的推送时间点\n')
    else:
        print('未在规定的时间范围内\n')
示例#25
0
        for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers,
                                                       batch_size,
                                                       learning_rate):
            writer.write(str(index) + ":" + "\n")
            writer.write('ks={}, num_layer={}, bs={}, lr={}'.format(
                ks, num_layer, bs, lr) + "\n")
            index = index + 1
        del index

    index = 1
    for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers,
                                                   batch_size, learning_rate):
        print("Index " + str(index))
        path = base_path + str(index)
        if not os.path.exists(path):
            os.makedirs(path)

        model = tools.create_model(lr, bs, ks, num_layer)
        print(model.summary())
        if model:
            run(bs, path, lr, ks, num_layer)
        else:
            overflow_model = overflow_model + 1
        del model
        index = index + 1

    print("Training finished! Overflow model: ", overflow_model)
except:
    notify.send('Exception occurred: without BN')

notify.send('Finish training! without BN')
示例#26
0
文件: ui.py 项目: rcoh/Rally
 def notify(self, title, msg):
   """Desktop notifications"""
   notify.send(title, msg)
        for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers,
                                                       batch_size,
                                                       learning_rate):
            writer.write(str(index) + ":" + "\n")
            writer.write('ks={}, num_layer={}, bs={}, lr={}'.format(
                ks, num_layer, bs, lr) + "\n")
            index = index + 1
        del index

    index = 1
    for ks, num_layer, bs, lr in itertools.product(kernel_size, num_layers,
                                                   batch_size, learning_rate):
        print("Index " + str(index))
        path = base_path + str(index)
        if not os.path.exists(path):
            os.makedirs(path)

        model = tools.create_model(lr, bs, ks, num_layer)
        print(model.summary())
        if model:
            run(bs, path, lr, ks, num_layer)
        else:
            overflow_model = overflow_model + 1
        del model
        index = index + 1

    print("Training finished! Overflow model: ", overflow_model)
except:
    notify.send('Exception occurred: Maxpool')

notify.send('Finish training! Maxpool')
示例#28
0
 def handle(self, record):
     send(self.formatter.format(record))
示例#29
0
# Sonoma County
from bs4 import BeautifulSoup
from scraper_init import scrape
from append import append
from notify import send

# Init Scraper and Return Soup
soup = scrape('https://socoemergency.org/', 1)

# Select Figures

try:
    content = soup.findAll("table", {"class": "cvTable"})[0].findAll("td")
    totalCases = content[0].contents[0]
    activeCases = content[1].contents[0]
    recoveredCases = content[2].contents[0]
    deaths = content[3].contents[0]
    tests = content[4].contents[0]

    # Append to JSON File
    append('sonoma', totalCases, activeCases, deaths, recoveredCases, tests)
except Exception as e:
    send("Sonoma", e)
示例#30
0
# Napa County
from bs4 import BeautifulSoup
from scraper_init import scrape
from append import append
from notify import send

# Init Scraper and Return Soup
soup = scrape(
    'https://legacy.livestories.com/s/v2/coronavirus-report-for-napa-county-ca/9065d62d-f5a6-445f-b2a9-b7cf30b846dd/',
    10)

try:
    ### SELECT VARIABLES
    selection = soup.body.find_all("table")[0].find_all("tr")[1].find_all("td")
    positiveCases = selection[1].contents[0]
    deaths = selection[2].contents[0]

    # Append to JSON File
    append('napa', 'N/A', positiveCases, deaths, 'N/A', 'N/A')
except Exception as e:
    send("Napa", e)
示例#31
0
 def emit(self, record):
     notify.send(self.title, record.msg)
示例#32
0
#!/usr/bin/env python
from littlefield import Littlefield
from configparser import ConfigParser
import notify

config = ConfigParser()
config.read(["littlefield.ini"])

littlefield = Littlefield(config["littlefield"]["user"], config["littlefield"]["password"])

for i in range(1, 4):
    station = littlefield.get_station(i)
    utilitization = littlefield.get_data("S%sUTIL" % i)["average"][-1]
    if utilitization > float(config["littlefield"]["util_high"]):
        machines = station["number of machines"] + 1
        notify.send(
            "Station %s has a utilitization of %s. Increasing machines from %s to %s"
            % (i, utilitization, station["number of machines"], machines)
        )
        littlefield.update_machine_count(station, machines)
    elif utilitization < float(config["littlefield"]["util_low"]) and station["number of machines"] > 1:
        machines = station["number of machines"] - 1
        notify.send(
            "Station %s has a utilitization of %s. Decreasing machines from %s to %s"
            % (i, utilitization, station["number of machines"], machines)
        )
        littlefield.update_machine_count(station, machines)
示例#33
0
    orders_hist_df = pd.DataFrame(orders_hist,
                                  columns=[
                                      'order_time', 'symbol', 'size', 'side',
                                      'ord_type', 'ref_price', 'signal_time',
                                      'order_id'
                                  ])

    print('xxxx trades sample:')
    print(orders_hist_df.tail())

    pnl_df, pnl_info = get_agg_pnl(orders_hist_df)

    print('xxxx pnl_info:')
    print(pnl_df)
    print(f'config: {config}')

    email_body = pnl_df.to_html()
    email_body += '<br><hr>'
    email_body += pnl_info.to_html()
    email_body += '<br><hr>'
    email_body += f'config: {config}'

    ### send email
    msg = message(subject=f'Daily pnl backtest report - {today}',
                  text=email_body,
                  img='/home/gfeng/html/logo/sp500.png',
                  attachment=signals_file)

    send(msg)
# Contra Costa County
from bs4 import BeautifulSoup
from scraper_init import scrape
from append import append
from notify import send

# Init Scraper and Return Soup
soup = scrape('https://www.coronavirus.cchealth.org/', 5)

try: 
    ### SELECT VARIABLES
    selection = soup.body.find_all('h1')
    positiveCases = selection[0].contents[0]
    deaths = selection[3].contents[0]
    tests = selection[1].contents[0]
    
    # Append to JSON File
    append('contra_costa', 'N/A', positiveCases, deaths, 'N/A', tests)
except Exception as e:
    send("Contra Costa", e)
示例#35
0
#!/usr/bin/env python
from littlefield import Littlefield
from configparser import ConfigParser
import notify

config = ConfigParser()
config.read(['littlefield.ini'])

littlefield = Littlefield(config['littlefield']['user'],
                          config['littlefield']['password'])

for i in range(1, 4):
    station = littlefield.get_station(i)
    utilitization = littlefield.get_data("S%sUTIL" % i)['average'][-1]
    if utilitization > float(config['littlefield']['util_high']):
        machines = station['number of machines'] + 1
        notify.send(
            "Station %s has a utilitization of %s. Increasing machines from %s to %s"
            % (i, utilitization, station['number of machines'], machines))
        littlefield.update_machine_count(station, machines)
    elif utilitization < float(config['littlefield']['util_low']
                               ) and station['number of machines'] > 1:
        machines = station['number of machines'] - 1
        notify.send(
            "Station %s has a utilitization of %s. Decreasing machines from %s to %s"
            % (i, utilitization, station['number of machines'], machines))
        littlefield.update_machine_count(station, machines)
示例#36
0
import os 
import notify 
from data import Sql 

dt = Sql('database123', 'server001') #setup the connection to SQL Server

for i, file in enumerate(os.listdir('../data/new')):
    dt.push_raw(f'../data/new/{file}') #push a file to SQL Server

    #once the upload is complete send a notification 
    # first we create the message 
    msg = notify.message(
        subject='SQL Data Upload',
        text=f'Data upload complete, {i} files uplaoded.',
    )

    # send the message 
    notify.send(msg)

    #If errors are occasionally thrown, we could also add a try-except clause to catch the error
示例#37
0
文件: ui.py 项目: allygale/Rally
 def notify(self, title, msg):
     notify.send(title, msg)
示例#38
0
文件: test_notify.py 项目: rcoh/Rally
#test_notify.py
#Copyright (C) 2011  Russell Cohen <*****@*****.**>
#
# This file is part of Rally.
#
# Rally is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Rally is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rally.  If not, see
# <http://www.gnu.org/licenses/>.

import notify
notify.init('test')
notify.send('test title', 'test message')
# Alameda County
from bs4 import BeautifulSoup
from scraper_init import scrape
from append import append
from notify import send

# Init Scraper and Return Soup
soup = scrape('https://ac-hcsa.maps.arcgis.com/apps/opsdashboard/index.html#/948c67558cff414dbbee1a78fcbab1c9', 5)

try: 
    # Select Figures
    selection = soup.find("full-container").findAll("div")
    positiveCasesRaw = selection[11].findAll("text")[0].contents[0]
    deaths = selection[19].findAll("text")[0].contents[0]
    
    # Append to JSON File
    append('alameda', positiveCasesRaw, 'N/A', deaths, 'N/A', 'N/A')
except Exception as e:
    send("Alameda", e)