def __init__(self): self.lat = Config().get()['Position']['Latitude'] self.lng = Config().get()['Position']['Longitude'] self.url = "https://api.sunrise-sunset.org/json?lat=%s&lng=%s&date=%s&formatted=0" self.data = None self.cacheKey = None self.fetch()
def update(self, update, context): import subprocess import sys subprocess.Popen( "sleep 5 && sh %s &> %s" % (Config().get()['Updater']['Path'], Config().get()['Logger']['Path']), shell=True) sys.exit(0)
def sendLatest(self, chat_id): latest = self.Capture() path = '%s%s_c%s_02%s' % ( Config().get()["MotionDetector"]["Folder"], "latest", 0, Config().get()["MotionDetector"]["Extension"]) Logger().logger.info(path) cv2.imwrite(path, latest) FeroxBot().sendImage(path, chat_id)
def test_config(self): """ Test Config object """ print("Start test of Config class...") c = Config('MSF21ADT', 'AMPSTC21ADT', 'CIM_2_NSTMMC21_AMPSTCADT') c.set_derived_val('NSTMMC21_MSFADT_VALID_2_MAP', 'NSTMMC21_MSFADT_MAP_2_CIM', 'NSTMMC21') data = vars(c) result = len(data) self.assertEqual(result, 6) self.assertDictEqual(data, self.cfgdict)
def _init(): Config.load() Bot.session = vk_api.VkApi(token=Config.token) Bot.api = Bot.session.get_api() Bot.longpoll = LongPoll(Bot.session, Config.group_id) if Bot.api.groups.getOnlineStatus( group_id=Config.group_id)['status'] == 'none': Bot.api.groups.enableOnline(group_id=Config.group_id) db.load() db.set_yusup_id(Bot.api) schedule.every().day.at("10:30").do(run_threaded, job)
def test_flows(self): """ Test Flows object """ print("Start test of Flows class...") c = Config('MSF21ADT', 'AMPSTC21ADT', 'CIM_2_NSTMMC21_AMPSTCADT') c.set_derived_val('NSTMMC21_MSFADT_VALID_2_MAP', 'NSTMMC21_MSFADT_MAP_2_CIM', 'NSTMMC21') flow = Flows(c.dstFlowName, FlowType.VF, vars(c), patternType=PatternType.AMP) data = vars(flow) #result = len(data) #self.assertEqual(result, 6) self.assertDictEqual(data, self.flowdict)
def run(plugin_list: bool, plugins: str): """ Version 3.0 work in progress """ config = Config() if plugin_list: pluginManager = PluginManager() pluginManager.print_plugins_list() exit(0) if plugins is not None: plugins = PluginManager(plugins) print("Loaded : {0} plugins".format(plugins.plugin_loaded())) # todo load data dataDriver file.json or mongo # check if app running in docker environment and run server or client code if config.docker_mode: if os.environ.get("IS_SERVER"): # run server mode server = Server() else: # run client mode client = Client() exit(0) print("No arg detected :/") print("Please run 'python3 Toudoum.py run --help'")
def main(): config = Config() print(config.fsqlite, config.bearer) #sys.exit(1) HttpParser(config)
def main(_): assert len(sys.argv) == 2 or len( sys.argv) == 3, "usage: main.py <config> <optional_config_string>" config_path = sys.argv[1] assert os.path.exists(config_path), config_path try: if len(sys.argv) == 3: config = Config(config_path, sys.argv[2]) else: config = Config(config_path) except ValueError as e: print("Malformed config file:", e) return -1 init_log(config) # dump the config into the log print(open(config_path).read(), file=log.v4) engine = Engine(config) engine.run()
def __init__(self): self.client = pymongo.MongoClient(Config().get()['MongoDB']['URL']) if "ferox" not in self.client.list_database_names(): raise Exception("database ferox not found") self.ferox = self.client["ferox"] if "chats" not in self.ferox.list_collection_names(): raise Exception("database ferox not found") self.chats = self.ferox["chats"]
def __init__(self): filename = Config().get()['Logger']['Path'] if (filename == "None"): filename = None logging.basicConfig( level=logging.CRITICAL, filename=filename, format='[%(asctime)s]: %(levelname)s - %(message)s') self.logger = logging.getLogger() self.logger.setLevel(logging.INFO)
def main(_): assert len(sys.argv) == 2, "usage: main.py <config>" config_path = sys.argv[1] assert os.path.exists(config_path), config_path try: config = Config(config_path) except ValueError as e: print("Malformed config file:", e) return -1 init_log(config) # dump the config into the log print(open(config_path).read(), file=log.v4) engine = EvalPascalRecursive(config) engine.run()
class Harvester: # API Endpoints _BASE_URL_PATH = 'https://na1.api.riotgames.com/lol' _CHALLENGER_PATH = _BASE_URL_PATH + '/league/v3/challengerleagues/by-queue/' _MATCH_PATH = _BASE_URL_PATH + '/match/v3/' _SUMMONER_PATH = _BASE_URL_PATH + '/summoner/v3/summoners/' # Total matches to fetch TOTAL_MATCHES = 1000 def __init__(self): # Load config for defaults & key self.config_manager = Config().get_instance() self.api_key = self.config_manager.get_api_key() self.logger = Logger() def make_request(self, path, payload=None): """ Make request to Riot API Developer endpoint with optional data :param path: endpoint to query :param payload: optional parameters to send with the request :return: """ try: if payload is None: payload = {'api_key': self.api_key} else: payload['api_key'] = self.api_key response = requests.get(path, params=payload) self.logger.info(path + str(response)) response.raise_for_status() return response.json() except requests.exceptions.RequestException: return None def get_challenger_path(self): return self._CHALLENGER_PATH def get_match_path(self): return self._MATCH_PATH def get_summoner_path(self): return self._SUMMONER_PATH def get_total_matches(self): return self.TOTAL_MATCHES
def __init__(self): self.updater = Updater(token=Config().get()["Telegram"]["Token"], use_context=True) self.dispatcher = dispatcher = self.updater.dispatcher dispatcher.add_handler(CommandHandler('subscribe', self.subscribe)) dispatcher.add_handler(CommandHandler('unsubscribe', self.unsubscribe)) dispatcher.add_handler(CommandHandler('start', self.start)) dispatcher.add_handler(CommandHandler('stop', self.stop)) dispatcher.add_handler(CommandHandler('status', self.status)) dispatcher.add_handler(CommandHandler('latest', self.latest)) dispatcher.add_handler(CommandHandler('sun', self.sun)) dispatcher.add_handler(CommandHandler('day', self.day)) dispatcher.add_handler(CommandHandler('cache', self.cache)) dispatcher.add_handler(CommandHandler('help', self.help)) dispatcher.add_handler(CommandHandler('update', self.update))
def setUp(self): self.config = Config('config.json')
from core.Config import Config from core.Flows import FlowType, PatternType, Flows c = Config('MSF21ADT', 'AMPSTC21ADT', 'CIM_2_NSTMMC21_AMPSTCADT') c.set_derived_val('NSTMMC21_MSFADT_VALID_2_MAP', 'NSTMMC21_MSFADT_MAP_2_CIM', 'NSTMMC21') #c.display() print(" - Config Vars - ") print(vars(c)) flow = Flows(c.dstFlowName, FlowType.VF, vars(c), patternType=PatternType.AMP) print(" - Flow Vars - ") print(vars(flow))
import threading import time from threading import Thread from time import sleep from binance.client import Client from binance.enums import * from binance.websockets import BinanceSocketManager from core.Config import Config from core.data.DailyTickerData import DailyTickerData from core.data.TradeData import TradeData from core.ForceCloseableThread import ForceCloseableThread from plotting.RealtimePlot import RealtimePlot config = Config() client = Client(config["exchanges"]["binance"]["api_key"], config["exchanges"]["binance"]["api_secret"]) bm = BinanceSocketManager(client) plot = RealtimePlot('Binance: BTC-USDT') threads = [] def todo_make_this_call_a_strategy(event): print( "Thread starting for event: {}, length of previous trades: {}".format( event[0], len(event[1]))) while True:
async def setUp(self): self.config = Config("../config.json", False) self.ticket = await Api.get_ticket(self.config.account, self.config.password)
def __init__(self): self.config = Config.get_instance() logging.basicConfig(filename=self.config.get_default_log_path(), level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
#!/usr/bin/env python3 import os from core.OpCodeHandler import OpCodeHandler as Client from core.Config import Config as Config from core.Plugin_Loader import Plugin_Loader from webserver.Webserver import Webserver PROJECT_ROOT = os.path.dirname(__file__) + '/' config = Config(PROJECT_ROOT + '/config.json') client = Client(config, PROJECT_ROOT + '/data/') client.set_plugin_loader(Plugin_Loader(PROJECT_ROOT + '/plugins/')) client.load_plugins() #client._set_save_path(PROJECT_ROOT+'/data/') #client.add_config(config)! # start webserver in thread Webserver(client) # forever! client.start()
#!/usr/bin/python3 import os import aiohttp, asyncio import requests import aiohttp import json from core.Config import Config as Config from core.HTTPClient import HTTPClient import binascii PROJECT_ROOT = os.path.dirname(__file__)+'/' cfg = Config(PROJECT_ROOT+'/config.json', False) server = "{}://{}:{}".format(cfg.webserver['protocol'], cfg.webserver['host'], cfg.webserver['port']) # don't do thix, use new http module! async def send_get_request(endpoint): headers = {"secret": str(cfg.webserver["secret"]), "content_type": "application/json"} resp = await HTTPClient.get(endpoint, headers) print (str(resp)) async def send_post_request(endpoint, data={}, headers = {'secret': cfg.webserver['secret']}): response = requests.post(endpoint, data=data, headers=headers) resp = response.content.decode('utf-8') print (str(resp))
def __init__(self): self.bot = telegram.Bot(Config().get()["Telegram"]["Token"])
from core.Args import Args from core.BackupFiles import BackupFiles from core.Config import Config if __name__ == '__main__': #Get the command lines arguments by initializing its class args = Args() config_file = args.get_config_file_arg() backup_path = args.get_backupdest_arg() file_name_add = args.get_add_file_arg() file_desc = args.get_file_desc_arg() file_name_rm = args.get_remove_file_arg() config_file_name = args.get_list_config_arg() #verify which argument has passed on cli to call the related method #a file is been added to config_file? if file_name_add: Config(config_file).add_config(file_name_add, file_desc) #a file is been removed from config_file? elif file_name_rm: Config(config_file).remove_config(file_name_rm) #user is listing files in config_file? elif config_file_name: Config(config_file).list_config(config_file_name) else: #backup files bkp = BackupFiles(config_file) #execute main program functionality - Make a backup bkp.execute_backup(backup_path)
def __init__(self, handler): self.folder = Config().get()["MotionDetector"]["Folder"] self.extension = Config().get()["MotionDetector"]["Extension"] self.handler = handler self.cam = Camera()
def __init__(self): # Load config for defaults & key self.config_manager = Config().get_instance() self.api_key = self.config_manager.get_api_key() self.logger = Logger()
# todo load data dataDriver file.json or mongo # check if app running in docker environment and run server or client code if config.docker_mode: if os.environ.get("IS_SERVER"): # run server mode server = Server() else: # run client mode client = Client() exit(0) print("No arg detected :/") print("Please run 'python3 Toudoum.py run --help'") if __name__ == '__main__': click.clear() console.banner() load_dotenv(".env") if os.environ.get("APP_VERSION") is None: print("Error no environments file found :/") exit(1) if os.getuid() == 0: # todo patch here for check windows admin config = Config() config.load() cli() else: console.error("You need to be run this script with root privileges") exit(1)