def sfd_process(sfd): FX_CHANNEL = "lightning_ticker_FX_BTC_JPY" BTC_CHANNEL = "lightning_ticker_BTC_JPY" class BitflyerSubscriberCallback(SubscribeCallback): def message(self, pubnub, message): tick = message.message timestamp = dateutil.parser.parse(tick["timestamp"]) with sfd.lock: changed = False if message.channel == FX_CHANNEL: if sfd.fx_ltp != tick["ltp"]: sfd.fx_ltp = tick["ltp"] changed = True elif message.channel == BTC_CHANNEL: if sfd.btc_ltp != tick["ltp"]: sfd.btc_ltp = tick["ltp"] changed = True if sfd.ready and changed: sfd.disparity = (sfd.fx_ltp / sfd.btc_ltp) * 100 - 100 if (sfd.fx_ltp > sfd.btc_ltp and sfd.disparity >= 10.0) or \ (sfd.fx_ltp < sfd.btc_ltp and sfd.disparity <= -10.0): sfd.last_sfd_at = timestamp sfd.updated_at = timestamp sfd.event.set() config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.LINEAR config.ssl = False config.set_presence_timeout(60) pubnub = PubNubTornado(config) listener = BitflyerSubscriberCallback() pubnub.add_listener(listener) pubnub.subscribe().channels([FX_CHANNEL, BTC_CHANNEL]).execute() pubnub.start()
def get_pubnub(): pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-a57ab586-2e94-11e9-8208-aaa77ad184aa' pnconfig.publish_key = 'pub-c-395634b8-6b43-407a-bd80-e656f030d997' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.uuid = 'mgmt_cloud_uuid' pubnub = PubNub(pnconfig) return pubnub
def __init__(self, fxevents, tick_interval): self.fxevents = fxevents self.tick_interval = tick_interval self.instruments = 'lightning_ticker_BTC_JPY' config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.LINEAR self.pubnub = PubNubTornado(config) self.run = True
def load_pubnub(self): config = PNConfiguration() config.subscribe_key = self.config.pubnub_sub_key config.publish_key = self.config.pubnub_pub_key config.reconnect_policy = PNReconnectionPolicy.LINEAR self.pubnub = PubNub(config) self.pubnub_listener = EventCallback(self) self.pubnub.add_listener(self.pubnub_listener) self.pubnub.subscribe().channels(self.config.pubnub_channel).execute()
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'pub-c-bc8de339-f4af-48fb-ad34-dce0abdc9531' pnconfig.publish_key = 'pub-c-bc8de339-f4af-48fb-ad34-dce0abdc9531' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-c6f57af0-4134-11e8-afae-2a65d00afee8' pnconfig.publish_key = 'pub-c-0cc9b82a-4cd0-4a90-9ab3-7705e5a07575' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print ('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = cfg.api['subscribe_key'] pnconfig.publish_key = cfg.api['publish_key'] pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print ('pubnub subscription completed')
def init_chatroom(nickname): pnconfig = PNConfiguration() pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.publish_key = pubkey pnconfig.subscribe_key = subkey pnconfig.uuid = nickname pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('mychatroom').with_presence().execute() return pubnub
def _pubnub_config(self): channel_config = self.client.channels.list() channels = [channel['name'] for channel in channel_config['channels']] pnconfig = PNConfiguration() pnconfig.subscribe_key = channel_config['subscribe_key'] pnconfig.cipher_key = channel_config['cipher_key'] pnconfig.auth_key = channel_config['auth_key'] pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR return pnconfig, channels
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'SUBSCRIBE_KEY' pnconfig.publish_key = 'PUBLISH_KEY' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) #pubnub.subscribe().channels('magicmirror').execute() pubnub.subscribe().channels('magicmirror').with_presence().execute() print ('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() ### PubNub credentials fill here! pnconfig.subscribe_key = '' pnconfig.publish_key = '' ### credentialt above! pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
def __init__(self, subkey, pubkey, id): """Class constructor :param subkey: PubNub subscription key :param pubkey: PubNub publish key :param id: device id (UUID) """ class MySubscribeListener(SubscribeListener): def __init__(self): self._logger = logging.getLogger('sprinkler') super().__init__() def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: # This event happens when radio / connectivity is lost self._logger.error("Unexpected disconnection") elif status.category == PNStatusCategory.PNConnectedCategory: # Connect event. You can do stuff like publish, and know you'll get it. # Or just use the connected event to confirm you are subscribed for # UI / internal notifications, etc self._logger.info("Connection OK") elif status.category == PNStatusCategory.PNReconnectedCategory: # Happens as part of our regular operation. This event happens when # radio / connectivity is lost, then regained. self._logger.info("Reconnection OK") elif status.category == PNStatusCategory.PNDecryptionErrorCategory: # Handle message decryption error. Probably client configured to # encrypt messages and on live data feed it received plain text. self._logger.error("Decryption error") super().status(pubnub, status) def message(self, pubnub, message): if message.publisher != pubnub.uuid: self._logger.debug(f"RECV from {message.publisher}: \ {json.dumps(message.message['content'])}") super().message(pubnub, message.message['content']) self._logger = logging.getLogger('sprinkler') self.message_listener = MySubscribeListener() self.messages = self.message_listener.message_queue pnconfig = PNConfiguration() pnconfig.subscribe_key = subkey pnconfig.publish_key = pubkey pnconfig.uuid = id pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.subscribe_timeout = 20 self.pubnub = PubNubAsyncio(pnconfig) self.pubnub.add_listener(self.message_listener) self.pubnub.subscribe().channels('sprinkler').execute()
def subscribe(self): r = self.rc.post('/restapi/v1.0/subscription', json=self._request_body()) self.subscription = r.json() pnconfig = PNConfiguration() pnconfig.subscribe_key = self.subscription['deliveryMode'][ 'subscriberKey'] pnconfig.daemon = True pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL self.pubnub = PubNubSDK(pnconfig) self.pubnub.add_listener(self.callback) self.pubnub.subscribe().channels( self.subscription['deliveryMode']['address']).execute()
def async_create_pubnub(user_uuid, subscriptions): """Create a pubnub subscription.""" pnconfig = PNConfiguration() pnconfig.subscribe_key = AUGUST_CHANNEL pnconfig.uuid = f"pn-{str(user_uuid).upper()}" pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pubnub = PubNubAsyncio(pnconfig) pubnub.add_listener(subscriptions) pubnub.subscribe().channels(subscriptions.channels).execute() def _unsub(): pubnub.unsubscribe().channels(subscriptions.channels).execute() return _unsub
async def __aenter__(self): message_decrypter = BeekeeperBotMessageDecrypter( base64.b64decode(self._pubnub_channel_key)) message_listener = BeekeeperBotMessageListener( bot=self, decrypter=message_decrypter) pubnub_config = PNConfiguration() pubnub_config.subscribe_key = self._pubnub_key pubnub_config.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub_config.connect_timeout = 30 self._pubnub = PubNubAsyncio(config=pubnub_config) self._pubnub.add_listener(message_listener) self._pubnub.subscribe().channels([self._pubnub_channel_name ]).execute() return self
def __init__(self): password = raw_input("Database password: ") host = 'ephesus.cs.cf.ac.uk' user = '******' database = 'c1312433' self.db = db.DB(host, user, password, database) pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-12c2dd92-860f-11e7-8979-5e3a640e5579' pnconfig.publish_key = 'pub-c-85d5e576-5d92-48b0-af83-b47a7f21739f' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.subscribe_timeout = pnconfig.connect_timeout = pnconfig.non_subscribe_timeout = 9^99 pnconfig.auth_key = self.db.embedded_devices_key() self.pubnub = PubNub(pnconfig) self.pubnub.add_listener(self) self.pubnub.subscribe().channels('embedded_devices').execute()
def test_reconnection(self): pnconf = PNConfiguration() pnconf.publish_key = "demo" pnconf.subscribe_key = "demo" pnconf.origin = "localhost:8089" pnconf.subscribe_request_timeout = 10 pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) time_until_open_again = 10 @gen.coroutine def close_soon(): yield gen.sleep(3) pubnub.http.close() pubnub.http = None print(">>> connection is broken") @gen.coroutine def open_again(): yield gen.sleep(time_until_open_again) pubnub.http = tornado.httpclient.AsyncHTTPClient( max_clients=PubNubTornado.MAX_CLIENTS) print(">>> connection is open again") @gen.coroutine def countdown(): yield gen.sleep(2) opened = False count = time_until_open_again while not opened: print(">>> %ds to open again" % count) count -= 1 if count <= 0: break yield gen.sleep(1) my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() yield gen.sleep(1000)
async def subscripbe_for_realtime_updates(self) -> None: """Subscribes to PubNub for realtime updates.""" # make a call to vivint's userauth endpoint authuser_data = await self.vivintskyapi.get_authuser_data() pubnub.set_stream_logger("pubnub", logging.INFO) pnconfig = PNConfiguration() pnconfig.subscribe_key = PN_SUBSCRIBE_KEY pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL self.__pubnub = PubNubAsyncio(pnconfig) self.__pubnub.add_listener( VivintPubNubSubscribeListener(self.handle_pubnub_message) ) pn_channel = f'{PN_CHANNEL}#{authuser_data[AuthUserAttributes.Users][AuthUserAttributes.UsersAttributes.MessageBroadcastChannel]}' # noqa self.__pubnub.subscribe().channels(pn_channel).with_presence().execute()
def test_reconnection(self): pnconf = PNConfiguration() pnconf.publish_key = "demo" pnconf.subscribe_key = "demo" pnconf.origin = "localhost:8089" pnconf.subscribe_request_timeout = 10 pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) time_until_open_again = 10 @gen.coroutine def close_soon(): yield gen.sleep(3) pubnub.http.close() pubnub.http = None print(">>> connection is broken") @gen.coroutine def open_again(): yield gen.sleep(time_until_open_again) pubnub.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS) print(">>> connection is open again") @gen.coroutine def countdown(): yield gen.sleep(2) opened = False count = time_until_open_again while not opened: print(">>> %ds to open again" % count) count -= 1 if count <= 0: break yield gen.sleep(1) my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() yield gen.sleep(1000)
def initPubNub(stdscr): """ Ask for a pseudo if not in the path and init the pubnub.PubNub object. Parameters ---------- stdscr: :class:curses._CursesWindow the screen initialised in main.py Returns ------- :class:pubnub.PubNub with configuration """ pseudo = os.getenv("PSEUDO") if pseudo == None: pseudo = "" while len(pseudo) < 2: stdscr.addstr(0, 0, "pseudo :") stdscr.refresh() editwin = curses.newwin(1, min(16, curses.COLS - 1), 1, 1) # pylint: disable=no-member editwin.keypad(True) box = Textbox(editwin) box.edit() pseudo = " ".join(box.gather().split()) alphabet = string.ascii_letters + string.digits pseudo += ''.join(secrets.choice(alphabet) for i in range(10)) with open("assets/data/.env", "a") as file: file.write(f"\nPSEUDO=\"{pseudo}\"") editwin.erase() pnconfig = PNConfiguration() pnconfig.subscribe_key = os.getenv("SUB_KEY") pnconfig.publish_key = os.getenv("PUB_KEY") pnconfig.ssl = True pnconfig.cipher_key = os.getenv("CYPHER_KEY") pnconfig.uuid = pseudo pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pnconfig.connect_timeout = 30 return PubNub(pnconfig)
async def message_pump(self): pnconfig = PNConfiguration() pnconfig.subscribe_key = config['cardsubkey'] # Why aren't these the default settings? pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pubnub = PubNubAsyncio(pnconfig) listener = SubscribeListener() pubnub.add_listener(listener) pubnub.subscribe().channels(config['cardviewerchannel']).execute() await listener.wait_for_connect() log.info("Connected to PubNub") message_future = asyncio.ensure_future( listener.wait_for_message_on(config['cardviewerchannel'])) while True: await asyncio.wait([self.stop_future, message_future], return_when=asyncio.FIRST_COMPLETED) if message_future.done(): message = message_future.result().message log.info("Message from PubNub: %r", message) card_id = self._extract(message) if card_id is not None: await self._card(card_id) message_future = asyncio.ensure_future( listener.wait_for_message_on(config['cardviewerchannel'])) if self.stop_future.done(): break if not message_future.done(): message_future.cancel() pubnub.unsubscribe().channels(config['cardviewerchannel']).execute() await listener.wait_for_disconnect() pubnub.stop() log.info("Disconnected from PubNub")
def __init__(self, gdatabase = None, admin_channel = None): self.gdatabase = gdatabase self.admin_channel = admin_channel if gdatabase is None: password = input("Database password: "******"Rebuilding subscriptions..") subscriptions = self.gdatabase.get_channels() if subscriptions: self.subscribe_channels(subscriptions) self.default_channels = ["policy", "gateway_global", self.admin_channel, "embedded_devices"] print("GatewayReceiver: Subscribing to the Policy server and Gateway global feed..") self.pubnub.grant().channels(self.default_channels[0]).auth_keys([self.gdatabase.receivers_key(), self.gdatabase.policy_key()]).read(True).write(True).manage(True).ttl(0).sync() self.pubnub.grant().channels(self.default_channels[1:]).read(True).write(True).manage(True).sync() self.subscribe_channels(self.default_channels[:-1]) self.pastebin = PasteFetcher.PasteFetcher()
def __init__(self, host, user, password, database): print("GatewayAuth: Starting gateway database..") self.gd = gateway_database.GatewayDatabase(host, user, password, database) pnconfig = PNConfiguration() pnconfig.subscribe_key = self.gd.sub_key() pnconfig.publish_key = self.gd.pub_key() pnconfig.secret_key = self.gd.sec_key() pnconfig.subscribe_timeout = 9 ^ 99 pnconfig.connect_timeout = 9 ^ 99 pnconfig.non_subscribe_timeout = 9 ^ 99 pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.uuid = 'GA' pnconfig.auth_key = idgen.id_generator(size=42) self.pubnub = PubNub(pnconfig) self.pubnub.add_listener(self) self.pubnub.unsubscribe_all() self.admin_channel = idgen.id_generator(size=255) self.pubnub.grant().channels(self.admin_channel).auth_keys( [self.gd.receivers_key(), pnconfig.auth_key]).read(True).write(True).manage(True).sync() print("GatewayAuth: Starting the receiver..") self.gr = gateway_receiver.Receiver(self.gd, self.admin_channel) self.gateway_uuids = [pnconfig.uuid, self.gr.uuid] self.gateway_channels = ["gateway_auth", "gateway_global"] self.pubnub.grant().channels( self.gateway_channels).read(True).write(True).manage(True).sync() print( "GatewayAuth: Connecting to gateway channel and gateway global feed.." ) self.pubnub.subscribe().channels( self.gateway_channels + [self.admin_channel]).with_presence().execute() self.receiver_auth_key = self.gd.receivers_key()
async def subscribe_for_realtime_updates(self, authuser_data: dict = None) -> None: """Subscribes to PubNub for realtime updates.""" # make a call to vivint's authuser endpoint to get message broadcast channel if not supplied if not authuser_data: authuser_data = await self.vivintskyapi.get_authuser_data() pubnub.set_stream_logger("pubnub", logging.INFO) pnconfig = PNConfiguration() pnconfig.subscribe_key = PN_SUBSCRIBE_KEY pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL self.__pubnub = PubNubAsyncio(pnconfig) self.__pubnub.add_listener( VivintPubNubSubscribeListener(self.handle_pubnub_message) ) pn_channel = f"{PN_CHANNEL}#{authuser_data[AuthUserAttribute.USERS][AuthUserAttribute.UserAttribute.MESSAGE_BROADCAST_CHANNEL]}" self.__pubnub.subscribe().channels(pn_channel).with_presence().execute()
async def message_pump(self): pnconfig = PNConfiguration() pnconfig.subscribe_key = config['cardsubkey'] # Why aren't these the default settings? pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pubnub = PubNubAsyncio(pnconfig) listener = SubscribeListener() pubnub.add_listener(listener) pubnub.subscribe().channels(config['cardviewerchannel']).execute() await listener.wait_for_connect() log.info("Connected to PubNub") message_future = asyncio.ensure_future(listener.wait_for_message_on(config['cardviewerchannel'])) while True: await asyncio.wait([self.stop_future, message_future], return_when=asyncio.FIRST_COMPLETED) if message_future.done(): message = message_future.result().message log.info("Message from PubNub: %r", message) card_id = self._extract(message) if card_id is not None: await self._card(card_id) message_future = asyncio.ensure_future(listener.wait_for_message_on(config['cardviewerchannel'])) if self.stop_future.done(): break if not message_future.done(): message_future.cancel() pubnub.unsubscribe().channels(config['cardviewerchannel']).execute() await listener.wait_for_disconnect() pubnub.stop() log.info("Disconnected from PubNub")
def executionsProcess(self): """ pubnubで価格を取得する場合の処理(基本的に不要.) """ channels = ["lightning_executions_FX_BTC_JPY"] executions = self.executions class BFSubscriberCallback(SubscribeCallback): def message(self, pubnub, message): execution = message.message for i in execution: executions.append(i) config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL config.ssl = False config.set_presence_timeout(60) pubnub = PubNubTornado(config) listener = BFSubscriberCallback() pubnub.add_listener(listener) pubnub.subscribe().channels(channels).execute() pubnubThread = threading.Thread(target=pubnub.start) pubnubThread.start()
class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): print("### status changed to: %s" % status.category) if status.category == PNStatusCategory.PNReconnectedCategory: pubnub.stop() def message(self, pubnub, message): pass def presence(self, pubnub, presence): pass pnconf = PNConfiguration() pnconf.publish_key = "demo" pnconf.subscribe_key = "demo" pnconf.origin = "localhost:8089" pnconf.subscribe_request_timeout = 10 pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconf) time_until_open_again = 8 my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() # atexit.register(pubnub.stop)
from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado from pubnub.pnconfiguration import PNReconnectionPolicy import pandas as pd from datetime import datetime, timezone, timedelta #API_KEYとAPI_SECRETを記述 #my_order_size == 一度に買いたい量 my_order_size = 0.001 API_KEY = "Your_API_KEY" API_SECRET = "Your_API_SECRET" config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNubTornado(config) api = pybitflyer.API(api_key=API_KEY, api_secret=API_SECRET) df_all = pd.DataFrame(index=['datetime'], columns=[ 'id', 'side', 'price', 'size', 'exec_date', 'buy_child_order_acceptance_id', 'sell_child_order_acceptance_id' ]) # entry buy or sell position def entry(side, order_size): print('[' + side + ' Entry]') now_tick = api.ticker(product_code="FX_BTC_JPY") #現在の中間価格を代入
from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score from nltk.stem.porter import PorterStemmer from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from textstat.textstat import * from keras.models import load_model import json from keras.models import model_from_json pn_twitter_config = PNConfiguration() pn_twitter_config.subscribe_key = 'sub-c-78806dd4-42a6-11e4-aed8-02ee2ddab7fe' pn_twitter_config.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pubnub_twitter = PubNub(pn_twitter_config) pn_config = PNConfiguration() pn_config.subscribe_key = 'sub-c-93679206-1202-11e8-bb84-266dd58d78d1' pn_config.publish_key = 'pub-c-44842793-32df-4b69-b576-4495abcf64ec' pubnub_personal = PubNub(pn_config) #TF hack os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #Change Folder Path here raw_data_path = "/Users/ritiztambi/repos/Twitter-RealtimeAnalysis-Pubnub" os.chdir(raw_data_path) #Creating dataframes
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.blockchain.block import Block pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-7c05ce8e-61ab-11ea-aaa3-eab2515ceb0d' pnconfig.publish_key = 'pub-c-d7e75e4e-3274-4017-83d4-e940969268e1' pnconfig.reconnect_policy = 'PNReconnectionPolicy.EXPONENTIAL' CHANNELS = { 'TEST': 'TEST', 'BLOCK': 'BLOCK' } class Listener(SubscribeCallback): def __init__(self, blockchain): self.blockchain = blockchain def message(self, pubnub, message_object): print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block) try:
def __init__(self, channels): self.channels = channels pnc = PNConfiguration() pnc.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' pnc.reconnect_policy = PNReconnectionPolicy.LINEAR self.pubnub = PubNubTornado(pnc)