Beispiel #1
0
    def loadEngine(self, newEngine):
        """ Loads a new engine into the bot.
        """

        # check for confilcts:
        for conflict in newEngine.conflicts:
            if conflict in self.engines.keys():
                raise ValueError("%s conflicts with %s." % (newEngine.name, self.engines[conflict].name))

        for depend in newEngine.depends:
            if depend not in self.enginesSupplied.keys():
                raise ValueError("%s depends on %s, but has not been supplied." % (newEngine.name, depend))

        # check configuration
        if newEngine.confName is not None:
            conf = getConfiguration(newEngine.confName)
            if int(conf["versioning"]["version"]) < newEngine.requiredConfVersion:
                raise RuntimeError("Configuration for '%s' is too far out of date." % newEngine.name)

        else:
            conf = None
        engine = newEngine(self, conf)
        self.engines[engine.name] = engine

        for supply in engine.supplies:
            self.enginesSupplied[supply] = engine
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    dashstats_auth = firebase.FirebaseAuthentication(appconfig['firebase']['token'], appconfig['firebase']['email'])
    dashstats = firebase.FirebaseApplication(appconfig['firebase']['url'], dashstats_auth)
    #database clean up
    #we only need 1440 records to fill a 24h chart with 100 points/ chart resolution 14,4 minutes
    #will leave 1500 records and delete the rest. this increases board start
    records = dashstats.get("stats", None, {'shallow': 'true'})
    print records
    print "total records: %s" % len(records)
    nrecs = len(records) - 1500
    print "records to delete: %s" % nrecs
    if nrecs > 0:
        recs_to_delete = dashstats.get("stats", None, {'orderBy': '"timestamp"', 'limitToFirst': nrecs})
        for rec in recs_to_delete:
            print "deleting record %s:%s" % (rec, recs_to_delete[rec]['timestamp'])
            dashstats.delete("stats", rec)
Beispiel #3
0
    def loadEngine(self, newEngine):
        """ Loads a new engine into the bot.
        """

        # check for confilcts:
        for conflict in newEngine.conflicts:
            if conflict in self.engines.keys():
                raise ValueError("%s conflicts with %s." %
                                 (newEngine.name, self.engines[conflict].name))

        for depend in newEngine.depends:
            if depend not in self.enginesSupplied.keys():
                raise ValueError(
                    "%s depends on %s, but has not been supplied." %
                    (newEngine.name, depend))

        # check configuration
        if newEngine.confName is not None:
            conf = getConfiguration(newEngine.confName)
            if int(conf["versioning"]
                   ["version"]) < newEngine.requiredConfVersion:
                raise RuntimeError(
                    "Configuration for '%s' is too far out of date." %
                    newEngine.name)

        else:
            conf = None
        engine = newEngine(self, conf)
        self.engines[engine.name] = engine

        for supply in engine.supplies:
            self.enginesSupplied[supply] = engine
Beispiel #4
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    dashstats_auth = firebase.FirebaseAuthentication(
        appconfig['firebase']['token'], appconfig['firebase']['email'])
    dashstats = firebase.FirebaseApplication(appconfig['firebase']['url'],
                                             dashstats_auth)
    #database clean up
    #we only need 1440 records to fill a 24h chart with 100 points/ chart resolution 14,4 minutes
    #will leave 1500 records and delete the rest. this increases board start
    records = dashstats.get("stats", None, {'shallow': 'true'})
    print records
    print "total records: %s" % len(records)
    nrecs = len(records) - 1500
    print "records to delete: %s" % nrecs
    if nrecs > 0:
        recs_to_delete = dashstats.get("stats", None, {
            'orderBy': '"timestamp"',
            'limitToFirst': nrecs
        })
        for rec in recs_to_delete:
            print "deleting record %s:%s" % (rec,
                                             recs_to_delete[rec]['timestamp'])
            dashstats.delete("stats", rec)
Beispiel #5
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    auth = firebase.FirebaseAuthentication(appconfig['firebase']['token'], appconfig['firebase']['email'])
    dashproposals = firebase.FirebaseApplication(appconfig['firebase']['url'], auth)

    default_cmd = ["dash-cli", "-datadir=%s" % DATA_PATH, "-conf=%s" % CONF_PATH]

    #run dash-cli getmininginfo
    #dashd should already been started
    cmd = default_cmd + ["getmininginfo"]
    getmininginfo = subprocess.check_output(cmd)
    getmininginfo = json.loads(getmininginfo)
    print getmininginfo

    #run dash-cli masternode count
    cmd = default_cmd + ["masternode", "count"]
    masternodecount = subprocess.check_output(cmd)
    print "masternodecount: %s" % masternodecount
    dashproposals.put("", "masternodes", masternodecount)

    #proposals
    cmd = default_cmd + ["mnbudget", "show"]
    proposals = subprocess.check_output(cmd)
    proposals = json.loads(proposals)

    print "Proposals"
    urls_prefix = ["", "https://", "http://"]
    for i in proposals:
        for u in urls_prefix:
            try:
                requests.get("%s%s" % (u, proposals[i]["URL"]), verify=False)
                proposals[i]["fixed_URL"] = "%s%s" % (u, proposals[i]["URL"])
                break
            except:
                pass
        print proposals[i]
        proposals[i]["timestamp"] = {".sv": "timestamp"}

    dashproposals.put("", "proposals", proposals)
