77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
import argparse
|
|
import json
|
|
import logging
|
|
import time
|
|
|
|
from tempfile import NamedTemporaryFile
|
|
from collections import namedtuple
|
|
|
|
import schedule
|
|
|
|
from plot import get_plot
|
|
from sources import IsFsWIAIopen
|
|
from targets import Client, MatrixClient, TelegramClient
|
|
|
|
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s:%(message)s', level=logging.DEBUG, datefmt="%Y.%m.%d %H:%M:%S")
|
|
log = logging.getLogger(__name__)
|
|
|
|
Config = namedtuple("Config", ['sleep', 'plot_interval', 'clients', 'source', 'loop'])
|
|
|
|
def publish(clients, fn, **kwargs):
|
|
for client in clients:
|
|
fn(client, **kwargs)
|
|
|
|
def post_plot(config):
|
|
with NamedTemporaryFile() as target:
|
|
plot_file, last = get_plot(target)
|
|
plot_file.seek(0)
|
|
publish(config.clients, Client.post_image, file=plot_file, name="")
|
|
|
|
def has_argument(args, key):
|
|
return key in args and args[key]
|
|
|
|
def get_config(args):
|
|
settings = json.load(open(args['config']))
|
|
clients = []
|
|
for client in (MatrixClient, TelegramClient):
|
|
if client.key in settings['groups']:
|
|
clients.append(client(**settings['groups'][client.key]))
|
|
config = Config(
|
|
sleep=args['interval'] if has_argument(args, 'interval') else settings['sleep'],
|
|
plot_interval=settings['plot_interval'],
|
|
clients=clients,
|
|
source=IsFsWIAIopen(texts=settings['texts']),
|
|
loop=args['loop'])
|
|
return config
|
|
|
|
def setup(config):
|
|
schedule.every(config.plot_interval).seconds.do(lambda: post_plot(config))
|
|
|
|
def main(args={'config': "settings.json"}):
|
|
config = get_config(args)
|
|
|
|
status = config.source.get_status()
|
|
publish(config.clients, Client.post_text, text=status.text)
|
|
setup(config)
|
|
|
|
while config.loop:
|
|
try:
|
|
schedule.run_pending()
|
|
new_status = config.source.get_status()
|
|
if not new_status.doorstate == status.doorstate:
|
|
status = new_status
|
|
publish(config.clients, Client.post_text, text=status.text)
|
|
time.sleep(config.sleep)
|
|
except Exception as e:
|
|
log.exception(e)
|
|
if not config.loop:
|
|
post_plot(config)
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description="DoorStateBot")
|
|
parser.add_argument("--config", "-c", default="settings.json", help="Configuration file")
|
|
parser.add_argument("--loop", "-l", action="store_false", help="Loop")
|
|
parser.add_argument("--interval", "-i", help="Interval")
|
|
args = parser.parse_args()
|
|
main(vars(args))
|