diff --git a/app.py b/app.py index b5920a7..76375e3 100644 --- a/app.py +++ b/app.py @@ -1,18 +1,18 @@ import requests from requests_oauthlib import OAuth1 from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException -import settings import json import threading import time # import traceback +from bot_config import BotConfig class XP_RPC(): def __init__(self): self.connection = AuthServiceProxy( - settings.RPC_URL % (settings.rpc_user, settings.rpc_password)) + BotConfig.RPC_URL % (BotConfig.RPC_USER, BotConfig.RPC_PASSWORD)) self.tax = 1.0 def get_address(self, name): @@ -65,10 +65,10 @@ class Twitter(): def __init__(self): self.xpd = XP_RPC() - self.auth_stream = OAuth1(settings.CONSUMER_KEY_STREAM, settings.CONSUMER_SECRET_STREAM, - settings.ACCESS_TOKEN_STREAM, settings.ACCESS_TOKEN_SECRET_STREAM) - self.auth_reply = OAuth1(settings.CONSUMER_KEY_REPLY, settings.CONSUMER_SECRET_REPLY, - settings.ACCESS_TOKEN_REPLY, settings.ACCESS_TOKEN_SECRET_REPLY) + self.auth_stream = OAuth1(BotConfig.CONSUMER_KEY_STREAM, BotConfig.CONSUMER_SECRET_STREAM, + BotConfig.ACCESS_TOKEN_STREAM, BotConfig.ACCESS_TOKEN_SECRET_STREAM) + self.auth_reply = OAuth1(BotConfig.CONSUMER_KEY_REPLY, BotConfig.CONSUMER_SECRET_REPLY, + BotConfig.ACCESS_TOKEN_REPLY, BotConfig.ACCESS_TOKEN_SECRET_REPLY) self.tweets = [] def reply(self, text, reply_token): diff --git a/bot_config.py b/bot_config.py new file mode 100644 index 0000000..d95a7d7 --- /dev/null +++ b/bot_config.py @@ -0,0 +1,55 @@ +""" +Configuration object that does not need to instantiate. + +Usage: +> from bot_config import BotConfig +> BotConfig.SOME_PROPERTY +""" +import os +from collections import ChainMap + +DEFAULTS = { + 'CONSUMER_KEY': None, + 'CONSUMER_SECRET': None, + 'ACCESS_TOKEN': None, + 'ACCESS_TOKEN_SECRET': None, + 'RPC_URL': None, + 'RPC_USER': None, + 'RPC_PASSWORD': None, +} + + +class Singleton(type): + """Make class to be a singleton""" + _instances = {} + + def __call__(self, *args, **kwargs): + """If instance exists, just return it.""" + if self not in self._instances: + self._instances[self] = super().__call__(*args, **kwargs) + return self._instances[self] + + +class BotConfigFactory(object, metaclass=Singleton): + """Factory provides BotConfig instance as a singleton.""" + + def __init__(self): + """Pick variables from environment variables, `setting.py`, DEFAULTS. + + Only the keys in `settings.py` are case insensitive.""" + environments = dict((key, val) for key, val in os.environ.items() if key in DEFAULTS) + from_settings = {} + try: + import settings + from_settings = dict((key.upper(), getattr(settings, key)) for key in dir(settings) + if key.upper() in DEFAULTS) + except ModuleNotFoundError: + print('settings.py not found. continue with using environment variables.') + + _configs = ChainMap(environments, from_settings, DEFAULTS) + + for key, val in _configs.items(): + setattr(self, key, val) + + +BotConfig = BotConfigFactory()