def test_events_batch(self): events_list = [ { "event": "Signed Up", "properties": { "distinct_id": "13793", "token": "e3bc4100330c35722740fb8c6f5abddc", "Referred By": "Friend", "time": 1371002000 } }, { "event": "Uploaded Photo", "properties": { "distinct_id": "13793", "token": "e3bc4100330c35722740fb8c6f5abddc", "Topic": "Vacation", "time": 1371002104 } } ] token = "e3bc4100330c35722740fb8c6f5abddc" mp = Mixpanel(token) mock_response = Mock() mock_response.read.return_value = '1' data = mp._prepare_data(events_list) with patch('urllib2.Request', return_value = mock_response) as mock_Request: with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen: mp.send_events_batch(events_list) mock_Request.assert_called_once_with(self.track_request_url, data)
def mixpanel_track(distinct_id, event_name, properties=None, utm=None, user_ip=None, user_agent=None): if not distinct_id: return if not settings.DEBUG and domain_exclude and distinct_id.endswith( domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return # if utm: # properties.update({ # "utm_referrer": utm.get("referrer"), # "utm_source": utm.get("source"), # "utm_campaign": utm.get("campaign"), # "utm_medium": utm.get("medium"), # }) mp = Mixpanel(id) mp.track(distinct_id, event_name, properties or {})
def __init__(self): # init the client ID and config if it doesn't exist if not CONFIG_FILE.exists(): self.client_id = str(uuid.uuid4()) self.update_config() else: self.load_config() # send updated user-level properties self.mp = None if self.enabled: try: self.mp = Mixpanel( MIXPANEL_TOKEN, consumer=Consumer(request_timeout=int(TIMEOUT))) self.mp.people_set( self.client_id, { "datahub_version": datahub_package.nice_version_name(), "os": platform.system(), "python_version": platform.python_version(), }, ) except Exception as e: logger.debug(f"Error connecting to mixpanel: {e}")
def mutate(self, info, **parameters): success = False file_info = parameters['files_data'] project_name = parameters['project_name'].lower() user_email = util.get_jwt_content(info.context)['user_email'] signed_url = resources.download_file(file_info, project_name) if signed_url: msg = 'Security: Downloaded file {file_name} in project {project} succesfully'\ .format(project=project_name, file_name=parameters['files_data']) util.cloudwatch_log(info.context, msg) mp_obj = Mixpanel(settings.MIXPANEL_API_TOKEN) mp_obj.track(user_email, 'DownloadProjectFile', { 'Project': project_name.upper(), 'Email': user_email, 'FileName': parameters['files_data'], }) success = True else: util.cloudwatch_log(info.context, 'Security: Attempted to download file {file_name} \ in project {project}'.format(project=project_name, file_name=parameters['files_data'])) rollbar.report_message('Error: \ An error occurred generating signed URL', 'error', info.context) ret = DownloadFile(success=success, url=str(signed_url)) return ret
def check_update(): """ Check if there is a later version of Screenly OSE available. Only do this update once per day. Return True if up to date was written to disk, False if no update needed and None if unable to check. """ sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha') device_id_file = path.join(settings.get_configdir(), 'device_id') if path.isfile(sha_file): sha_file_mtime = path.getmtime(sha_file) last_update = datetime.fromtimestamp(sha_file_mtime) else: last_update = None if not path.isfile(device_id_file): device_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(15)) with open(device_id_file, 'w') as f: f.write(device_id) else: with open(device_id_file, 'r') as f: device_id = f.read() logging.debug('Last update: %s' % str(last_update)) git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip() git_hash = sh.git('rev-parse', '--short', 'HEAD').strip() if last_update is None or last_update < (datetime.now() - timedelta(days=1)): if not settings['analytics_opt_out'] and not is_ci(): mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56') try: mp.track(device_id, 'Version', { 'Branch': str(git_branch), 'Hash': str(git_hash), }) except MixpanelException: pass except AttributeError: pass if remote_branch_available(git_branch): latest_sha = fetch_remote_hash(git_branch) if latest_sha: with open(sha_file, 'w') as f: f.write(latest_sha) return True else: logging.debug('Unable to fetch latest hash.') return else: touch(sha_file) logging.debug('Unable to check if branch exist. Checking again tomorrow.') return else: return False
def track_achievement_creation(achievement, user): """Logs the creation of a new Achievement, and its player if they're logged in. Parameter: achievement(Achievement): the Achievement being created user(User): the user earning the Achievement Returns: None """ # instantiate the Mixpanel tracker mp = Mixpanel(settings.MP_PROJECT_TOKEN) # Set the properties properties = dict() properties["achievementType"] = achievement.mission.question.category # set the user property if user.is_authenticated: properties["user"] = user.username else: # user is not authenticated properties["user"] = "******" # track the event try: mp.track( properties["user"], event_name="createAchievement", properties=properties ) # let Mixpanel fail silently in the dev environment except MixpanelException: pass return None
def get_new_users(key, time_in_minutes): """Gets new users from MixPanel.""" logging.info('Making an API call to MixPanel') api = Mixpanel(api_secret=str(key).strip()) mixpanel_data = {} current_time = int(time.time()) time_in_seconds = int(float(time_in_minutes) * 60) created_start_search = 'datetime({0})'.format(current_time - time_in_seconds - RUNTIME) try: mixpanel_data = api.request( ['engage'], {'where': '{0} < user["$created"]'.format(created_start_search)}) # '(properties["$created"]) > XXXX-YY-ZZ' except (urllib2.URLError, urllib2.HTTPError) as error: logging.exception('An error occurred: {0}'.format(error)) # Pagination with weird MixPanel API session_id = mixpanel_data['session_id'] # Unsure if it stays the same current_page = mixpanel_data['page'] current_total = mixpanel_data['total'] while current_total >= 1000: logging.info('Page: {0}'.format(current_page + 1)) try: mixpanel_data['results'].append( api.request(['engage'], { 'page': current_page + 1, 'session_id': session_id })['results']) except (urllib2.URLError, urllib2.HTTPError) as error: logging.error('An error occurred: {0}'.format(error)) pass return mixpanel_data
def track_first_device(self): if self.user.devices.count() == 1 and settings.MIXPANEL_TOKEN: try: mp = Mixpanel(settings.MIXPANEL_TOKEN) mp.track(self.user.email, 'First Node') except MixpanelException: logger.exception('Failed to send First Device event')
def mutate(self, info, **parameters): success = False file_info = parameters['files_data'] project_name = parameters['project_name'].lower() file_url = project_name + "/" + file_info minutes_until_expire = 1.0 / 6 signed_url = resources.sign_url(FI_CLOUDFRONT_RESOURCES_DOMAIN, file_url, minutes_until_expire) if signed_url: user_email = info.context.session['username'] msg = 'Security: Downloaded file {file_name} in project {project} succesfully'\ .format(project=project_name, file_name=parameters['files_data']) util.cloudwatch_log(info.context, msg) mp_obj = Mixpanel(settings.MIXPANEL_API_TOKEN) mp_obj.track( user_email, 'DownloadProjectFile', { 'Project': project_name.upper(), 'Email': user_email, 'FileName': parameters['files_data'], }) success = True else: util.cloudwatch_log( info.context, 'Security: Attempted to download file {file_name} \ in project {project}'.format( project=project_name, file_name=parameters['files_data'])) rollbar.report_message( 'Error: \ An error occurred generating signed URL', 'error', info.context) ret = DownloadFile(success=success, url=str(signed_url)) return ret
def post_event(token, data): mixpanel = Mixpanel(token) distinct_id = data["custom_data"]["$mixpanel_distinct_id"] event_name = data["name"] if distinct_id is None: return 'Missing distinct_id' mixpanel.track(distinct_id, event_name, data) print('Sent')
def users(email, name=None, ip=None): mp = Mixpanel(TOKEN) params = {'$email': email} if name: params['$name'] = name if ip: params['$ip'] = ip mp.people_set(email, params)
def ping_mixpanel(): mp = Mixpanel(settings.MIXPANEL_TOKEN) try: mp.track(settings.DEVICE_ID, 'ping', {'Balena': bool(settings.BALENA)}) except MixpanelException: pass except AttributeError: pass
def ping_mixpanel(): mp = Mixpanel(settings.MIXPANEL_TOKEN) try: mp.track(settings.DEVICE_ID, 'ping') except MixpanelException: pass except AttributeError: pass
def track_event(user, event_name, event_properties={}): # Don't track events during unit tests if in_testing_mode(): return mixpanel_token = getattr(settings, 'MIXPANEL_TOKEN', None) if mixpanel_token: mixpanel = Mixpanel(mixpanel_token) mixpanel.track(str(user.id), event_name, event_properties)
def test_alias(self): token = '12345' mp = Mixpanel(token) mock_response = Mock() mock_response.read.return_value = '1' with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen: mp.alias('amq','3680') data = mp._prepare_data({'event': '$create_alias', 'properties': {'distinct_id': '3680', 'alias': 'amq', 'token': '12345'}}) mock_urlopen.assert_called_once_with(self.engage_request_url, data)
def test_people_set(self): token = '12345' mp = Mixpanel(token) mock_response = Mock() mock_response.read.return_value = '1' with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen: mp.people_set('amq', {'birth month': 'october', 'favorite color': 'purple'}) data = mp._prepare_data({'$token': '12345', '$distinct_id': 'amq', '$set': {'birth month': 'october', 'favorite color': 'purple'}}) mock_urlopen.assert_called_once_with(self.engage_request_url, data)
def test_track(self): token = '12345' mp = Mixpanel(token) mock_response = Mock() mock_response.read.return_value = '1' with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen: mp.track('button press', {'size': 'big', 'color': 'blue'}) data = mp._prepare_data({'event': 'button press', 'properties': {'token': '12345', 'size': 'big', 'color': 'blue'}}) mock_urlopen.assert_called_once_with(self.track_request_url, data)
def track(user_id, event, properties=None): if not settings.TRACK_EVENTS: return data = {'source': 'web'} if properties: data = dict(data.items() + properties.items()) mp = Mixpanel(Events.PROJECT_TOKEN) mp.track(user_id, event, data)
def form_valid(self, form): device = form.cleaned_data['device'] device.associate_and_publish_associated_msg(self.request.user) mp = Mixpanel(settings.MIXPANEL_TOKEN) mp.track(device.user.username, "LAMPI Activation", {'event_type': 'activations', 'interface': 'web', 'device_id': device.device_id}) return super(AddLampiView, self).form_valid(form)
def mixpanel_alias(new_id, old_id): if not settings.DEBUG and domain_exclude and new_id.endswith(domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return mp = Mixpanel(id) mp.alias(new_id, old_id)
def mixpanel_alias(new_id, old_id): if not settings.DEBUG and domain_exclude and new_id.endswith( domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return mp = Mixpanel(id) mp.alias(new_id, old_id)
def mixpanel_track_charge(distinct_id, amount): if not settings.DEBUG and domain_exclude and distinct_id.endswith(domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return mp = Mixpanel(id) mp.people_track_charge(distinct_id, amount, { '$time': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') })
def load(self, options: PluginLoadOptions) -> None: self._consumer = BufferedConsumer( max_size=self._options.flush_queue_size, request_timeout=int(self._options.request_timeout.total_seconds()), events_url=None if self._options.api_host is None else f'{self._options.api_host}/track', people_url=None if self._options.api_host is None else f'{self._options.api_host}/engage', ) self._client = Mixpanel( token=self._api_key, consumer=self._consumer, ) self._logger = options.logger
def __init__(self, settings: SettingsType, distinct_id=None, global_event_props=None) -> None: """Initialize API connector.""" self.distinct_id = distinct_id self.events = self._resolve_events(settings.get("mixpanel.events")) self.event_properties = self._resolve_event_properties( settings.get("mixpanel.event_properties")) self.profile_properties = self._resolve_profile_properties( settings.get("mixpanel.profile_properties")) self.profile_meta_properties = self._resolve_profile_meta_properties( settings.get("mixpanel.profile_meta_properties")) use_structlog = settings.get("pyramid_heroku.structlog", False) is True consumer = self._resolve_consumer(settings.get("mixpanel.consumer"), use_structlog) if settings.get("mixpanel.token"): self.api = Mixpanel(token=settings["mixpanel.token"], consumer=consumer) else: self.api = Mixpanel(token="testing", consumer=MockedConsumer()) # nosec if global_event_props: self.global_event_props = global_event_props else: self.global_event_props = {} if (settings.get("customerio.tracking.site_id") and settings.get("customerio.tracking.api_key") and settings.get("customerio.tracking.region")): # This is here because customerio support is an install extra, # i.e. it is optional from customerio import CustomerIO from customerio import Regions if settings["customerio.tracking.region"] == "eu": region = Regions.EU elif settings["customerio.tracking.region"] == "us": region = Regions.US else: raise ValueError("Unknown customer.io region") self.cio = CustomerIO( settings["customerio.tracking.site_id"], settings["customerio.tracking.api_key"], region=region, ) else: self.cio = None
def signup(request): """Render the Signup form or a process a signup """ mp = Mixpanel("a28ae260bcb8356ddcbb5658e35cb787") print("hello101","natashalee") if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() id = form.cleaned_data.get('username') print("distinct_id",id) username = form.cleaned_data.get('first_name') print("first_name",username) lastname = form.cleaned_data.get('last_name') print("last_name",lastname) email = form.cleaned_data.get('email') print("email",email) mp.alias(email, id) print("Alias created for "+ email + " and distinct ID is " + id) now = datetime.datetime.now() mp.track(id, 'Signup', { 'Username': username, 'SignUp Date': now.isoformat() }) print("SignUp Date",now.isoformat()) mp.track(id, 'Page View', { 'PageName': 'Signup Page', 'SignUp PageView Date': now.isoformat() }) mp.people_set(id, { '$name' : username, '$last_name' : lastname, '$email' : email, 'SignUpDate': now.isoformat() }, meta = {'$ignore_time' : 'true', '$ip' : 0}) raw_password = form.cleaned_data.get('password1') user = authenticate(username=id, password=raw_password) log_in(request, user) return HttpResponseRedirect('/') else: form = SignUpForm() return render(request, 'images/signup.html', {'form': form})
def on_event(self,event,payload): if not hasattr(self, 'mp'): # Attach static but essential mixpanel information to this Plugin instance if not already. The 2 pieces of static data are the token that links to the specific mixpanel project and the printer's id to which printer event will be correlated. token = self._settings.get(['token']) self.printer_id = self._settings.get(['printer_id']) self.mp = Mixpanel(token) mixpanel_payload = generate_mixpanel_payload(event, payload) if mixpanel_payload: self.mp.track(self.printer_id, event, mixpanel_payload) else: return
def mixpanel_track_charge(distinct_id, amount): if not settings.DEBUG and domain_exclude and distinct_id.endswith( domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return mp = Mixpanel(id) mp.people_track_charge( distinct_id, amount, {'$time': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')})
def do_set_alert(data): """Function set_alert.""" try: company = data.split(CMD_SEP)[1] project = data.split(CMD_SEP)[2] message = ' '.join(data.split(CMD_SEP)[3:]) if project.find('\'') >= 0: output = SQL_ERROR else: if message in ('ACTIVATE', 'DEACTIVATE'): integrates_dao.change_status_comalert_dynamo( message, company, project) output = \ '*[OK]* Alert for *"%s"* in *%s* has been *%sD*.' % \ (project.upper(), company.upper(), message.upper()) mp_obj = Mixpanel(settings.MIXPANEL_API_TOKEN) mp_obj.track(project, 'BOT_ActivateAlert') else: if integrates_dao.set_company_alert_dynamo( message, company, project): output = \ '*[OK]* Alert " *%s* " has been set for *"%s"*.' % \ (message, company) mp_obj = Mixpanel(settings.MIXPANEL_API_TOKEN) mp_obj.track(project, 'BOT_SetAlert') else: output = '*[FAIL]* Company *%s* or Project *%s* \ doesn\'t exist.' % (company, project) except ValueError: output = CANT_DO_ERROR return output
def is_up_to_date(): """ Primitive update check. Checks local hash against GitHub hash for branch. Returns True if the player is up to date. """ latest_sha, retrieved_update = fetch_remote_hash() git_branch = get_git_branch() git_hash = get_git_hash() git_short_hash = get_git_short_hash() get_device_id = r.get('device_id') if not latest_sha: logging.error('Unable to get latest version from GitHub') return True if not get_device_id: device_id = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(15)) r.set('device_id', device_id) else: device_id = get_device_id if retrieved_update: if not settings['analytics_opt_out'] and not is_ci(): mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56') try: mp.track( device_id, 'Version', { 'Branch': str(git_branch), 'Hash': str(git_short_hash), 'NOOBS': os.path.isfile('/boot/os_config.json'), 'Balena': is_balena_app(), 'Docker': is_docker(), 'Pi_Version': lookup_raspberry_pi_revision( parse_cpu_info()['revision'])['model'] }) except MixpanelException: pass except AttributeError: pass return latest_sha == git_hash
class MixpanelClient(BaseClient): def __init__(self, token, **kwargs): super().__init__(**kwargs) self._client = Mixpanel(token=token) def register_purchase(self, user: User, amount: int, currency: str, source_integration: str): self._client.track( str(user.pk), "new_purchase", dict(amount=amount, currency=currency, source_integration=source_integration), )
def get_event_data(events, unit=DEFAULT_UNIT, interval=DEFAULT_INTERVAL): """Retrieve event data for a list of events""" MIXPANEL_API_KEY = os.environ["MIXPANEL_API_KEY"] MIXPANEL_API_SECRET = os.environ["MIXPANEL_API_SECRET"] client = Mixpanel(api_key=MIXPANEL_API_KEY, api_secret=MIXPANEL_API_SECRET) response = client.request('events', 'general', { 'event' : events, 'unit' : unit, 'interval' : interval }) return response['data']['values']
def track(id, metric, data, **kwargs): """ Sends a metrics event to mixpanel :param id: The unique ID for this event :param metric: The name of the metric event :param data: A dictionary containing additional properties associated with this event :param kwargs: Additional arguments that will be passed through to Mixpanel's track function """ global _mp if _mp is None: _mp = Mixpanel(Config.MIXPANEL_TOKEN, EnqueuingConsumer()) _mp.track(id, metric, data, **kwargs)
def _trace_mixpanel(action_name, auth_user, client_user, client_token, kwargs): from mixpanel import Mixpanel from mixpanel_async import AsyncBufferedConsumer some_user_id = auth_user or client_user or client_token try: if action_name in ["get_server_info", "publish"]: mp = Mixpanel(BII_MIXPANEL_TOKEN, consumer=AsyncBufferedConsumer()) properties = {'action': action_name, 'anonymous': (some_user_id == client_token)} if action_name == "get_server_info": properties["os"] = kwargs["bson_data"]["data"][0]["family"] properties["biicode_version"] = kwargs["bson_data"]["data"][1] mp.track(some_user_id, BII_API_MIXPANEL_EVENT_NAME, properties) except Exception as e: logger.warning("Error sending action to mixpanel: %s" % e)
def logout(request): """Logout the user """ mp = Mixpanel("a28ae260bcb8356ddcbb5658e35cb787") log_out(request) return HttpResponseRedirect('/')
def do_tracking(project_token, distinct_id, queue): ''' This process represents the work process where events and updates are generated. This might be the service thread of a web service, or some other process that is mostly concerned with getting time-sensitive work done. ''' consumer = QueueWriteConsumer(queue) mp = Mixpanel(project_token, consumer) for i in xrange(100): event = 'Tick' mp.track(distinct_id, 'Tick', {'Tick Number': i}) print 'tick {0}'.format(i) queue.put(None) # tell worker we're out of jobs
def __init__(self): with open('etc/mp.yml', 'r') as f: mp = yaml.load(f) self.api = Mixpanel( api_key=mp['api_key'], api_secret=mp['api_secret'] )
def setUp(self): self.requests_mock = responses.RequestsMock(assert_all_requests_are_fired=False) self.requests_mock.start() self._mock_user() self._mock_email() mock_mp = Mixpanel('dummy_token', MockMixpanelConsumer()) self.mp_patcher = mock.patch('quilt_server.views.mp', mock_mp) self.mp_patcher.start() self.payments_patcher = mock.patch('quilt_server.views.HAVE_PAYMENTS', False) self.payments_patcher.start() self.s3_stubber = Stubber(s3_client) self.s3_stubber.activate() random_name = ''.join(random.sample(string.ascii_lowercase, 10)) self.db_url = 'postgresql://postgres@localhost/test_%s' % random_name self.app = quilt_server.app.test_client() quilt_server.app.config['TESTING'] = True quilt_server.app.config['SQLALCHEMY_ECHO'] = False quilt_server.app.config['SQLALCHEMY_DATABASE_URI'] = self.db_url sqlalchemy_utils.create_database(self.db_url) quilt_server.db.create_all()
def get_mixpanel_client(): global _mixpanel_client if _mixpanel_client is None: mixpanel_key = getattr(settings, 'MIXPANEL_KEY', None) if mixpanel_key: _mixpanel_client = Mixpanel(mixpanel_key) return _mixpanel_client
def do_tracking(project_token, distinct_id, queue): """ This process represents the work process where events and updates are generated. This might be the service thread of a web service, or some other process that is mostly concerned with getting time-sensitive work done. """ consumer = QueueWriteConsumer(queue) mp = Mixpanel(project_token, consumer) for i in xrange(100): event = "Tick" mp.track(distinct_id, "Tick", {"Tick Number": i}) print "tick {0}".format(i) queue.put(None) # tell worker we're out of jobs
class MixpanelOnLawpal(object): token = None service = None def __init__(self, *args, **kwargs): self.token = kwargs.get('token', MIXPANEL_SETTINGS.get('token', None)) if self.token is not None: self.service = Mixpanel(self.token) def mixpanel_alias(self, alias_id, original, **kwargs): if self.service is not None: try: self.service.alias(alias_id=alias_id, original=original, **kwargs) except Exception as e: logger.error('Mixpanel error: distinct_id, missing or empty: %s :%s' % (alias_id, e)) def mixpanel_track_charge(self, user, amount, time, distinct_id=None, **kwargs): if self.service is not None: if distinct_id is None: distinct_id = user.pk try: self.service.people_track_charge(distinct_id=distinct_id, amount=amount, properties={ '$time': time }) except Exception as e: logger.error('Mixpanel error: %s' % e) def event(self, key, user, distinct_id=None, **kwargs): if self.service is not None: if distinct_id is None: distinct_id = user.pk user_profile = user.profile all_properties = { 'account_type': user_profile.account_type, 'plan': user_profile.plan, 'plan_interval': user_profile.plan_interval, 'user': user.get_full_name(), 'user_type': user_profile.type, 'via': 'web' } all_properties.update(kwargs) try: self.service.track(distinct_id=distinct_id, event_name=key, properties=all_properties) except Exception as e: logger.error('Mixpanel error: %s' % e) def anon_event(self, key, distinct_id, **kwargs): if self.service is not None: all_properties = { 'user_id': distinct_id, 'account_type': 'anonymous', 'via': 'web' } all_properties.update(kwargs) try: self.service.track(distinct_id=distinct_id, event_name=key, properties=all_properties) except Exception as e: logger.error('Mixpanel error: %s' % e)
def get_mixpanel_client(): # Why this? seems like there must be a simpler way global _mixpanel_client if _mixpanel_client is None: mixpanel_key = getattr(settings, 'MIXPANEL_KEY', None) if mixpanel_key: _mixpanel_client = Mixpanel(mixpanel_key) return _mixpanel_client
def mixpanel_event(name, username=None, properties=None): """ Takes an event name and a dict of args and registers it with Mixpanel. If the username is None, it will assumed that it can be found in a .siphon file in the directory. """ # Use AsyncBufferedConsumer to avoid blocking the main thread mp = Mixpanel(MIXPANEL_TOKEN, consumer=AsyncBufferedConsumer()) if not username: auth = Auth() username = auth.username props = {'user_platform': get_platform_name()} if properties: props.update(properties) mp.track(username, name, props)
def do_add_project(data): """Function add_project.""" try: project = data.split(CMD_SEP)[1] project_type = data.split(CMD_SEP)[2].lower() text = ' '.join(data.split(CMD_SEP)[3:]) try: if project_type not in ('continuous', 'oneshot'): output = 'You must enter the project type: \ *Continuous* or *Oneshot*.' return output else: companies_text = \ text[(text.index('[') + 1):text.index(']')].split(',') companies = map(unicode.strip, companies_text) description = ' '.join(text.split('] ')[1:]) except ValueError: output = \ 'You must enter the company or companies names \ within square brackets [] and comma separated.' return output if project.find('\'') >= 0 or description.find('\'') >= 0: output = SQL_ERROR elif companies == ['']: output = 'You must enter the company or companies names.' elif description.strip() == '': output = 'You must enter a project description.' else: if integrates_dao.create_project_dao(project, description): integrates_dao.add_project_dynamo(project, description, companies, project_type, status='ACTIVE') output = \ '*[OK]* Created project *%s* *%s* *"%s"* *%s*.' % \ (project, project_type, description, companies) mp_obj = Mixpanel(settings.MIXPANEL_API_TOKEN) mp_obj.track(project.upper(), 'BOT_AddProject') else: output = '*[FAIL]* Project *%s* already exists.' % (project) except ValueError: output = CANT_DO_ERROR return output
def submit_scholarship(req): if req.method == 'GET': context = { 'page_title': 'About Scholar Hippo' } return render_to_response('submit_scholarship.html', context) elif req.method == 'POST': payload = json.loads(req.body) submitted_scholarship = SubmittedLink(title=payload['title'], third_party_url=payload['url']) if 'email' in payload: submitted_scholarship.email = payload['email'] submitted_scholarship.save() mp = Mixpanel('2871f3b0cb686b7f9fff1ba66d042817') mp.track(0, 'submission', { 'title': payload['title'] }) client.captureMessage("New scholarship submitted.", title=payload['title']) return HttpResponse(json.dumps({'msg': 'thanks dawg'}))
def bb_track(title="", data={}): """ Wrapper function for backend mixpanel tracking. One day we may be able to refactor this to the adapter pattern for multiple metrics. """ if not title: return False mp = None key = getattr(properties, 'MIXPANEL', None) if key: mp = Mixpanel(key) else: return False if mp: mp.track(None, title, data)
def mixpanel_main(): api_client = Mixpanel(mp['APIKEY'], mp['APISECRET']) data = api_client.request(['events'], { 'event' : ['create_feature', 'signup', 'add_member'], 'unit' : 'week', 'interval' : 2, 'type': 'general' }) date = data['data']['series'][0] print "Metrics for the week\n" print "Mixpanel\n" global mp_signups global mp_members global mp_features mp_signups = data['data']['values']['signup'][date] mp_members = data['data']['values']['add_member'][date] mp_features = data['data']['values']['create_feature'][date] print "Signups: " + str(mp_signups) print "Members added: " + str(mp_members) print "Created first feature: " + str(mp_features)
class MixpanelPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.EventHandlerPlugin,octoprint.plugin.SettingsPlugin): """ It responds to events, generates mixpanel data and registers it to mixpanel server """ def on_after_startup(self): self._logger.info("Hello World! I want to log events!") def on_event(self,event,payload): if not hasattr(self, 'mp'): # Attach static but essential mixpanel information to this Plugin instance if not already. The 2 pieces of static data are the token that links to the specific mixpanel project and the printer's id to which printer event will be correlated. token = self._settings.get(['token']) self.printer_id = self._settings.get(['printer_id']) self.mp = Mixpanel(token) mixpanel_payload = generate_mixpanel_payload(event, payload) if mixpanel_payload: self.mp.track(self.printer_id, event, mixpanel_payload) else: return
def __init__(self, api_key, api_secret, period_threshold = 1, usage_threshold = 1, where = "true", period = "week"): self.api_key = api_key self.api_secret = api_secret self.api = Mixpanel(self.api_key, self.api_secret) #self.users = [] self.daily_threshold = period_threshold self.usage_threshold = usage_threshold self.where = where self.period = period self.user_data = {} pass
def mixpanel_people_set(distinct_id, event_name, value=None, increment=False): """ If value not set value = datetime` """ if not distinct_id: return if not settings.DEBUG and domain_exclude and distinct_id.endswith(domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return mp = Mixpanel(id) if increment: mp.people_increment(distinct_id, {event_name: value}) else: if value is None: value = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') mp.people_set(distinct_id, {event_name: value})
class Analytics: # Setup analytics. # dnt - do not track. Disables tracking if True # token - The mixpanel token def __init__(self, dnt, token): self.dnt = dnt self.tracker = Mixpanel(token) if(self.dnt == True): print "[+] Analytics disabled" # Track an event # event - string containing the event name # data - data related to the event, defaults to {} def track(self, event, data = {}): if(self.dnt == False): # All events are tracked anonymously self.tracker.track("anonymous", event, data) # Track a visit to a URL # The url maybe an HN submission or # some meta-url pertaining to hackertray def visit(self, url): self.track('visit', {"link":url})
def mixpanel_track(distinct_id, event_name, properties=None, utm=None, user_ip=None, user_agent=None): if not distinct_id: return if not settings.DEBUG and domain_exclude and distinct_id.endswith(domain_exclude): return id = settings.METRICS.get('mixpanel', {}).get('id') if not id: logger.info('Mixpanel id not defined, task ignored') return # if utm: # properties.update({ # "utm_referrer": utm.get("referrer"), # "utm_source": utm.get("source"), # "utm_campaign": utm.get("campaign"), # "utm_medium": utm.get("medium"), # }) mp = Mixpanel(id) mp.track(distinct_id, event_name, properties or {})
def post(self, *args, **kwargs): mp = Mixpanel('e8fca4fdf3a958f40dbaa6f86dd7d26b') if 'profile_id' in self.request.session: profile_id = self.request.session['profile_id'] profile = StudentCourseProfile.objects.get(id=profile_id) data = self.request.POST form = ContactInfoForm(data=data) if form.is_valid(): user = form.save() profile.user = user profile.save() mp.track(user.id, 'User signup') return HttpResponseRedirect(reverse('thank-you')) else: self.context['form'] = form return render(self.request, self.template_name, self.context) else: return HttpResponseRedirect(reverse('toefl'))
def getShownSubModal(api_key, api_secret, startDate, endDate): # print 'Requesting Mixpanel data' api = Mixpanel( api_key = api_key, api_secret = api_secret ) data = api.request(['export'], { 'event' : ['Show subscription modal',], 'from_date' : startDate, 'to_date' : endDate }) uniques = set() # biggestDate = 0 lines = data.split('\n') # print "Received %d entries" % len(lines) for line in lines: try: if len(line) is 0: continue event = json.loads(line) properties = event['properties'] if not event['event'] in ['Show subscription modal']: print 'Unexpected event ' + event['event'] break # print 'Processing', event['event'], properties['time'], properties['dateCreated'] if 'distinct_id' in properties and not properties['distinct_id'] in uniques: uniques.add(properties['distinct_id']) # if int(properties['time']) > biggestDate: # biggestDate = int(properties['time']) except: print "Unexpected error:", sys.exc_info()[0] print line break # print 'Biggest date:', datetime.utcfromtimestamp(int(properties['time'])) return len(uniques)
class MixpanelTest(object): def __init__(self): with open('etc/mp.yml', 'r') as f: mp = yaml.load(f) self.api = Mixpanel( api_key=mp['api_key'], api_secret=mp['api_secret'] ) def request(self, funnel_id, seg_property, from_date): data = self.api.request(['funnels'], { 'funnel_id': funnel_id, 'on': 'properties["%s"]' % seg_property, 'from_date': from_date, 'to_date': datetime.date.today().isoformat(), 'interval': 60 })['data'] return data[from_date] def test(self, data, control, variations): update = {} buckets = [control] + variations for bucket in buckets: total = data[bucket][0]['count'] successes = data[bucket][1]['count'] update[bucket] = (successes, total - successes) test = Trials(buckets) test.update(update) dominances = test.evaluate('dominance', control=control) lifts = test.evaluate('expected lift', control=control) intervals = test.evaluate('lift CI', control=control, level=95) for variation in variations: print('Variation {name}:'.format(name=variation)) s, t = update[variation] print('* Successes: {0}, Total: {1}, Percent: {2:2.3f}%'.format(s, t, 100*float(s)/t)) print('* E[lift] = {value:.2%}'.format(value=lifts[variation])) print('* P({lower:.2%} < lift < {upper:.2%}) = 95%'.format(lower=intervals[variation][0], upper=intervals[variation][2])) print('* P({name} > {control}) = {value:.2%}'.format(name=variation, control=control, value=dominances[variation])) print
def events(email, event_name, properties={}): mp = Mixpanel(TOKEN) mp.track(email, event_name, properties)
import sys import json import subprocess from mixpanel import Mixpanel mpResults = Mixpanel("f9ce3b0a5f0c588c7219f4624085db0e") ########################################################################################################################################## ########################################################################################################################################## #----------------------------------------------------METRICA LINEAS DE CODIGO------------------------------------------------------------- ########################################################################################################################################## ########################################################################################################################################## network_list = ["twitter", "facebook", "github","googleplus","instagram"] version_list = ["master","latency", "accuracy"] #consola: python code_lines.py component version if len(sys.argv) >= 2: social_network = sys.argv[1] else: social_network = '' if len(sys.argv) >= 3: version= sys.argv[2] else: version = '' #CASOS: if social_network in network_list: