def main_handler(event, context): log.info('任务开始') notify = Notify() msg_list = [] ret = success_num = fail_num = 0 # ============= miHoYo BBS COOKIE ============ # 此处填米游社的COOKIE # 注: Github Actions用户请到Settings->Secrets里设置,Name=COOKIE,Value=<获取的值> # 多个账号的COOKIE值之间用 # 号隔开,例如: 1#2#3#4 COOKIE = '' if os.environ.get('COOKIE', '') != '': COOKIE = os.environ['COOKIE'] cookie_list = COOKIE.split('#') log.info(f'检测到共配置了 {len(cookie_list)} 个帐号') for i in range(len(cookie_list)): log.info(f'准备为 NO.{i + 1} 账号签到...') try: msg = f' NO.{i + 1} 账号:{Sign(cookie_list[i]).run()}' msg_list.append(msg) success_num = success_num + 1 except Exception as e: msg = f' NO.{i + 1} 账号:\n {e}' msg_list.append(msg) fail_num = fail_num + 1 log.error(msg) ret = -1 continue notify.send(status=f'成功: {success_num} | 失败: {fail_num}', msg=msg_list) if ret != 0: log.error('异常退出') exit(ret) log.info('任务结束')
def notification(request): response = HttpResponse() notifymessage = request.GET['notifymessage'] no = Notify() print no no.notify('tokudo/123', notifymessage, no.NOTIFY_TYPE_ALL) return response
def cronjob(): tic = time() monitor = Monitor() db = Database() db._add_system_log('cron', {'message': 'emails script executing'}) # get all class openings (for waited-on classes) from MobileApp new_slots = monitor.get_classes_with_changed_enrollments() total = 0 for classid, n_new_slots in new_slots.items(): if n_new_slots == 0: continue try: # n_notifs = min(db.get_class_waitlist_size(classid), n_new_slots) n_notifs = db.get_class_waitlist_size(classid) except Exception as e: print(e, file=stderr) continue # randomly iterate through lists to ensure fairness ordering = list(range(n_notifs)) shuffle(ordering) for i in ordering: try: notify = Notify(classid, i, n_new_slots) print(notify) print('sending email to', notify.get_netid()) stdout.flush() # only if email was sent, remove user from waitlist if notify.send_email_html(): print(i + 1, '/', n_notifs, 'emails sent for this class') total += 1 # db.remove_from_waitlist(notify.get_netid(), classid) else: print('failed to send email') except Exception as e: print(e, file=stderr) print() if total > 0: db._add_admin_log( f'sent {total} emails in {round(time()-tic)} seconds') db._add_system_log( 'cron', {'message': f'sent {total} emails in {round(time()-tic)} seconds'}) elif total == 0: db._add_system_log( 'cron', {'message': f'sent 0 emails in {round(time()-tic)} seconds'})
def __init__(self): self.n = Notify() for x in range(1,6): key = '<ctrl>F' + str(x) if not bind(key, lambda y=x: self.rate(y)): exit(1) if not bind('<ctrl>F6', self.show): exit(1) if not bind('<ctrl>F7', self.decr): exit(1) if not bind('<ctrl>F8', self.incr): exit(1)
def checkin(cookie): session = requests.Session() url = f'https://note.youdao.com/yws/mapi/user?method=checkin' headers = { "User-Agent": "YNote", # "Referer": "https://note.youdao.com", "Host": "note.youdao.com", "Accept-Encoding": "gzip, deflate, br", "Cache-Control": "no-cache", "Connection": "keep-alive", "Accept": "*/*", "Cookie": cookie } response = session.post(url, headers=headers) json = response.json() logging.info(json) # 通知信息 message = '' if 'success' in json : user = getuser(cookie) space = getTotalSpace(cookie) message = "用户名:%s\n邮箱:%s\n获得空间:%dM,总空间%.2fG" % (user['name'], user['email'], json['space'] / 1048576, space['um']['q'] / 1073741824) if json['success'] == 1: logging.info("签到成功") message += "\n状态:签到成功" elif json['success'] == 0: logging.warning("重复签到") message += "\n状态:重复签到" logging.info(message) else: logging.info("签到失败:%s",json['message']) message += "\n状态:签到失败\n原因:" + json['message'] Notify().sendMessage(message) return json
def _AlertDestination(self, phone, mr): """Send alert notification to the registered destination.""" #self.response.out.write('Send alert to dst email: %s\n' % mr.primary_email) s = 'Live Home Free<*****@*****.**>' sub = 'URGENT!! Alert from %s' % phone body = 'Please contact %s ASAP!' % phone logging.debug('sender: %s\nto: %s\nsub: %s\nbody: %s' % (s, mr.primary_email, sub, body)) # TODO: less-ugly config management config = ConfigObj('config.ini') os.environ["TWILIO_ACCOUNT_SID"] = config['twillio_account'] os.environ["TWILIO_AUTH_TOKEN"] = config['twillio_token'] n = Notify(config) n.sms(mr.primary_phone, 'Please contact %s ASAP!' % phone) self.response.out.write('Send alert to dst email: %s\n' % mr.primary_email)
def handleClaim(packtpub, args, config, dir_path): if args.dev: log_json(packtpub.info) log_success('[+] book successfully claimed') upload = None upload_info = None if not args.claimOnly: types = parse_types(args) packtpub.download_ebooks(types, dir_path) if args.extras: packtpub.download_extras(dir_path) if args.archive: raise NotImplementedError('not implemented yet!') if args.upload is not None: upload = Upload(config, args.upload) upload.run(packtpub.info['paths']) if upload is not None and upload is not SERVICE_DRIVE: log_warn('[-] skip store info: missing upload info') elif args.store is not None: Database(config, args.store, packtpub.info, upload.info).store() if args.notify: if upload is not None: upload_info = upload.info Notify(config, packtpub.info, upload_info, args.notify).run()
def test_send_authorized_notifcation(self): test_user = '******' with Notify() as n: response = n.send_notification(user_id=test_user) assert response.status_code == 200
def servermain(): logger = logging.getLogger('jobs') try: while True: noo=Notify() rest=noo.bingfa() noo.close() if not rest: logger.debug('No data') logger.debug('current time-->%s',datetime.now()) sec=setting.PERIOD-datetime.now().second logger.debug('sleep....%ss',sec) time.sleep(sec) except KeyboardInterrupt, e: #LOG(e) logger.debug(e)
def __init__(self): self.bot = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=chrome_options) self.logger = Logger() self.notify = Notify() self.att_count = 0 self.marked_count = 0 self.server_ip = ''
def __init__(self): logging.getLogger('garage').info('Butler is starting...') self.notify = Notify(self) GPIO.add_event_detect(button_pin, GPIO.FALLING, callback=self.door_check, bouncetime=1000) scheduler.start() scheduler.add_job(self.status_check, 'interval', minutes=1) self.last_notification = datetime.datetime.strptime('Jun 1 2005 1:00PM', '%b %d %Y %I:%M%p') self.last_status = GPIO.input(button_pin)
def main(): parser = argparse.ArgumentParser( description='Download FREE eBook every day from www.packtpub.com', formatter_class=argparse.ArgumentDefaultsHelpFormatter, version='1.3.0') parser.add_argument('-c', '--config', required=True, help='configuration file') parser.add_argument('-d', '--dev', action='store_true', help='only for development') parser.add_argument('-e', '--extras', action='store_true', help='download source code (if exists) and book cover') parser.add_argument('-u', '--upload', choices=[SERVICE_DRIVE, SERVICE_DROPBOX], help='upload to cloud') parser.add_argument('-a', '--archive', action='store_true', help='compress all file') parser.add_argument('-n', '--notify', action='store_true', help='notify via email') parser.add_argument('-s', '--store', choices=[DB_FIREBASE], help='store info') group = parser.add_mutually_exclusive_group() group.add_argument('-t', '--type', choices=['pdf', 'epub', 'mobi'], default='pdf', help='specify eBook type') group.add_argument('--all', dest='types', action='store_const', const=['pdf', 'epub', 'mobi'], help='all eBook types') args = parser.parse_args() try: #ip_address() config = config_file(args.config) types = parse_types(args) packpub = Packpub(config, args.dev) packpub.run() log_json(packpub.info) packpub.download_ebooks(types) if args.extras: packpub.download_extras() if args.archive: raise NotImplementedError('not implemented yet!') upload = None if args.upload is not None: upload = Upload(config, args.upload) upload.run(packpub.info['paths']) if upload is None: log_warn('[-] skip store info: missing upload info') log_warn('[-] skip notification: missing upload info') else: if args.store is not None: Database(config, args.store, packpub.info, upload.info).store() if args.notify: Notify(config, packpub.info, upload.info).send_email() except KeyboardInterrupt: log_error('[-] interrupted manually') except Exception as e: log_debug(e) log_error('[-] something weird occurred, exiting...')
def lambda_handler(event, context): # Instantiate Custom classes logger.info("Event: " + json.dumps(event)) notify = Notify(logger) # solution id and data must be updated every solution solution_id = os.environ['solution_id'] data = event['Data'] uuid = os.environ['uuid'] # from env variable send_data = os.environ['SEND_ANONYMOUS_DATA'] # Metrics Account (Production) metrics_url = 'https://metrics.awssolutionsbuilder.com/generic' # Metrics Account (Dev1) #metrics_url = 'https://oszclq8tyh.execute-api.us-east-1.amazonaws.com/prod/generic' # Send Anonymous Metrics if send_data == "Yes": notify.metrics(solution_id, uuid, data, metrics_url) logger.debug(uuid + " : " + json.dumps(data))
def main(datapath): """ Just a generic entrypoint for testing. """ notify = Notify(config.gitter_token, config.gitter_community) go_back = changed_after_days() ghf = GithubFeeds(config.github_token, datapath + '/github.yml', go_back) updates = ghf.update() results = [] for org in updates.keys(): if updates[org]: results.append(org) if len(results) > 0: message_template = Template(bot_message) message = message_template.render(data=results) print(message) notify.send(config.gitter_channel, message)
def monitor(self): """ @Purpose: Main monitoring routine. """ while True: ##### Checking envdb availability ##### try: envdb = EnvDB() self.isEnvDBAlive = True except Exception, e: if self.isEnvDBAlive: self.isEnvDBAlive = False else: if not self.sentDownMsg: ################ EMAIL DOWN MSG ############### print self.__DATABASE_DOWN_SUBJECT__ print self.__DATABASE_DOWN_MSG__ % self.__getTimeString__() notifyObj = Notify(notifyList, subject=self.__DATABASE_DOWN_SUBJECT__) notifyObj.send(self.__DATABASE_DOWN_MSG__ % self.__getTimeString__()) ############################################### self.sentDownMsg = True ###### try: for probe in self.monitorList: latestValue = envdb.getLatestProbeValue(probe) probeRange = self.__PROBE_RANGE__[probe] if self.monitorValidMap[probe] and (latestValue > probeRange[1] or latestValue < probeRange[0]): self.monitorValidMap[probe] = False ############### EMAIL PROBE OUT OF RANGE MSG ############ print self.__PROBE_OUT_OF_RANGE_SUBJECT__ % probe print self.__PROBE_OUT_OF_RANGE_MSG__ % (self.__getTimeString__(), probe, latestValue) notifyObj = Notify(notifyList, subject=self.__PROBE_OUT_OF_RANGE_SUBJECT__ % probe) notifyObj.send(self.__PROBE_OUT_OF_RANGE_MSG__ % (self.__getTimeString__(), probe, latestValue)) ######################################################### elif (not self.monitorValidMap[probe]) and \ (latestValue >= probeRange[0]-self.__PROBE_THRESHOLD__ and latestValue <= probeRange[1]-self.__PROBE_THRESHOLD__): self.monitorValidMap[probe] = True ############### EMAIL PROBE WITHIN RANGE MSG ############ print self.__PROBE_COME_BACK_WITH_IN_RANGE_SUBJECT__ % probe print self.__PROBE_COME_BACK_WITH_IN_RANGE_MSG__ % (self.__getTimeString__(), probe, latestValue) notifyObj = Notify(notifyList, subject=self.__PROBE_COME_BACK_WITH_IN_RANGE_SUBJECT__ % probe) notifyObj.send(self.__PROBE_COME_BACK_WITH_IN_RANGE_MSG__ % (self.__getTimeString__(), probe, latestValue)) ######################################################### except Exception, e: print traceback.print_exc()
def proxy_complete(self): if self.uploading is True: return if self.status.get('builder_status', None) == "BuilderStatus.ABORTING": buildid = self.status.get('buildid', None) job = Job.selectBy(id=buildid)[0] self.complete(job, JobStatus.CANCELED) if self.status.get('builder_status', None) == 'BuilderStatus.WAITING': buildid = self.status.get('build_id', None) try: job = Job.selectBy(id=buildid)[0] except Exception as e: print(e) return if self.status.get('build_status') == "BuildStatus.OK": job_status = JobStatus.BUILD_OK else: job_status = JobStatus.FAILED # notify build try: _package = job.package.dict() cwd = os.path.join(config['cache']['sources'], _package['pkgname']) command = "git show %s --pretty=%%ae | head -n 1" % _package['hashsum'] status, email = functions.getstatusoutput(command, cwd=cwd) if status != 0: email = None command = "git log -1 %s --pretty=%%s | head -n 1" % _package['hashsum'] status, subject = functions.getstatusoutput(command, cwd=cwd) if status != 0: subject = None message_text = "Build %(pkgname)s - %(pkgver)s to %(reponame)s" % _package message_text += " [Failed](%s/job/%s)" % (config['runtime']['url'], str(job.id)) attachments_text = "Action: %(action)s\nHashsum: %(hashsum)s\n" % _package if subject: attachments_text += "Subject: %s\n" % subject attachments = [{ "text": attachments_text, "color": "#ffa500" }] #Notify().notify('bearychat', message_text=message_text, # author_email=email, message_attachments=attachments) Notify().notify('deepinworknoticebot', message_text=message_text, author_email=email, message_attachments=attachments) except Exception as error: print(error) self.complete(job, job_status)
def run_server(): db.init_data() db.load_to_file() player_event = Event() thread_player = Player(player_event) thread_player.play_current_song() thread_player.setDaemon(True) thread_player.start() down_event = Event() thread_down = Downloader(down_event) thread_down.setDaemon(True) thread_down.start() notify_event = Event() thread_notify = Notify(notify_event) thread_notify.setDaemon(True) thread_notify.start() maintain_event = Event() thread_maintain = Maintain(maintain_event) thread_maintain.setDaemon(True) thread_maintain.start() run(host='0.0.0.0', port=80, server=PasteServer)
def main(username, password): # 通知信息 message = f"用户:{username[:3]+'****'+username[7:]}\n" s = requests.Session() login(s, username, password) rand = str(round(time.time() * 1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', "Referer": "https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1", "Host": "m.cloud.189.cn", "Accept-Encoding": "gzip, deflate", } response = s.get(surl, headers=headers) netdiskBonus = response.json()['netdiskBonus'] if (response.json()['isSign'] == "false"): message += f"状态:签到成功\n获得:{netdiskBonus}M空间" log.info(f"状态:签到成功,获得:{netdiskBonus}M空间") else: message += f"状态:已经签到过了\n获得:{netdiskBonus}M空间" log.info(f"状态:已经签到过了,获得:{netdiskBonus}M空间") headers = { 'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', "Referer": "https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1", "Host": "m.cloud.189.cn", "Accept-Encoding": "gzip, deflate", } response = s.get(url, headers=headers) if ("errorCode" in response.text): errCode = response.json()['errorCode'] message += f"\n抽奖:{errCode}" log.info(response.text) else: description = response.json()['description'] message += f"\n抽奖:{description}" log.info(f"抽奖获得{description}") response = s.get(url2, headers=headers) if ("errorCode" in response.text): errCode = response.json()['errorCode'] message += f"\n抽奖:{errCode}" log.info(response.text) else: description = response.json()['description'] message += f"\n抽奖:{description}" log.info(f"抽奖获得{description}") Notify().sendMessage(message)
def test_send_unauthorized_notification(self): test_user = '******' with Notify() as n: response = n.send_notification(user_id=test_user) # Have facebook changed the error code for this? # assert response.status_code == 500 # updated new expected status code # Apparrently we want 400 error now # TODO - check this is correct assert response.status_code == 400
def main_handler(event, context): """云函数入口""" logging.getLogger().setLevel(logging.INFO) logging.info('script start up') logging.info('start read csv') with open('./user_data.csv') as f: logging.info('read csv finished') user_data_csv = csv.DictReader(f) logging.info('read csv finished, start execute all user') for csv_dict in user_data_csv: try: with ModSession() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2)'} # 设置UA避免被防火墙拦截 logging.info(f'start trying login user:{csv_dict["login_id"]}') login_state = Secure(csv_dict['login_id'], csv_dict['login_pwd'], session).login().test() if login_state: logging.info('login finished') else: logging.error(f'login user:{csv_dict["login_id"]} failed') continue card = Card(session) logging.info('card init finished') card.submit(csv_dict) logging.info('card init finished') today_submit_time = card.get_today_submit_time() Notify().send('[OK]健康卡自动填报已执行', f'健康卡自动填报成功,从服务端查询到的最后填报时间为{today_submit_time}') logging.info(f'[OK]健康卡:{csv_dict["login_id"]}自动填报成功,从服务端查询到的最后填报时间为{today_submit_time}') except Exception as e: print(e) Notify().send('[ERROR]健康卡自动填表发生错误', '健康卡自动填表发生错误,请到云函数平台检查执行日志,联系开发者并提供必要的错误日志') logging.error(f'[ERROR]健康卡:{csv_dict["login_id"]}自动填报失败')
class Butler: def __init__(self): logging.getLogger('garage').info('Butler is starting...') self.notify = Notify(self) GPIO.add_event_detect(button_pin, GPIO.FALLING, callback=self.door_check, bouncetime=1000) scheduler.start() scheduler.add_job(self.status_check, 'interval', minutes=1) self.last_notification = datetime.datetime.strptime('Jun 1 2005 1:00PM', '%b %d %Y %I:%M%p') self.last_status = GPIO.input(button_pin) def door_check(self, channel): time.sleep(3) status = GPIO.input(button_pin) db = get_db() # logging.getLogger('garage').info('status = %s, last status = %s' % (status, self.last_status)) if status == 1: if status != self.last_status: db.record_door_closed() logging.getLogger('garage').info('Door closed') self.notify.notify() else: pass # logging.getLogger('garage').info('Door closed again') else: if status != self.last_status: db.record_door_opened() logging.getLogger('garage').info('Door opened') self.notify.notify() else: pass # logging.getLogger('garage').info('Door opened again') db.shutdown() self.last_status = status def status_check(self): logging.getLogger('garage').info('checking status') db = get_db() status = db.get_status() settings = db.get_settings() db.shutdown() logging.getLogger('garage').info('status is %s' % status) logging.getLogger('garage').info('setting are %s' % settings) self.notify.notify() def toggle_switch(self): logging.getLogger('garage').info('toggle switch') GPIO.output(relay_pin, 0) time.sleep(.25) GPIO.output(relay_pin, 1) def _notify(self, status, settings): pass def _mins_since_last_notification(self): delta = datetime.datetime.now() - self.last_notification return delta.total_seconds()/60
class Notification: def __init__(self): self.notification = Notify() self.msg = self.notification.add_msg() self.close = self.notification.add_button() self.close.connect("clicked",self.close_notify) def get_widget(self): return self.notification def hide(self): self.notification.hide_all() def close_notify(self, w): self.notification.hide_all() def add_icon(self, icon): self.notification.add_icon(icon) def show_notify(self, icon, text): if text: self.add_icon(icon) self.msg.set_text(text) self.notification.show_all()
def main(): settings = get_settings() if settings: notify = Notify(settings["to"], settings["username"], settings["password"], settings["phone"]) if len(settings["course"]) == 3: enroller = Enroll(notify, settings["course"][0], settings["course"][1], settings["course"][2], settings["netid"], settings["netid_password"]) elif len(settings["course"]) == 4: enroller = Enroll(notify, settings["course"][0], settings["course"][1], settings["course"][2], settings["netid"], settings["netid_password"], settings["course"][3]) else: print("Unsupported amount of arguments") return enroller.main_loop() else: print("Error parsing Settings.cfg")
def __init__(self): self.notification = Notify() self.msg = self.notification.add_msg() self.close = self.notification.add_button() self.close.connect("clicked",self.close_notify)
from notify import Notify from chooseMatches import chooseMatches from score import score match = chooseMatches() Notify(match)
def test_get_users(self): with Notify() as n: response = n.get_users() assert response.status_code == 200 assert response.json()['users'] is not None
def test_authorized_access(self): with Notify() as n: response = n.get_users() assert response.status_code == 200
def test_unauthorized_access(self): with Notify() as n: response = n.get_users(username="******", password="******") assert response.status_code == 403
""" # GitHub Actions Users Please go to the settings-> secrets of the REPO to set the variable, the variable name must be completely consistent with the above parameter variable name, otherwise it will be invalid !!! # Name = <Variable Name>, value = <Get Value> WB_COOKIE = '' KA_COOKIE = '' if os.environ.get('WB_COOKIE', '') != '': WB_COOKIE = os.environ['WB_COOKIE'] if os.environ.get('KA_COOKIE', '') != '': KA_COOKIE = os.environ['KA_COOKIE'] if WB_COOKIE: Weibo(WB_COOKIE).super_sign() if KA_COOKIE: events = RedeemCode(KA_COOKIE).get_id() codes = RedeemCode(KA_COOKIE).get_box_code() if events else '' if events and codes: ids = [i for i in events if i not in codes[0]] if not ids: log.info('The redemption code has been received') else: log.info(f'Detected {len(ids)} unclaimed redemption code(s)') for id in ids: code = RedeemCode(KA_COOKIE).get_code(id) status = 'Original god exchange code' if code else 'Original God Weibo Campaign reminder' msg = code if code else f'🎁 You have unclaimed gift packages' Notify().send(status=status, msg=msg, hide=True) else: log.info('Cancelled pick-up package')
class RateSong(object): def __init__(self): self.n = Notify() for x in range(1,6): key = '<ctrl>F' + str(x) if not bind(key, lambda y=x: self.rate(y)): exit(1) if not bind('<ctrl>F6', self.show): exit(1) if not bind('<ctrl>F7', self.decr): exit(1) if not bind('<ctrl>F8', self.incr): exit(1) def rate(self, n): rating = get_rating() set_rating(clamp(n)) track = current_track() song = song_string(track) self.n.update(song, rating) self.n.change_stars(n) def decr(self): rating = get_rating() new_rating = clamp(rating - 1) set_rating(new_rating) song = song_string(current_track()) self.n.update(song, rating) self.n.change_stars(new_rating) def incr(self): rating = get_rating() new_rating = clamp(rating + 1) set_rating(new_rating) song = song_string(current_track()) self.n.update(song, rating) self.n.change_stars(new_rating) def show(self): rating = get_rating() song = song_string(current_track()) self.n.update(song, rating) self.n.show()
def test_class_context(self): with Notify() as n: assert n is not None
message['status'] = response['message'] message_list.append(self.message.format(**message)) log.info('Check-in complete') return ''.join(message_list) @property def message(self): return CONFIG.MESSAGE_TEMPLATE if __name__ == '__main__': log.info(f'Genshin Impact Check-In Helper v{CONFIG.GIH_VERSION}') log.info('If you fail to check in, please try to update!') notify = Notify() msg_list = [] ret = success_num = fail_num = 0 """ HoYoLAB Community's COOKIE :param OS_COOKIE: HoYoLAB cookie(s) for one or more accounts. Separate cookies for multiple accounts with the hash symbol # e.g. cookie1text#cookie2text Do not surround cookies with quotes "" if using Github Secrets. """ # Github Actions -> Settings -> Secrets # Ensure that the Name is exactly: OS_COOKIE # Value should look like: login_ticket=xxx; account_id=696969; cookie_token=xxxxx; ltoken=xxxx; ltuid=696969; mi18nLang=en-us; _MHYUUID=xxx # Separate cookies for multiple accounts with the hash symbol # # e.g. cookie1text#cookie2text OS_COOKIE = ''
:param KA_COOKIE: 新浪新手卡的COOKIE.前往 https://ka.sina.com.cn 获取. """ # Github Actions用户请到Repo的Settings->Secrets里设置变量,变量名字必须与上述参数变量名字完全一致,否则无效!!! # Name=<变量名字>,Value=<获取的值> WB_COOKIE = '' KA_COOKIE = '' if os.environ.get('WB_COOKIE', '') != '': WB_COOKIE = os.environ['WB_COOKIE'] if os.environ.get('KA_COOKIE', '') != '': KA_COOKIE = os.environ['KA_COOKIE'] if WB_COOKIE: Weibo(WB_COOKIE).super_sign() if KA_COOKIE: events = RedeemCode(KA_COOKIE).get_id() codes = RedeemCode(KA_COOKIE).get_box_code() if events and codes: ids = [i for i in events if i not in codes[0]] if not ids: log.info('兑换码已全部领取') else: log.info(f'检测到有 {len(ids)} 个未领取的兑换码') for id in ids: code = RedeemCode(KA_COOKIE).get_code(id) if code: Notify().send(status='原神兑换码', msg=code, hide=True) else: log.info('数据获取异常, 取消领取礼包')
def sendmail(receviers, subject, msg=None, attach_files=None): recevier_list = receviers.split(",") # 待发送邮件内容 msg_text = "" if msg: msg_text = msg # 待发送文件 attach_file_list = [] if attach_files: attach_file_list = attach_files.split(",") mail = MailSender() mail.send(recevier_list, subject, msg_text, attach_file_list) if __name__ == '__main__': if len(sys.argv) < 3: print("receviers and subject needed!") elif len(sys.argv) == 3: print("receviers and subject needed!") # sendmail(sys.argv[1], sys.argv[2]) elif len(sys.argv) == 4: Notify("【精排模型】").send_mail(sys.argv[2], sys.argv[3], sys.argv[1]) # sendmail(sys.argv[1], sys.argv[2], sys.argv[3]) else: Notify("【精排模型】").send_mail(sys.argv[2], sys.argv[3], sys.argv[1], sys.argv[4]) # sendmail(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
def alert_cron(): configure_logging() Notify.setup() while True: Notify().check_notification() time.sleep(60 * 60 * 3)
def main(): parser = argparse.ArgumentParser( description='Download FREE eBook every day from www.packtpub.com', formatter_class=argparse.ArgumentDefaultsHelpFormatter, version='2.2.0') parser.add_argument('-c', '--config', required=True, help='configuration file') parser.add_argument('-d', '--dev', action='store_true', help='only for development') parser.add_argument('-e', '--extras', action='store_true', help='download source code (if exists) and book cover') parser.add_argument('-u', '--upload', choices=[SERVICE_DRIVE, SERVICE_DROPBOX, SERVICE_SCP], help='upload to cloud') parser.add_argument('-a', '--archive', action='store_true', help='compress all file') parser.add_argument('-n', '--notify', choices=[SERVICE_GMAIL, SERVICE_IFTTT, SERVICE_JOIN], help='notify after claim/download') parser.add_argument('-s', '--store', choices=[DB_FIREBASE], help='store info') parser.add_argument('-o', '--claimOnly', action='store_true', help='only claim books (no downloads/uploads)') group = parser.add_mutually_exclusive_group() group.add_argument('-t', '--type', choices=['pdf', 'epub', 'mobi'], default='pdf', help='specify eBook type') group.add_argument('--all', dest='types', action='store_const', const=['pdf', 'epub', 'mobi'], help='all eBook types') args = parser.parse_args() now = datetime.datetime.now() log_info('[*] {date} - Fetching today\'s books'.format( date=now.strftime("%Y-%m-%d %H:%M"))) packtpub = None try: config = config_file(args.config) #ip_address() log_info('[*] getting daily free ebook') packpub = Packpub(config, args.dev) run(packpub, args, config) except KeyboardInterrupt: log_error('[-] interrupted manually') except Exception as e: log_debug(e) if args.notify: Notify(config, None, None, args.notify).sendError(e, 'global') log_info('[*] done')
# -*- coding: utf8 -*- from datetime import datetime, timedelta from notify import Notify import config if __name__ == "__main__": # Set the last date to yesterday so the logic will work for today. last_date = datetime.utcnow() - timedelta(days=1) while True: today = datetime.utcnow() + timedelta(hours=11) # If it's the right time of the day... if today.day > last_date.day and today.hour == config.HOUR: last_date = today # Get all the users and send them a notifcation. with Notify() as n: [ n.send_notification(user_id=user['facebook_id']) for user in n.get_users().json()['users'] ]
message['status'] = response['message'] message_list.append(self.message.format(**message)) log.info('签到完毕') return ''.join(message_list) @property def message(self): return CONFIG.MESSGAE_TEMPLATE if __name__ == '__main__': log.info(f'🌀原神签到小助手 {version()}') log.info('若签到失败, 请尝试更新!') log.info('任务开始') notify = Notify() msg_list = [] ret = success_num = fail_num = 0 """miHoYo BBS COOKIE :param COOKIE: 米游社的COOKIE.多个账号的COOKIE值之间用 # 号隔开,例如: 1#2#3#4 """ # Github Actions用户请到Repo的Settings->Secrets里设置变量,变量名字必须与上述参数变量名字完全一致,否则无效!!! # Name=<变量名字>,Value=<获取的值> COOKIE = '' if os.environ.get('COOKIE', '') != '': COOKIE = os.environ['COOKIE'] cookie_list = COOKIE.split('#') log.info(f'检测到共配置了 {len(cookie_list)} 个帐号') for i in range(len(cookie_list)):
def start(self): #ignore pings if self.event['name'] == 'ping': return #ignore all resources other than services. if self.event['resourceType'] != 'service': return #for services, we only care if the status has become active, or removed if self.event['data']['resource']['state'] == 'active' or self.event['data']['resource']['state'] == 'removed': log.info('Detected a change in rancher services. Begin processing.') log.info(self._raw) #get the current event's stack information r = requests.get(self.event['data']['resource']['links']['environment'], auth=(self.access_key, self.secret_key), headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} ) r.raise_for_status() service_stack_response = r.json() try: notify = Notify(service_stack_response, 'started' if self.event['data']['resource']['state'] == 'active' else 'stopped') notify.send() except: log.error('An error occured while trying to notify stack change') # list of running stacks, called environments in api r = requests.get(self.api_endpoint + '/environments', auth=(self.access_key, self.secret_key), headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} ) r.raise_for_status() stacks_response = r.json() loadbalancer_entries = [] loadbalancer_service = None log.info(' -- Finding all Stacks') for stack in stacks_response['data']: stack_name = stack['name'] # make sure the stack/environment is active if stack['state'] != 'active': log.info(' -- -- Ignoring {0} stack because it\'s not active'.format(stack_name)) continue if stack_name == 'utility': loadbalancer_service = self.get_utility_loadbalancer(stack) depot_services = self.get_stack_services(stack) for service in depot_services: port = service['launchConfig'].get('labels',{}).get('depot.lb.port', '80') loadbalancer_entries.append({ 'serviceId': service['id'], 'ports': [ stack_name + '.' + self.domain + ':' + self.external_loadbalancer_http_port + '=' + port ] }) if loadbalancer_service is None: raise Exception('Could not find the Utility stack external load balancer. This should never happen') log.info(' -- Setting loadbalancer entries:') log.info(loadbalancer_entries) self.set_loadbalancer_links(loadbalancer_service, loadbalancer_entries) log.info('Finished processing')