def send_notifications(self, tx, coin, fraction): body = self.body(tx, coin, fraction) for user in users: if user.email: send_email(user.email, subject, body) if user.phone: send_text(user.email, subject, body)
def reply(request): if request['REQUEST_METHOD'] == 'GET': return static_file('static/reply.html') invitedata = read_post_data(request) deltagar_id = invitedata["id"][0] status = invitedata["status"][0] if status == "ja": foto = invitedata["foto"][0] else: foto = "" db.cursor.execute( ''' UPDATE deltagare SET status = ?, foto = ? WHERE id = ? AND status = "inbjuden"; ''', (status, foto, deltagar_id)) db.commit() kodstuga = deltagare.get_kodstuga(deltagar_id) if status == "ja" and kodstuga["epost_status_ja"] != "inaktiv": kontakter = kontaktpersoner.fordeltagare(deltagar_id) this_deltagare = deltagare.get_one(deltagar_id) meddelande = kodstuga["epost_text_ja"] meddelande = meddelande.replace("%namn%", this_deltagare["fornamn"]).replace( "%kodstuga%", kodstuga["namn"]) for kontakt in kontakter: send_email(kontakt["epost"], kodstuga["epost_rubrik_ja"], meddelande) return static_file('static/reply_done.html')
def main(): prepare() sp = SubprocessManager() results = sp.results sp.run('python3 manage.py clearsessions') # sp.run(f'rm {project_root}/caches/*') sp.run('ls /var/log/letsencrypt/') for log in results[-1].stdout.split('\n'): if log != 'letsencrypt.log' and log: sp.run('rm /var/log/letsencrypt/' + log) sp.run('ls /var/log/') for log in results[-1].stdout.split('\n'): if '-20' in log: sp.run('rm /var/log/' + log) try: for result in results: result.check_returncode() except Exception: message = '清理垃圾文件时发生了错误!\n\n' + traceback.format_exc() + '\n' error = True else: message = '垃圾文件已清理干净\n' error = False setup_django() message += sp.format_results() if error: send_email('www.fossen.cn | 清理垃圾文件', message) return message
def send_utskick_once(): logger.info("Datumspecifika utskick genomförs.") found = db.cursor.execute( ''' SELECT id, kodstugor_id, typ, rubrik, text, datum, status FROM utskick WHERE datum < ? AND status = "aktiv" ORDER BY datum; ''', (int(time.time()), )) def to_headers(row): ut = {} for idx, col in enumerate(found.description): ut[col[0]] = row[idx] return ut up_for_sending = found.fetchall() if len(up_for_sending) > 0: for utskick in list(map(to_headers, up_for_sending)): logger.info("Utskick för kostuga %s genomförs.", utskick["kodstugor_id"]) for mottagare in kontaktpersoner.for_kodstuga( utskick["kodstugor_id"]): message = utskick["text"].replace( "%namn%", mottagare["deltagare_fornamn"]).replace( "%kodstuga%", mottagare["kodstugor_namn"]) if utskick["typ"] == "sms": send_sms(mottagare["telefon"], message) elif utskick["typ"] == "e-post": send_email(mottagare["epost"], utskick["rubrik"], message) db.cursor.execute( ''' UPDATE utskick SET status = "skickad" WHERE id = ?; ''', (utskick["id"], )) db.commit() logger.info("Datumspecifika utskick genomförda.")
def send_invites_once(): found = db.cursor.execute(''' SELECT kodstugor.namn AS kodstuga, kodstugor.typ AS kodstuga_typ, deltagare.id AS deltagare_id, deltagare.status AS deltagare_status, deltagare.fornamn AS deltagare_fornamn, kontaktpersoner.epost AS kontaktperson_epost FROM deltagare INNER JOIN kontaktpersoner_deltagare ON deltagare.id=kontaktpersoner_deltagare.deltagare_id INNER JOIN kontaktpersoner ON kontaktpersoner.id=kontaktpersoner_deltagare.kontaktpersoner_id INNER JOIN kodstugor ON deltagare.kodstugor_id=kodstugor.id WHERE deltagare.status = "inbjudan" ORDER BY deltagare.id; ''') def to_headers(row): ut = {} for idx, col in enumerate(found.description): ut[col[0]] = row[idx] return ut deltagare_id = False for row in list(map(to_headers, found.fetchall())): if not deltagare_id: deltagare_id = row["deltagare_id"] if row["deltagare_id"] != deltagare_id: break message = texter.get_one("Erbjudande om plats " + row["kodstuga_typ"])["text"] link = "https://besk.kodcentrum.se/reply?id=" + row["deltagare_id"] message = message.replace("%namn%", row["deltagare_fornamn"]).replace( "%kodstuga%", row["kodstuga"]).replace("%länk%", link) send_email(row["kontaktperson_epost"], "Erbjudande om plats", message) db.cursor.execute( ''' UPDATE deltagare SET status = "inbjuden" WHERE id = ?; ''', (deltagare_id, )) db.commit()
def rent_dev(id): try: print request.form Lend_Record.lend_pending( device_id=id, user_name=request.form['user_name'], user_department=request.form['user_department'], user_building=request.form['user_building'], user_floor=request.form['user_floor'], user_room=request.form['user_room']) recipients = request.form['email'] tools.send_email([recipients]) return render_template('result.html', result=u'预订成功,请查收邮件填写申请表并签字,提交给管理员.') except StandardError, e: return render_template('result.html', result=u'出错了!') print e
def read_item(snid: int, platform: str, alg: str, params: Optional[str] = None): if snid <= 0: raise HTTPException(status_code=404, detail="snid is not a valid user identifier") try: sel = sels.get(platform) if not sel: sel = Selector(platform) sels[platform] = sel nodes, edges = sel.ego_graph(int(snid)) except (OperationTimedOut) as e: raise HTTPException(status_code=408, detail="cassandra.OperationTimedOut") except UnresolvableContactPoints as e: raise HTTPException(status_code=503, detail="cassandra.UnresolvableContactPoints") except (Exception) as e: raise HTTPException(status_code=500, detail=str(e)) if not edges: raise HTTPException(status_code=404, detail="Item not found") if params: params = params.split(',') params = {k: v for k, v in zip(params[::2], params[1::2])} try: cs = find_communities(len(nodes), edges, alg, params) except: msg = traceback.format_exc() tools.send_email(body=msg) logging.error(msg) raise HTTPException(status_code=500) if cs is None: raise HTTPException(status_code=501, detail="Not Implemented") data = canvas_data(nodes, edges, cs) data['snid'] = snid data['platform'] = platform return data
def main(): time.sleep(random.random() * 3600) sp = SubprocessManager() sp.run('/home/fossen/certbot-auto --no-self-upgrade renew') if 'Cert not yet due for renewal' in sp.results[-1].stderr: return sp.format_results() try: for r in sp.results: r.check_returncode() except Exception: message = '续期SSL证书时发生了错误!\n\n' + traceback.format_exc() + '\n' else: message = 'SSL证书已续期\n' setup_django() message += sp.format_results() send_email('www.fossen.cn | 续期SSL证书', message) return message
def main(): for i in range(1, 15): try: json_data = get_index_list(i) print('访问114首页ajax接口:{}'.format(json_data)) for item in json_data['data']['list']: print('每个医院的大致简介:{}'.format(item)) if item['name'] in filter_hospital: print('要过滤的医院{}'.format(item)) break if '一级' in item['levelText'] or '二级' in item['levelText']: print('要过滤的医院{}'.format(item)) break try: detail_json = get_deatil_list(item['code']) for item2 in detail_json['data']['list']: print('医院科室分类的情况:{}'.format(item2)) for item3 in item2['subList']: print('具体到某个医院某个门诊的某个小门诊:{}'.format(item3)) if '口腔' not in item3['name']: continue try: final_json = get_detail( item3['dept1Code'], item3['code'], item['code']) print('我想要得到的具体信息:{}'.format(final_json)) for item4 in final_json['data']['calendars']: info = '医院:{},levelText:{},一级科室:{},二级科室:{},时间:{}-->{},挂号情况:{}'.format( item['name'], item['levelText'], item2['name'], item3['name'], item4['dutyDate'], item4['weekDesc'], item4['status']) print(info) if item4['status'] == 'AVAILABLE': send_email(info) except Exception as e: print(e) except Exception as e: print(e) except Exception as e: print(e)
def main(): sp = SubprocessManager() try: sp.run('git checkout master') sp.run('git pull origin master') results = sp.results results[-1].check_returncode() if 'Already up' in results[-1].stdout: #no need to continue message = sp.format_results() print(message) return message sp.run('docker restart fossensite') if results[-1].returncode: error_result = results[-1] sp.run('docker inspect -f {{.State.Status}} fossensite') if 'running' not in results[-1].stdout: sp.run('git reset --hard HEAD^') sp.run('docker restart fossensite') sp.run('docker inspect -f {{.State.Status}} fossensite') # raise error error_result.check_returncode() sp.run(f'chown -R 1000:1000 {project_root}') except Exception: message = '部署过程中发生了错误!\n\n' + traceback.format_exc() + '\n' else: message = '部署完成\n' setup_django() message += sp.format_results() print(message) send_email('www.fossen.cn | 自动部署结果', message) sp.run('docker restart fossensite-deploy') return message
def send_email_reminders_once(): datum = arrow.utcnow().shift( hours=24).to('Europe/Stockholm').format('YYYY-MM-DD') logger.info("Sending Email reminders for: " + datum) found = db.cursor.execute( ''' SELECT id, kodstugor_id, datum FROM kodstugor_datum WHERE datum = ? ORDER BY datum; ''', (datum, )) def to_headers(row): ut = {} for idx, col in enumerate(found.description): ut[col[0]] = row[idx] return ut for utskick in list(map(to_headers, found.fetchall())): kodstuga = kodstugor.get_kodstuga(utskick["kodstugor_id"]) if kodstuga["epost_status"] == "inaktiv": continue for mottagare in kontaktpersoner.for_kodstuga(utskick["kodstugor_id"]): link = "https://besk.kodcentrum.se/svar?id=" + mottagare[ "deltagare_id"] + "&datum=" + datum message = kodstuga["epost_text"].replace( "%namn%", mottagare["deltagare_fornamn"]).replace( "%kodstuga%", mottagare["kodstugor_namn"]).replace( "%datum%", datum).replace("%länk%", link) send_email(mottagare["epost"], kodstuga["epost_rubrik"], message)
def add_or_update_admin(request): post_data = read_post_data(request) if "flytta" in post_data: for flytta_id in post_data["flytta"]: add_roller(post_data["kodstugor_id"][0], "volontär", flytta_id) elif "flera" in post_data: for i, namn in enumerate(post_data["namn"]): data = ( post_data["namn"][i], post_data["epost"][i], phonenumber_to_format(post_data["telefon"][i]), arrow.get("2090-01-01").timestamp(), ) try: db.cursor.execute(""" INSERT INTO volontarer (namn, epost, telefon, utdrag_datum) VALUES (?,?,?,?) """, data) db.commit() add_roller( post_data["kodstugor_id"][0], "volontär", get_id(post_data["epost"][i]) ) send_email( post_data["epost"][i], "BESK-konto aktiverat", texter.get_one("BESK-konto aktiverat")["text"] ) except db.sqlite3.IntegrityError: pass else: try: phone_number = phonenumbers.parse(post_data["telefon"][0], "SE") phone_number_str = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164) except Exception: raise Error400("Fyll i ett giltigt telefonummer.") if not phonenumbers.is_valid_number(phone_number): raise Error400("Fyll i ett giltigt telefonummer.") if "id" in post_data: data = ( post_data["namn"][0], post_data["epost"][0], phone_number_str, arrow.get("2090-01-01").timestamp(), post_data["id"][0] ) db.cursor.execute(""" UPDATE volontarer SET namn = ?, epost = ?, telefon = ?, utdrag_datum = ? WHERE id = ? """, data) db.commit() roll_list = [] if "kodstugor_id" in post_data: for form_index, value in enumerate(post_data["kodstugor_id"]): roll_list.append( { "kodstugor_id": value, "roll": post_data["roller"][form_index] } ) add_or_update_roller(roll_list, post_data["id"][0]) else: add_or_update_roller([], post_data["id"][0]) else: data = ( post_data["namn"][0], post_data["epost"][0], phone_number_str, arrow.get("2090-01-01").timestamp(), ) try: db.cursor.execute(""" INSERT INTO volontarer (namn, epost, telefon, utdrag_datum) VALUES (?,?,?,?) """, data) db.commit() send_email( post_data["epost"][0], "BESK-konto aktiverat", texter.get_one("BESK-konto aktiverat")["text"] ) roll_list = [] if "kodstugor_id" in post_data: for form_index, value in enumerate(post_data["kodstugor_id"]): roll_list.append( { "kodstugor_id": value, "roll": post_data["roller"][form_index] } ) add_or_update_roller(roll_list, get_id(post_data["epost"][0])) except db.sqlite3.IntegrityError: raise Error400("E-Postadressen finns redan.")
dfs = []; buoys = [] for buoy in bys.keys(): if len(buoy) > 1 or not bys[buoy]['active']: # don't include other buoys continue fname = 'tabs_' + buoy + '_ven' df = pd.read_table(path.join('..', 'daily/', fname), parse_dates=True, index_col=0, na_values=[-999]) df = df.tz_localize('utc') # all files are read in utc # if dataframe is too short, don't include if len(df) < 10: dfs.append(None) # check if any of dataset is from within the past 5 days before appending elif (pd.Timestamp('now', tz='utc') - df.index[-1]).days < 5: dfs.append(df) else: dfs.append(None) buoys.append(buoy) fig1 = plot_buoy.currents(dfs[:5], buoys[:5]) fig2 = plot_buoy.currents(dfs[5:], buoys[5:]) fig1.savefig(path.join('..', 'daily', 'currents1.pdf')) fig1.savefig(path.join('..', 'daily', 'currents1.png')) fig2.savefig(path.join('..', 'daily', 'currents2.pdf')) fig2.savefig(path.join('..', 'daily', 'currents2.png')) close(fig1) close(fig2) # send error email if eflag was set to True somewhere if eflag: tools.send_email()
help='name of a social network') parser.add_argument("--email", action='store_true', help="send email on completion") args = parser.parse_args() basedir = '../data/%s/' % args.socialnet fcluster = join(basedir, 'cluster.pkl') fname = join(basedir, 'post_geo.csv') fnodes = join(basedir, 'nodes.bin') if isfile(fcluster): with open(fcluster, 'rb') as f: cl = pickle.load(f) else: typecode = 'I' if args.socialnet == 'vk' else 'L' cl = ccmgCluster(load_vector(fnodes, typecode), args.socialnet) cl.save(fcluster) asyncio.run( query_all(cl, partial(account_rubrs, org='%s.com' % args.socialnet), rec_fn, fname, chunk_size=500, threads_per_host=8)) if args.email: tools.send_email(body="%s completed" % __file__)
def new(request): data_to_db = {"kids": [], "adults": []} status = "ansökt" formdata = read_post_data(request) if request["BESK_login"]["user"]: user_is_admin = login.is_admin( request["BESK_login"]["user"]["user"]["email"]) else: user_is_admin = False if "invite_now" in formdata: if user_is_admin and formdata["invite_now"][0] == "inbjudan": status = "inbjudan" if user_is_admin and formdata["invite_now"][0] == "ja": status = "ja" if "approve" not in formdata: raise Error400("Du måste acceptera Kodcentrums Integritetspolicy.") try: kodstugaid = formdata["kodstuga"][0] (kodstuga, kodstuga_typ) = db.cursor.execute( """ SELECT namn, typ FROM kodstugor WHERE id = ?; """, (kodstugaid, )).fetchone() except Exception: raise Error400("Välj en aktivitet.") now = int(time.time()) for i, _ in enumerate(formdata["barn_efternamn"]): if user_is_admin: foto = formdata["foto"][i] else: foto = None if formdata["barn_fornamn"][i] == "": raise Error400("Fyll i förnamn för samtliga barn.") if formdata["barn_efternamn"][i] == "": raise Error400("Fyll i efternamn för samtliga barn.") if formdata["kon"][i] == "": raise Error400("Fyll i kön för samtliga barn.") if formdata["klass"][i] == "": raise Error400("Fyll i klass för samtliga barn.") if formdata["skola"][i] == "": raise Error400("Fyll i skola för samtliga barn.") data_to_db["kids"].append( (uuid.uuid4().hex, kodstugaid, formdata["barn_fornamn"][i], formdata["barn_efternamn"][i], formdata["kon"][i], formdata["klass"][i], formdata["skola"][i], foto, now, status)) for i, value in enumerate(formdata["vuxen_efternamn"]): try: phone_number = phonenumbers.parse(formdata["telefon"][i], "SE") except Exception: raise Error400("Fyll i ett giltigt telefonummer för alla målsmän.") if not phonenumbers.is_valid_number(phone_number): raise Error400("Fyll i ett giltigt telefonummer för alla målsmän.") if formdata["vuxen_fornamn"][i] == "": raise Error400("Fyll i förnamn för alla målsmän.") if formdata["vuxen_efternamn"][i] == "": raise Error400("Fyll i efternamn för alla målsmän.") if formdata["email"][i] == "": raise Error400("Fyll i en email för alla målsmän.") data_to_db["adults"].append( (uuid.uuid4().hex, formdata["vuxen_fornamn"][i], formdata["vuxen_efternamn"][i], formdata["email"][i], phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164))) for kid in data_to_db["kids"]: db.cursor.execute( "INSERT INTO deltagare (id,kodstugor_id,fornamn,efternamn,kon,klass,skola,foto,datum,status) VALUES (?,?,?,?,?,?,?,?,?,?)", kid) # noqa: E501 for adult in data_to_db["adults"]: db.cursor.execute( "INSERT INTO kontaktpersoner (id,fornamn,efternamn,epost,telefon) VALUES (?,?,?,?,?)", adult) for adult in data_to_db["adults"]: for kid in data_to_db["kids"]: db.cursor.execute( "INSERT INTO kontaktpersoner_deltagare (kontaktpersoner_id, deltagare_id) VALUES (?,?)", (adult[0], kid[0])) hittade = (formdata["hittade"][0], ) db.cursor.execute("INSERT INTO hittade (hittade) VALUES (?)", hittade) db.commit() if status == "ansökt": mailmessage = texter.get_one("Intresseanmälan " + kodstuga_typ)["text"].replace( "%kodstuga%", kodstuga) mailsubject = "Tack för din intresseanmälan" for email in formdata["email"]: send_email(email, mailsubject, mailmessage) return {"applied": data_to_db}
def send_mail(): tools.send_email() return "ok"
ids = sort_people(fin, fout, anew=1) tsar_download(ids, 'comment', platform) tsar_download(ids, 'share', platform) def download(): download_vk() # download_facebook() # download_twitter() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--email", action='store_true', help="send email on completion/error") args = parser.parse_args() try: download() except KeyboardInterrupt: exit() except: if args.email: tools.send_email(body=traceback.format_exc()) raise if args.email: tools.send_email(body="%s completed" % __file__)
Use this script by : ``` $ chmod +x absPath/daily_check.py # make this script run-able $ crontab -e # write these cmd in 30 8 * * * python3 /home/pi/AgRobot/src/management_scripts/daily_check.py # run 8:30 per day # add some more daily running ``` ------------------------------------------------------------ ATTENTION PLEASE Edit crontab with 'crontab -e' as below, then it can be executed automatic ------------------------------------------------------------ """ import sys, os, time sys.path.append("/home/pi/AgRobot/src/") from tools import send_email title = 'I am fine' content = 'I am pi from HuYang building ,I am alive.' address = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] send_email(title, content, address)
'active']: # don't include other buoys continue fname = 'tabs_' + buoy + '_ven' df = pd.read_table(path.join('..', 'daily/', fname), parse_dates=True, index_col=0, na_values=[-999]) df = df.tz_localize('utc') # all files are read in utc # if dataframe is too short, don't include if len(df) < 10: dfs.append(None) # check if any of dataset is from within the past 5 days before appending elif (pd.Timestamp('now', tz='utc') - df.index[-1]).days < 5: dfs.append(df) else: dfs.append(None) buoys.append(buoy) fig1 = plot_buoy.currents(dfs[:5], buoys[:5]) fig2 = plot_buoy.currents(dfs[5:], buoys[5:]) fig1.savefig(path.join('..', 'daily', 'currents1.pdf')) fig1.savefig(path.join('..', 'daily', 'currents1.png')) fig2.savefig(path.join('..', 'daily', 'currents2.pdf')) fig2.savefig(path.join('..', 'daily', 'currents2.png')) close(fig1) close(fig2) # send error email if eflag was set to True somewhere if eflag > 7: logger_rd.warning('eflag=%i; sending email.' % eflag) tools.send_email()