def main(logger): envse = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_NAME', 'DISCORDBOT_TOKEN'] envsc = [ 'LOCATION', 'XRAIN_ZOOM', 'MANET', 'GOOGLE_MAPS_API_KEY', 'DARK_SKY_API_KEY', 'CADVISOR', 'CONTAINERS', 'MORNING', 'EVENING', 'XRAIN_LAT', 'XRAIN_LON', 'PORT' ] f = util.environ(envse, 'error') util.environ(envsc, 'warning') if f: logger.error('error: some environment variables are not set. exiting.') sys.exit(1) sendqueue = queue.Queue() httploop = asyncio.new_event_loop() ap = api.API(httploop, sendqueue, logger, os.environ.get('DISCORDBOT_TOKEN')) threading.Thread(target=ap.run, name='api', daemon=True).start() wea = weather.Weather(sendqueue, logger) mon = monitoring.Monitoring(sendqueue, logger) scheduleloop = asyncio.new_event_loop() sched = Scheduler(sendqueue, wea, mon, logger, scheduleloop) threading.Thread(target=sched.run, name='scheduler', daemon=True).start() logger.debug('launch discord client') client = discordbot.DiscordClient(os.environ.get('DISCORD_CHANNEL_NAME'), sendqueue, wea, mon, logger) client.run(os.environ.get('DISCORD_TOKEN'))
def main(): envse = [ 'GOOGLE_OAUTH_CLIENT', 'GOOGLE_OAUTH_SECRET', 'DISCORDBOT', 'DISCORDBOT_TOKEN', 'BASE_URL', 'S3_BUCKET', 'S3_PREFIX' ] out = util.Output(logdir, util.environ_bool('DEBUG')) f = util.environ(envse, 'error') if f: out.error('error: some environment variables are not set. exiting.') sys.exit(1) if os.environ.get('ONESHOT') is None and ( os.environ.get('SCHEDULE_TIME') is None or os.environ.get('SCHEDULE_WEEKDAY') is None): out.error( 'error: environment variables ONESHOT or (SCHEDULE_TIME and SCHEDULE_WEEKDAY) must be set. exiting.' ) sys.exit(1) os.makedirs(catalogdir, exist_ok=True) try: redirect_url = '{0}{1}'.format(os.environ['BASE_URL'], callback_url) cred = credential.Credential(out, os.environ['GOOGLE_OAUTH_CLIENT'], os.environ['GOOGLE_OAUTH_SECRET'], token_url, scope, redirect_url, authorization_base_url, tokendir) cb = callback.Callback(asyncio.new_event_loop(), out, cred, callback_url) threading.Thread(target=cb.run, name='callback', daemon=True).start() album = util.environ_bool('ALBUM') library = util.environ_bool('LIBRARY') back = backup.Backup(out, cb, cred, os.environ['S3_BUCKET'], os.environ['S3_PREFIX'], catalogdir, album, library) if cred.load(): out.info('using saved token') else: authorization_url = cred.authorization_step() out.message('Please authenticate the application: {0}'.format( authorization_url)) cred.wait_authorization() out.info('main(): authorized, email={}'.format(cred.email)) if util.environ_bool('ONESHOT'): back.run() out.info('main(): all tasks done') else: sched = Scheduler(None, out, back) sched.run() out.error('main(): scheduler down!') except Exception as e: out.exception('error: main', e)
def dockerps(self, show_all): try: env = ['CADVISOR', 'CONTAINERS'] if util.environ(env, 'warning'): self.sendqueue.put({ 'message': 'error: One or some environment variables are not set. Must be set {0}' .format(' '.join(env)) }) return watch_container = {} for c in os.environ.get('CONTAINERS').split(','): watch_container[c] = False if self.running_last_period.get(c) is None: self.running_last_period[c] = True url = 'http://{0}/api/v1.3/containers/docker'.format( os.environ.get('CADVISOR')) r = requests.get(url).json() #debug #self.logger.debug(r['name']) for container in r['subcontainers']: c = requests.get('http://{0}/api/v1.3/containers{1}'.format( os.environ.get('CADVISOR'), container['name'])).json() watch_container[c['spec']['labels'] ['com.docker.compose.service']] = True if show_all: text = '' for k, v in watch_container.items(): flag = util.emoji('ok') if v else util.emoji('bad') text += '{0} {1}\n'.format(flag, k) self.running_last_period[k] = v self.sendqueue.put({'message': '{0}'.format(text)}) else: text = '' count = 0 for k, v in watch_container.items(): if v == False and self.running_last_period.get(k) == True: text += '{0} '.format(k) count += 1 self.running_last_period[k] = v if count > 0: self.sendqueue.put({ 'message': '{0} {1} が停止しています'.format(util.emoji('bad'), text) }) except Exception as e: msg = 'dockerps()' self.logger.exception(msg, stack_info=True) self.sendqueue.put({ 'message': 'error {}: {}({})'.format(msg, e.__class__.__name__, str(e)) })
def main(logger): envse = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_NAME', 'NOTIFYD_TOKEN'] envsc = ['PORT', 'RECEIVE'] dotenv.load_dotenv() f = util.environ(envse, 'error') util.environ(envsc, 'warning') if f: logger.error('error: some environment variables are not set. exiting.') sys.exit(1) sendqueue = queue.Queue() httploop = asyncio.new_event_loop() ap = api.API(httploop, sendqueue, logger, os.environ.get('NOTIFYD_TOKEN')) threading.Thread(target=ap.run, name='api', daemon=True).start() logger.debug('launch discord client') client = discordclient.DiscordClient( os.environ.get('DISCORD_CHANNEL_NAME'), sendqueue, logger, os.environ.get('RECEIVE')) client.run(os.environ.get('DISCORD_TOKEN'))
def forecast(self, loc, lat, lng): try: env = ['GOOGLE_MAPS_API_KEY', 'DARK_SKY_API_KEY'] if util.environ(env, 'warning'): self.sendqueue.put({ 'message': 'error: One or some environment variables are not set. Must be set {0}' .format(' '.join(env)) }) return url = 'https://api.darksky.net/forecast/{0}/{1},{2}?lang=ja&units=si'.format( os.environ.get('DARK_SKY_API_KEY'), str(self.lat), str(self.lng)) #debug self.logger.debug(url) r = requests.get(url).json() hourly = '' count = 0 for item in r['hourly']['data']: count += 1 if count >= 20: break if count % 2 == 1: continue hourly += '{0}: {1}, {2}度, {3}%\n'.format( util.unixtimestrt(item['time']), item['summary'], int(item['temperature']), int(item['humidity'] * 100)) self.sendqueue.put({ 'message': '''{0}時点の{1}の天気: {2}, {3}度, 湿度{4}%, 風速{5}m/s 予報: {6} {7}'''.format(util.unixtimestr(r['currently']['time']), loc, r['currently']['summary'], int(r['currently']['temperature']), int(r['currently']['humidity'] * 100), int(r['currently']['windSpeed']), r['hourly']['summary'], hourly) }) except Exception as e: msg = 'forecast()' self.logger.exception(msg, stack_info=True) self.sendqueue.put({ 'message': 'error {}: {}({})'.format(msg, e.__class__.__name__, str(e)) })
def xrain(self, loc, lat, lng): try: env = ['XRAIN_ZOOM', 'MANET'] if util.environ(env, 'warning'): self.sendqueue.put({ 'message': 'error: One or some environment variables are not set. Must be set {0}' .format(' '.join(env)) }) return # & -> %26 url = 'http://{0}/?url=http://www.river.go.jp/x/krd0107010.php?lon={1}%26lat={2}%26opa=0.4%26zoom={3}%26leg=0%26ext=0&width=1000&height=850'.format( os.environ.get('MANET'), lng, lat, os.environ.get('XRAIN_ZOOM')) # debug self.logger.debug(url) r = requests.get(url) if r.status_code == 200: if 'image' in r.headers['content-type']: with open('/tmp/xrain.png', 'wb') as f: f.write(r.content) self.sendqueue.put({'imagefile': r.content}) else: # error self.sendqueue.put({ 'message': 'could not get screenshot. content-type={0}'.format( r.headers['content-type']) }) return else: self.sendqueue.put({ 'message': 'could not get screenshot. code={0}'.format(r.status_code) }) except Exception as e: msg = 'xrain()' self.logger.exception(msg, stack_info=True) self.sendqueue.put({ 'message': 'error {}: {}({})'.format(msg, e.__class__.__name__, str(e)) })
if main != None: main.close() sys.exit(0) if __name__ == "__main__": # log name = 'weather-monitor' datadir = f'/data/{name}' if os.environ.get('DEBUG') else f'data/{name}' logdir = f'/logs/{name}' if os.environ.get('DEBUG') else f'logs/{name}' os.makedirs(datadir, exist_ok=True) os.makedirs(logdir, exist_ok=True) logger, starttime = initlogger(name, logdir) logger.info(f'started {name} at {starttime}') # env envse = ['NOTIFYD_TOKEN', 'OWM_API_KEY', 'LAT', 'LON', 'KISHODAI', 'CITY'] envsc = [] f = util.environ(envse, 'error', False) util.environ(envsc, 'warning', False) if f: logger.error('error: some environment variables are not set. exiting.') sys.exit(1) # signal signal.signal(signal.SIGTERM, termed) # main main = Main(logger, datadir) main.run()
logger.exception('download()', stack_info=True) failureCount += 1 photoCurrent += 1 logger.info( '{0}/{1}: downloaded photos in album "{2}", total={3}, success={4}, failure={5}' .format(albumCurrent + 1, len(albums), albumName, len(photos), successCount, failureCount)) albumCurrent += 1 if successCount == len(albums): albumSuccessCount += 1 else: albumFailureCount += 1 logger.info( 'downloaded albums, total={0}, success={1}, failure={2}'.format( len(albums), albumSuccessCount, albumFailureCount)) if __name__ == '__main__': envse = ['S3_BUCKET', 'S3_PREFIX', 'EMAIL'] f = util.environ(envse, 'error') if f: print('error: some environment variables are not set. exiting.', file=sys.stderr) sys.exit(1) download()