def get_authorization_url(email_address, state):
    """Retrieve the authorization URL.

    Args:
      email_address: User's e-mail address.
      state: State for the authorization URL.
    Returns:
      Authorization URL to redirect the user to.
    """
    conf = config.getConfiguration()
    assert conf
    flow = flow_from_clientsecrets(conf.sys.client_credential, ' '.join(SCOPES),
                                   redirect_uri=conf.sys.oauth_redirect_uri)
    flow.params['access_type'] = 'offline'
    flow.params['approval_prompt'] = 'force'
    flow.params['user_id'] = email_address
    flow.params['state'] = state
    return flow.step1_get_authorize_url()
Beispiel #7
0
    def __sendNotifications(self, mail, tel, count):
        url, api_code, api_result = None, None, None
        conf = config.getConfiguration()
        assert conf is not None
        for method in conf.methods:
            try:
                template = {
                    'msg': 'Your account %s have %d unread messages.' % (maskedAccount(mail), count),
                    'to': tel
                }
                url, data = method.api, {}

                # apply variables( {msg} {to} ) to http parameters.
                if method.data:
                    for (k, v) in method.data.items():
                        k = k.format(**template) if '{' in k else k
                        v = v.format(**template) if '{' in v else v
                        data[k] = v
                    data = urllib.urlencode(data)
                    if method.method == 'GET':  # else POST : retain data.
                        # todo parse url, append to query_part
                        url = '%s?%s' % (url, data)  # GET : append parameters to url and remove data.
                        data = None

                # apply basic auth
                if method.basic_auth:
                    urllib2.install_opener(urllib2.build_opener(method.basic_auth))

                # headers=None is not allowed.
                headers = method.headers if method.headers else {}

                req = urllib2.Request(url, data=data, headers=headers)
                log.info('Call %s_api HTTP/%s ==> %s' % (method.name, method.method, url))
                if data:
                    log.debug('Post-data = %s', json.dumps(data))
                if headers:
                    log.debug('Header = %s', json.dumps(headers))
                # if 1 == 1: return
                httpCall = urllib2.urlopen(req, timeout=5)
                api_code = httpCall.getcode()
                api_result = httpCall.read()
                log.info('Responded %s_api ==> [Code=%d] %s' % (method.name, api_code, api_result))
            except:
                log.exception('Error call %s_api [Code=%d] %s' % (method.name, api_code, api_result))
def get_authorization_url(email_address, state):
    """Retrieve the authorization URL.

    Args:
      email_address: User's e-mail address.
      state: State for the authorization URL.
    Returns:
      Authorization URL to redirect the user to.
    """
    conf = config.getConfiguration()
    assert conf
    flow = flow_from_clientsecrets(conf.sys.client_credential,
                                   ' '.join(SCOPES),
                                   redirect_uri=conf.sys.oauth_redirect_uri)
    flow.params['access_type'] = 'offline'
    flow.params['approval_prompt'] = 'force'
    flow.params['user_id'] = email_address
    flow.params['state'] = state
    return flow.step1_get_authorize_url()
def exchange_code(authorization_code):
    """Exchange an authorization code for OAuth 2.0 credentials.

    Args:
      authorization_code: Authorization code to exchange for OAuth 2.0
                          credentials.
    Returns:
      oauth2client.client.OAuth2Credentials instance.
    Raises:
      CodeExchangeException: an error occurred.
    """
    conf = config.getConfiguration()
    assert conf
    flow = flow_from_clientsecrets(conf.sys.client_credential, ' '.join(SCOPES))
    flow.redirect_uri = conf.sys.oauth_redirect_uri
    try:
        credentials = flow.step2_exchange(authorization_code)
        return credentials
    except FlowExchangeError, error:
        logging.error('An error occurred: %s', error)
        raise CodeExchangeException(None)
Beispiel #10
0
def exchange_code(authorization_code):
    """Exchange an authorization code for OAuth 2.0 credentials.

    Args:
      authorization_code: Authorization code to exchange for OAuth 2.0
                          credentials.
    Returns:
      oauth2client.client.OAuth2Credentials instance.
    Raises:
      CodeExchangeException: an error occurred.
    """
    conf = config.getConfiguration()
    assert conf
    flow = flow_from_clientsecrets(conf.sys.client_credential,
                                   ' '.join(SCOPES))
    flow.redirect_uri = conf.sys.oauth_redirect_uri
    try:
        credentials = flow.step2_exchange(authorization_code)
        return credentials
    except FlowExchangeError, error:
        logging.error('An error occurred: %s', error)
        raise CodeExchangeException(None)
Beispiel #11
0
 def test_configuration(self):
     self.api = pybrawl.PlayersApi(
         pybrawl.ApiClient(config.getConfiguration()))
Beispiel #12
0
 def setUp(self):
     # create an instance of the API class
     self.api = pyroyale.PlayersApi(
         pyroyale.ApiClient(config.getConfiguration()))
     pass
Beispiel #13
0
import unittest

import config

import pyroyale
from pyroyale.rest import ApiException

configuration = config.getConfiguration()


class TestPlayersApi(unittest.TestCase):
    def setUp(self):
        # create an instance of the API class
        self.api = pyroyale.PlayersApi(
            pyroyale.ApiClient(config.getConfiguration()))
        pass

    def tearDown(self):
        pass

    def test_player_AaronTraas(self):
        try:
            player = self.api.get_player('#9ULGLRCL')
            assert player.tag == '#9ULGLRCL'
            assert player.name == 'AaronTraas'
            assert player.exp_level >= 13
            assert player.trophies >= 4000
            assert player.best_trophies >= 4000
            assert player.wins >= 7000
            assert player.losses >= 7000
            assert player.battle_count >= 20000
Beispiel #14
0
 def setUp(self):
     # create an instance of the API class
     self.api = pybrawl.ClubsApi(pybrawl.ApiClient(config.getConfiguration()))
     pass
Beispiel #15
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    a = firebase.FirebaseAuthentication(appconfig['firebase']['token'], appconfig['firebase']['email'])
    f = firebase.FirebaseApplication(appconfig['firebase']['url'], a)

    #run dash-cli getmininginfo
    #dashd should already been started
    getmininginfo = subprocess.check_output(["dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf", "getmininginfo"])
    getmininginfo = json.loads(getmininginfo)
    print getmininginfo

    #run dash-cli masternode count
    masternodecount = subprocess.check_output(["dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf" , "masternode", "count"])
    print "masternodecount: %s" % masternodecount

    #update firebase values
    f.put("", "masternodecount", masternodecount)
    f.put("", "lastblock", getmininginfo["blocks"])
    f.put("", "difficulty", round(getmininginfo["difficulty"], 2))
    hashrate = round(float(getmininginfo["networkhashps"])/1000000000, 2)
    f.put("", "hashrate", hashrate)

    #run dash-cli spork show
    spork = subprocess.check_output(["dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf","spork", "show"])
    spork = json.loads(spork)
    payment_enforcement = "On"
    unix_time_now = datetime.datetime.utcnow()
    unix_time_now = unix_time_now.strftime("%s")
    print "unix_time_now: %s" % unix_time_now
    print "SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT: %s" % spork["SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT"]

    #check if masternode payments enforcement is enabled
    if int(spork["SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT"]) > int(unix_time_now):
        payment_enforcement = "Off"

    #update firebase values
    f.put("", "enforcement", payment_enforcement)

    #get average DASH-BTC from cryptsy, bittrex and bitfinex
    DashBtc = {
        'cryptsy': {'url': 'http://pubapi2.cryptsy.com/api.php?method=singlemarketdata&marketid=155', 'fn_price': get_price, 'exchange': 'cryptsy', 'market': 'DRK'},
        'bittrex':  {'url': 'https://bittrex.com/api/v1.1/public/getticker?market=btc-dash', 'fn_price': get_price, 'exchange': 'bittrex', 'market': 'DRK'},
        'bitfinex': {'url':  'https://api.bitfinex.com/v1/pubticker/DRKBTC', 'fn_price': get_price, 'exchange': 'bitfinex', 'market': 'DRK'}
        }

    avg_price_dashbtc = []
    for key, value in DashBtc.iteritems():
        try:
            r = requests.get(value['url'])
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'], value['market'])
                if price is not None:
                    avg_price_dashbtc.append(price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'], value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'], value['market'])
    print "avg_price_dashbtc: %s" % avg_price_dashbtc
    if len(avg_price_dashbtc) > 0:
        DASHBTC = reduce(lambda x, y: x+y, avg_price_dashbtc)/len(avg_price_dashbtc)
        print avg_price_dashbtc
        print "AVG DASHBTC: %s" % round(DASHBTC, 5)
        f.put("", "priceBTC", round(DASHBTC, 5))

    #get average BTC-USD from btce, bitstamp, bitfinex
    BtcUsd = {
        'btce': {'url': 'https://btc-e.com/api/3/ticker/btc_usd', 'fn_price': get_price, 'exchange': 'btce', 'market': 'btc_usd'},
        'bitstamp': {'url': 'https://www.bitstamp.net/api/ticker/', 'fn_price': get_price, 'exchange': 'bitstamp', 'market': 'BTCUSD'},
        'bitfinex': {'url': 'https://api.bitfinex.com/v1/pubticker/BTCUSD', 'fn_price': get_price, 'exchange': 'bitfinex', 'market': 'BTCUSD'},
        'okcoin': {'url': 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd', 'fn_price': get_price, 'exchange': 'okcoin', 'market': 'BTCUSD'},
    }
    avg_price_btcusd = []
    for key, value in BtcUsd.iteritems():
        try:
            r = requests.get(value['url'])
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'], value['market'])
                if price is not None:
                    avg_price_btcusd.append(price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'], value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'], value['market'])
    if len(avg_price_btcusd) > 0:
        BTCUSD = reduce(lambda x, y: x+y, avg_price_btcusd)/len(avg_price_btcusd)
        print avg_price_btcusd
        print "AVG BTCUSD: %s" % round(BTCUSD, 8)
        f.put("", "priceBTCUSD", "$%s" % round(BTCUSD, 2))
        DASHUSD = "$%s" % round(float(BTCUSD * DASHBTC), 2)
        print "DASHUSD: %s" % DASHUSD
        f.put("", "price", DASHUSD)

    #get total coins supply from Chainz
    try:
        r = requests.get("http://chainz.cryptoid.info/dash/api.dws?q=totalcoins")
        int_total_coins = r.text.split(".")[0]
        try:
            #validate request
            int(int_total_coins)
            inv_total_coins = int_total_coins[::-1]
            availablesupply = ",".join(chunks(inv_total_coins, 3))[::-1]
            print "Available supply: %s" % availablesupply
            f.put("", "availablesupply", availablesupply)
        except ValueError:
            #reply is not an integer
            print "chainz reply is not valid"
    except requests.exceptions.RequestException as e:
        print e

    #timestamp is given by firebase server
    f.put("", "timestamp", {".sv": "timestamp"})
Beispiel #16
0
    def __init__(self):
        #logging.basicConfig(filename='/home/linaro/www/log', format='%(asctime)s %(message)s', level=logging.DEBUG)
        self.config = config.getConfiguration(CONFIG_FILE_PATH)
        required_keys = ['city', 'LOG_FILE', 'DATABASE_PATH']
        for key in required_keys:
            if key not in self.config:
                message = "*** ERROR: key \'%s\' is required" % key
                raise Exception(message)
        self.logger = logging.getLogger('server')
        self.logger.setLevel(logging.DEBUG)
        fh = logging.handlers.RotatingFileHandler(self.config['LOG_FILE'])
        fh.setLevel(logging.DEBUG)
        fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(fmt)
        self.logger.addHandler(fh)
        self.logger.info("starting service")
        self.logger.info("DEBUG: %s" % DEBUG)
        self.logger.debug("connecting to database")
        self.clients = []
        self.db = Database(self.config['DATABASE_PATH'])

        _astral = astral.Astral()
        _astral.solar_depression = 'civil'
        self.city = _astral[self.config['city']]

        #pubnub
        self.queue = Queue.Queue()
        if 'pubnub' in self.config:
            if 'PUBNUB_PUBLISH_KEY' in self.config['pubnub'] and 'PUBNUB_SUBSCRIBE_KEY' in self.config['pubnub']:
                self.pubnub = RemotePubNub(self.config['pubnub']['PUBNUB_PUBLISH_KEY'], self.config['pubnub']['PUBNUB_SUBSCRIBE_KEY'], self.queue)
                self.pubnub.subscribe('control')
            else:
                del self.config['pubnub']

        #get outputs initial status
        init_outputs = []
        db_outputs = self.db.all('outputs')
        for output in db_outputs:
            init_outputs.append({'name': output['name'], 'value': output['value']})
        self.logger.debug("initializing outputs")

        self.outputs = Outputs(init_outputs)
        self.logger.info("starting server")
        options.parse_command_line()
        handlers = [
            (r"/", HomeHandler),
            (r"/login", AuthLoginHandler),
            (r"/logout", AuthLogoutHandler),
            (r"/scheduleritems", SchedulerItems),
            (r"/deletescheduleritems", DeleteSchedulerItems),
            #(r'/', IndexHandler),
            (r'/ws', SocketHandler),
            (r'/api', ApiHandler),
            #(r"/(.*)", web.StaticFileHandler,{"path": "/www/tornado"})
            (r"/(.*)", web.StaticFileHandler, {"path": "/root/www/static"})
        ]
        settings = {
            "template_path": "/home/linaro/www/static/",
            "static_path": "/home/linaro/www/static/",
            "cookie_secret": "user",
            "login_url": "/login",
            "debug": DEBUG
        }
        self.logger.info("Application init")
        self.periodic_call = ioloop.PeriodicCallback(self.check_outputs, 1000)
        self.logger.info("periodic call")
        self.periodic_call.start()
        self.logger.info("periodic call - start")
        return web.Application.__init__(self, handlers, **settings)
Beispiel #17
0
commands = ["buildconf", "list", "bootstrap", "fetch", "update", "install",
            "rebuild", "clean", "diff", "envsh", "uninstall", "help", "info",
            "show-log"]

cfg = {}
for a in sys.argv:
    if "path=" in a:
        p = a[5:]
        if "'" in p:
            p = p.split("'")[1]
        elif '"' in p:
            p = p.split('"')[1]
        cfg["buildconfAddress"] = p

config.getConfiguration(cfg)
cfg["installed"] = []
cfg["updated"] = []
cfg["update"] = True
cfg["fetch"] = True
cfg["errors"] = []
cfg["continueOnError"] = True
cfg["overrides"] = {}
cfg["rebuild"] = False
cfg["profiling"] = []
cfg["checkDeps"] = True
cfg["deps"] = {}
cfg["multiprocessing"] = True
cfg["depsInverse"] = {}

overrides.loadOverrides(cfg)
Beispiel #18
0
#!/usr/bin/env python3
from bot import Bot
from engines import censorship, commands
from config import getConfiguration

newbot = Bot(getConfiguration("bot"))

# newbot.loadEngine(censorship.CensorshipEngine)
newbot.loadEngine(commands.PermissionEngine)
newbot.loadEngine(commands.CommandsEngine)

cmds = []

from commands.basic import Say, Help, Die, cnJoke, Ping

cmds.extend((Say, Help, Die, cnJoke, Ping))

from commands.fun import asciiClock, cowsay, slap, Dice

cmds.extend((asciiClock, cowsay, slap, Dice))

from commands.taiiwoport import cleverbot, findIP, FindPhone, Love, Moustache, WolframAlphaPlain, WolframAlphaImage, Joke, WYR, Fact

cmds.extend((cleverbot, findIP, FindPhone, Love, Moustache, WolframAlphaPlain,
             WolframAlphaImage, Joke, WYR, Fact))

from commands.utils import Permission, DeleteLastMessage

cmds.extend((Permission, DeleteLastMessage))

for cmd in cmds:
Beispiel #19
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    dashstats_auth = firebase.FirebaseAuthentication(appconfig['firebase']['token'], appconfig['firebase']['email'])
    dashstats = firebase.FirebaseApplication(appconfig['firebase']['url'], dashstats_auth)

    # run dash-cli getmininginfo
    # dashd should already been started
    getmininginfo = subprocess.check_output(["dash-cli", "-datadir=%s" % DATA_PATH, "-conf=%s" % CONF_PATH, "getmininginfo"])
    getmininginfo = json.loads(getmininginfo)
    print getmininginfo

    # run dash-cli masternode count
    masternodecount = subprocess.check_output(["dash-cli", "-datadir=%s" % DATA_PATH, "-conf=%s" % CONF_PATH, "masternode", "count"])
    print "masternodecount: %s" % masternodecount

    # update firebase values
    hashrate = round(float(getmininginfo["networkhashps"])/1000000000, 2)

    # run dash-cli spork show
    spork = subprocess.check_output(["dash-cli", "-datadir=%s" % DATA_PATH, "-conf=%s" % CONF_PATH, "spork", "show"])
    spork = json.loads(spork)
    payment_enforcement = "On"
    unix_time_now = datetime.datetime.utcnow()
    unix_time_now = unix_time_now.strftime("%s")
    print "unix_time_now: %s" % unix_time_now
    print "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: %s" % spork["SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"]

    # check if masternode payments enforcement is enabled
    if int(spork["SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"]) > int(unix_time_now):
        payment_enforcement = "Off"

    # get average DASH-BTC from cryptsy, bittrex and bitfinex
    DashBtc = {
        # 'cryptsy': {'url': 'http://pubapi2.cryptsy.com/api.php?method=singlemarketdata&marketid=155', 'fn_price': get_price, 'exchange': 'cryptsy', 'market': 'DRK'},
        'bittrex':  {'url': 'https://bittrex.com/api/v1.1/public/getticker?market=btc-dash', 'fn_price': get_price, 'exchange': 'bittrex', 'market': 'DRK'},
        'poloniex': {'url': 'https://poloniex.com/public?command=returnTicker', 'fn_price': get_price, 'exchange': 'poloniex', 'market': 'BTC_DASH'},
        'bter': {'url': 'http://data.bter.com/api/1/ticker/dash_btc', 'fn_price': get_price, 'exchange': 'bter', 'market': 'BTC_DASH'},
        'livecoin': {'url': 'https://api.livecoin.net/exchange/ticker?currencyPair=DASH/BTC', 'fn_price': get_price, 'exchange': 'livecoin', 'market': 'BTC_DASH'},
        'btce': {'url': 'https://btc-e.com/api/2/dsh_btc/ticker', 'fn_price': get_price, 'exchange': 'btce', 'market': 'dsh_btc'},
        'exmo': {'url': 'https://api.exmo.com/v1/ticker/', 'fn_price': get_price, 'exchange': 'exmo', 'market': 'DASH_BTC'}
        }

    avg_price_dashbtc = []
    for key, value in DashBtc.iteritems():
        try:
            r = requests.get(value['url'], verify=False, timeout=5)
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'], value['market'])
                if price is not None:
                    avg_price_dashbtc.append(price)
                    print "Market:%s/%s ; Price: %s" % (value['exchange'], value['market'], price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'], value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'], value['market'])
    print "avg_price_dashbtc: %s" % avg_price_dashbtc
    if len(avg_price_dashbtc) > 0:
        DASHBTC = reduce(lambda x, y: x+y, avg_price_dashbtc)/len(avg_price_dashbtc)
        print avg_price_dashbtc
        print "AVG DASHBTC: %s" % round(DASHBTC, 5)

    # get average BTC-USD from btce, bitstamp, bitfinex
    BtcUsd = {
        'btce': {'url': 'https://btc-e.com/api/3/ticker/btc_usd', 'fn_price': get_price, 'exchange': 'btce', 'market': 'btc_usd'},
        'bitstamp': {'url': 'https://www.bitstamp.net/api/ticker/', 'fn_price': get_price, 'exchange': 'bitstamp', 'market': 'BTCUSD'},
        'bitfinex': {'url': 'https://api.bitfinex.com/v1/pubticker/BTCUSD', 'fn_price': get_price, 'exchange': 'bitfinex', 'market': 'BTCUSD'},
        'okcoin': {'url': 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd', 'fn_price': get_price, 'exchange': 'okcoin', 'market': 'BTCUSD'},
    }
    avg_price_btcusd = []
    for key, value in BtcUsd.iteritems():
        try:
            r = requests.get(value['url'], verify=False, timeout=5)
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'], value['market'])
                if price is not None:
                    avg_price_btcusd.append(price)
                    print "Market:%s/%s ; Price: %s" % (value['exchange'], value['market'], price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'], value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'], value['market'])
    if len(avg_price_btcusd) > 0:
        BTCUSD = reduce(lambda x, y: x+y, avg_price_btcusd)/len(avg_price_btcusd)
        print avg_price_btcusd
        print "AVG BTCUSD: %s" % round(BTCUSD, 8)
        #f.put("", "priceBTCUSD", "$%s" % round(BTCUSD, 2))
        DASHUSD = "$%s" % round(float(BTCUSD * DASHBTC), 2)
        print "DASHUSD: %s" % DASHUSD

    output = {"difficulty": round(getmininginfo["difficulty"], 2), "enforcement": payment_enforcement,
        "hashrate": hashrate, "lastblock": getmininginfo["blocks"], "masternodecount": masternodecount, "price": round(float(BTCUSD * DASHBTC), 2),
        "priceBTC": round(DASHBTC, 5), "priceBTCUSD": round(BTCUSD, 2), "timestamp": {".sv": "timestamp"}
        }

    # get total coins supply from Chainz
    try:
        r = requests.get("http://chainz.cryptoid.info/dash/api.dws?q=totalcoins")
        int_total_coins = r.text.split(".")[0]
        try:
            # validate request
            int(int_total_coins)
            inv_total_coins = int_total_coins[::-1]
            availablesupply = ",".join(chunks(inv_total_coins, 3))[::-1]
            print "Available supply: %s" % availablesupply
            output.update({"availablesupply": availablesupply})
            # f.put("", "availablesupply", availablesupply)
        except ValueError:
            # reply is not an integer
            print "\033[91m chainz reply is not valid \033[0m"
    except requests.exceptions.RequestException as e:
        print e

    # get next super block
    super_block = subprocess.check_output(["dash-cli", "-datadir=%s" % DATA_PATH, "-conf=%s" % CONF_PATH, "mnbudget", "nextblock"])
    superblock = json.loads(super_block)
    output['superblock'] = superblock

    # get budget and proposals info from dashwhale api
    try:
        r = requests.get("https://www.dashwhale.org/api/v1/budget")
        response = r.json()
        output['n_proposals'] = len(response['proposals'])
        output['budget_total_amount'] = response['budget']['total_amount']
        output['budget_alloted_amount'] = response['budget']['alloted_amount']
        output['budget_payment_date'] = response['budget']['payment_date']
        output['budget_payment_date_human'] = response['budget']['payment_date_human']
    except requests.exceptions.RequestException as e:
        print e

    # masternode daily payment
    masternode_calcs = masternodes(int(output["masternodecount"]))
    output["masternodeDailyPayment"] = masternode_calcs.dailyPayment()
    print "Masternodes daily payment: %s" % output["masternodeDailyPayment"]

    dashstats.post("stats", output)
    print "sync ended"
Beispiel #20
0
#!/usr/bin/env python3
from bot import Bot
from engines import censorship, commands
from config import getConfiguration


newbot = Bot(getConfiguration("bot"))

# newbot.loadEngine(censorship.CensorshipEngine)
newbot.loadEngine(commands.PermissionEngine)
newbot.loadEngine(commands.CommandsEngine)

cmds = []

from commands.basic import Say, Help, Die, cnJoke, Ping
cmds.extend((Say, Help, Die, cnJoke, Ping))

from commands.fun import asciiClock, cowsay, slap, Dice
cmds.extend((asciiClock, cowsay, slap, Dice))

from commands.taiiwoport import cleverbot, findIP, FindPhone, Love, Moustache, WolframAlphaPlain, WolframAlphaImage, Joke, WYR, Fact
cmds.extend((cleverbot, findIP, FindPhone, Love, Moustache, WolframAlphaPlain, WolframAlphaImage, Joke, WYR, Fact))

from commands.utils import Permission, DeleteLastMessage
cmds.extend((Permission, DeleteLastMessage))

for cmd in cmds:
    cmd(newbot.getEngine("commands"))

newbot.start(1/30)
Beispiel #21
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    a = firebase.FirebaseAuthentication(appconfig['firebase']['token'],
                                        appconfig['firebase']['email'])
    f = firebase.FirebaseApplication(appconfig['firebase']['url'], a)

    #run dash-cli getmininginfo
    #dashd should already been started
    getmininginfo = subprocess.check_output([
        "dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf",
        "getmininginfo"
    ])
    getmininginfo = json.loads(getmininginfo)
    print getmininginfo

    #run dash-cli masternode count
    masternodecount = subprocess.check_output([
        "dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf",
        "masternode", "count"
    ])
    print "masternodecount: %s" % masternodecount

    #update firebase values
    f.put("", "masternodecount", masternodecount)
    f.put("", "lastblock", getmininginfo["blocks"])
    f.put("", "difficulty", round(getmininginfo["difficulty"], 2))
    hashrate = round(float(getmininginfo["networkhashps"]) / 1000000000, 2)
    f.put("", "hashrate", hashrate)

    #run dash-cli spork show
    spork = subprocess.check_output([
        "dash-cli", "-datadir=/root/data", "-conf=/root/data/dash.conf",
        "spork", "show"
    ])
    spork = json.loads(spork)
    payment_enforcement = "On"
    unix_time_now = datetime.datetime.utcnow()
    unix_time_now = unix_time_now.strftime("%s")
    print "unix_time_now: %s" % unix_time_now
    print "SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT: %s" % spork[
        "SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT"]

    #check if masternode payments enforcement is enabled
    if int(spork["SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT"]) > int(
            unix_time_now):
        payment_enforcement = "Off"

    #update firebase values
    f.put("", "enforcement", payment_enforcement)

    #get average DASH-BTC from cryptsy, bittrex and bitfinex
    DashBtc = {
        'cryptsy': {
            'url':
            'http://pubapi2.cryptsy.com/api.php?method=singlemarketdata&marketid=155',
            'fn_price': get_price,
            'exchange': 'cryptsy',
            'market': 'DRK'
        },
        'bittrex': {
            'url':
            'https://bittrex.com/api/v1.1/public/getticker?market=btc-dash',
            'fn_price': get_price,
            'exchange': 'bittrex',
            'market': 'DRK'
        },
        'bitfinex': {
            'url': 'https://api.bitfinex.com/v1/pubticker/DRKBTC',
            'fn_price': get_price,
            'exchange': 'bitfinex',
            'market': 'DRK'
        }
    }

    avg_price_dashbtc = []
    for key, value in DashBtc.iteritems():
        try:
            r = requests.get(value['url'])
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'],
                                          value['market'])
                if price is not None:
                    avg_price_dashbtc.append(price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'],
                                                          value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'],
                                                      value['market'])
    print "avg_price_dashbtc: %s" % avg_price_dashbtc
    if len(avg_price_dashbtc) > 0:
        DASHBTC = reduce(lambda x, y: x + y,
                         avg_price_dashbtc) / len(avg_price_dashbtc)
        print avg_price_dashbtc
        print "AVG DASHBTC: %s" % round(DASHBTC, 5)
        f.put("", "priceBTC", round(DASHBTC, 5))

    #get average BTC-USD from btce, bitstamp, bitfinex
    BtcUsd = {
        'btce': {
            'url': 'https://btc-e.com/api/3/ticker/btc_usd',
            'fn_price': get_price,
            'exchange': 'btce',
            'market': 'btc_usd'
        },
        'bitstamp': {
            'url': 'https://www.bitstamp.net/api/ticker/',
            'fn_price': get_price,
            'exchange': 'bitstamp',
            'market': 'BTCUSD'
        },
        'bitfinex': {
            'url': 'https://api.bitfinex.com/v1/pubticker/BTCUSD',
            'fn_price': get_price,
            'exchange': 'bitfinex',
            'market': 'BTCUSD'
        },
        'okcoin': {
            'url': 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd',
            'fn_price': get_price,
            'exchange': 'okcoin',
            'market': 'BTCUSD'
        },
    }
    avg_price_btcusd = []
    for key, value in BtcUsd.iteritems():
        try:
            r = requests.get(value['url'])
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'],
                                          value['market'])
                if price is not None:
                    avg_price_btcusd.append(price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'],
                                                          value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'],
                                                      value['market'])
    if len(avg_price_btcusd) > 0:
        BTCUSD = reduce(lambda x, y: x + y,
                        avg_price_btcusd) / len(avg_price_btcusd)
        print avg_price_btcusd
        print "AVG BTCUSD: %s" % round(BTCUSD, 8)
        f.put("", "priceBTCUSD", "$%s" % round(BTCUSD, 2))
        DASHUSD = "$%s" % round(float(BTCUSD * DASHBTC), 2)
        print "DASHUSD: %s" % DASHUSD
        f.put("", "price", DASHUSD)

    #get total coins supply from Chainz
    try:
        r = requests.get(
            "http://chainz.cryptoid.info/dash/api.dws?q=totalcoins")
        int_total_coins = r.text.split(".")[0]
        try:
            #validate request
            int(int_total_coins)
            inv_total_coins = int_total_coins[::-1]
            availablesupply = ",".join(chunks(inv_total_coins, 3))[::-1]
            print "Available supply: %s" % availablesupply
            f.put("", "availablesupply", availablesupply)
        except ValueError:
            #reply is not an integer
            print "chainz reply is not valid"
    except requests.exceptions.RequestException as e:
        print e

    #timestamp is given by firebase server
    f.put("", "timestamp", {".sv": "timestamp"})
Beispiel #22
0
def main():
    appconfig = config.getConfiguration(CONFIG_FILE_PATH)
    if appconfig is None:
        message = "Error parsing config file"
        raise Exception(message)

    print appconfig
    required_config_keys = ['firebase']
    for key in required_config_keys:
        if key not in appconfig:
            message = "*** ERROR: key \'%s\' is required" % key
            raise Exception(message)

    dashstats_auth = firebase.FirebaseAuthentication(
        appconfig['firebase']['token'], appconfig['firebase']['email'])
    dashstats = firebase.FirebaseApplication(appconfig['firebase']['url'],
                                             dashstats_auth)

    # run dash-cli getmininginfo
    # dashd should already been started
    getmininginfo = subprocess.check_output([
        "dash-cli",
        "-datadir=%s" % DATA_PATH,
        "-conf=%s" % CONF_PATH, "getmininginfo"
    ])
    getmininginfo = json.loads(getmininginfo)
    print getmininginfo

    # run dash-cli masternode count
    masternodecount = subprocess.check_output([
        "dash-cli",
        "-datadir=%s" % DATA_PATH,
        "-conf=%s" % CONF_PATH, "masternode", "count"
    ])
    print "masternodecount: %s" % masternodecount

    # update firebase values
    hashrate = round(float(getmininginfo["networkhashps"]) / 1000000000, 2)

    # run dash-cli spork show
    spork = subprocess.check_output([
        "dash-cli",
        "-datadir=%s" % DATA_PATH,
        "-conf=%s" % CONF_PATH, "spork", "show"
    ])
    spork = json.loads(spork)
    payment_enforcement = "On"
    unix_time_now = datetime.datetime.utcnow()
    unix_time_now = unix_time_now.strftime("%s")
    print "unix_time_now: %s" % unix_time_now
    print "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: %s" % spork[
        "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"]

    # check if masternode payments enforcement is enabled
    if int(spork["SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"]) > int(
            unix_time_now):
        payment_enforcement = "Off"

    # get average DASH-BTC from cryptsy, bittrex and bitfinex
    DashBtc = {
        # 'cryptsy': {'url': 'http://pubapi2.cryptsy.com/api.php?method=singlemarketdata&marketid=155', 'fn_price': get_price, 'exchange': 'cryptsy', 'market': 'DRK'},
        'bittrex': {
            'url':
            'https://bittrex.com/api/v1.1/public/getticker?market=btc-dash',
            'fn_price': get_price,
            'exchange': 'bittrex',
            'market': 'DRK'
        },
        'poloniex': {
            'url': 'https://poloniex.com/public?command=returnTicker',
            'fn_price': get_price,
            'exchange': 'poloniex',
            'market': 'BTC_DASH'
        },
        'bter': {
            'url': 'http://data.bter.com/api/1/ticker/dash_btc',
            'fn_price': get_price,
            'exchange': 'bter',
            'market': 'BTC_DASH'
        },
        'livecoin': {
            'url':
            'https://api.livecoin.net/exchange/ticker?currencyPair=DASH/BTC',
            'fn_price': get_price,
            'exchange': 'livecoin',
            'market': 'BTC_DASH'
        },
        'btce': {
            'url': 'https://btc-e.com/api/2/dsh_btc/ticker',
            'fn_price': get_price,
            'exchange': 'btce',
            'market': 'dsh_btc'
        },
        'exmo': {
            'url': 'https://api.exmo.com/v1/ticker/',
            'fn_price': get_price,
            'exchange': 'exmo',
            'market': 'DASH_BTC'
        }
    }

    avg_price_dashbtc = []
    for key, value in DashBtc.iteritems():
        try:
            r = requests.get(value['url'], verify=False, timeout=5)
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'],
                                          value['market'])
                if price is not None:
                    avg_price_dashbtc.append(price)
                    print "Market:%s/%s ; Price: %s" % (value['exchange'],
                                                        value['market'], price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'],
                                                          value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'],
                                                      value['market'])
    print "avg_price_dashbtc: %s" % avg_price_dashbtc
    if len(avg_price_dashbtc) > 0:
        DASHBTC = reduce(lambda x, y: x + y,
                         avg_price_dashbtc) / len(avg_price_dashbtc)
        print avg_price_dashbtc
        print "AVG DASHBTC: %s" % round(DASHBTC, 5)

    # get average BTC-USD from btce, bitstamp, bitfinex
    BtcUsd = {
        'btce': {
            'url': 'https://btc-e.com/api/3/ticker/btc_usd',
            'fn_price': get_price,
            'exchange': 'btce',
            'market': 'btc_usd'
        },
        'bitstamp': {
            'url': 'https://www.bitstamp.net/api/ticker/',
            'fn_price': get_price,
            'exchange': 'bitstamp',
            'market': 'BTCUSD'
        },
        'bitfinex': {
            'url': 'https://api.bitfinex.com/v1/pubticker/BTCUSD',
            'fn_price': get_price,
            'exchange': 'bitfinex',
            'market': 'BTCUSD'
        },
        'okcoin': {
            'url': 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd',
            'fn_price': get_price,
            'exchange': 'okcoin',
            'market': 'BTCUSD'
        },
    }
    avg_price_btcusd = []
    for key, value in BtcUsd.iteritems():
        try:
            r = requests.get(value['url'], verify=False, timeout=5)
            try:
                output = json.loads(r.text)
                price = value['fn_price'](output, value['exchange'],
                                          value['market'])
                if price is not None:
                    avg_price_btcusd.append(price)
                    print "Market:%s/%s ; Price: %s" % (value['exchange'],
                                                        value['market'], price)
            except Exception as e:
                print e
                print "Could not get price from %s:%s" % (value['exchange'],
                                                          value['market'])
        except requests.exceptions.RequestException as e:
            print e
            print "Could not get price from %s:%s" % (value['exchange'],
                                                      value['market'])
    if len(avg_price_btcusd) > 0:
        BTCUSD = reduce(lambda x, y: x + y,
                        avg_price_btcusd) / len(avg_price_btcusd)
        print avg_price_btcusd
        print "AVG BTCUSD: %s" % round(BTCUSD, 8)
        #f.put("", "priceBTCUSD", "$%s" % round(BTCUSD, 2))
        DASHUSD = "$%s" % round(float(BTCUSD * DASHBTC), 2)
        print "DASHUSD: %s" % DASHUSD

    output = {
        "difficulty": round(getmininginfo["difficulty"], 2),
        "enforcement": payment_enforcement,
        "hashrate": hashrate,
        "lastblock": getmininginfo["blocks"],
        "masternodecount": masternodecount,
        "price": round(float(BTCUSD * DASHBTC), 2),
        "priceBTC": round(DASHBTC, 5),
        "priceBTCUSD": round(BTCUSD, 2),
        "timestamp": {
            ".sv": "timestamp"
        }
    }

    # get total coins supply from Chainz
    try:
        r = requests.get(
            "http://chainz.cryptoid.info/dash/api.dws?q=totalcoins")
        int_total_coins = r.text.split(".")[0]
        try:
            # validate request
            int(int_total_coins)
            inv_total_coins = int_total_coins[::-1]
            availablesupply = ",".join(chunks(inv_total_coins, 3))[::-1]
            print "Available supply: %s" % availablesupply
            output.update({"availablesupply": availablesupply})
            # f.put("", "availablesupply", availablesupply)
        except ValueError:
            # reply is not an integer
            print "\033[91m chainz reply is not valid \033[0m"
    except requests.exceptions.RequestException as e:
        print e

    # get next super block
    super_block = subprocess.check_output([
        "dash-cli",
        "-datadir=%s" % DATA_PATH,
        "-conf=%s" % CONF_PATH, "mnbudget", "nextblock"
    ])
    superblock = json.loads(super_block)
    output['superblock'] = superblock

    # get budget and proposals info from dashwhale api
    try:
        r = requests.get("https://www.dashwhale.org/api/v1/budget")
        response = r.json()
        output['n_proposals'] = len(response['proposals'])
        output['budget_total_amount'] = response['budget']['total_amount']
        output['budget_alloted_amount'] = response['budget']['alloted_amount']
        output['budget_payment_date'] = response['budget']['payment_date']
        output['budget_payment_date_human'] = response['budget'][
            'payment_date_human']
    except requests.exceptions.RequestException as e:
        print e

    # masternode daily payment
    masternode_calcs = masternodes(int(output["masternodecount"]))
    output["masternodeDailyPayment"] = masternode_calcs.dailyPayment()
    print "Masternodes daily payment: %s" % output["masternodeDailyPayment"]

    dashstats.post("stats", output)
    print "sync ended"