def handle_text(message): data = event('voice', 'send_text') report(ANALYTICS_TRACKING_ID, ANALYTICS_ACCOUNT_ID, data) first_word = message.text.split(' ', 1)[0] if first_word.lower() == 'lyrics': artist = "" song = "" songname = message.text.split(first_word + ' ', 1)[1] if songname.count(" - ") == 1: artist, song = songname.rsplit(" - ", 1) if songname.count(" – ") == 1: artist, song = songname.rsplit(" – ", 1) if songname.count(" - ") == 2: artist, song, garbage = songname.rsplit(" - ", 2) if " / " in song: song, garbage = song.rsplit(" / ", 1) song = re.sub(' \(.*?\)', '', song, flags=re.DOTALL) if check_chinese(artist): bot.send_message(message.chat.id, 'Only English or Russian') else: send_lyrics(message, artist, song) else: bot.send_message( message.chat.id, "Just send me voice message and i'll try to recognize the song!")
def main(): parser = argparse.ArgumentParser(description='Send ecommerce transactions to Google Analytics') parser.add_argument('--google-analytics-id', '-g', dest='google_analytics_id', default=None, help='Google Analytics ID') parser.add_argument('--input-file', '-i', type=argparse.FileType('r')) args = parser.parse_args() google_analytics_id = args.google_analytics_id input_file = args.input_file with input_file as csvfile: reader = csv.DictReader(csvfile) for row in reader: client_id = row['client_id'] transaction_id = row['transaction_id'] product_name = row['product_name'] product_price = row['product_price'] product_quantity = row['product_quantity'] transaction_amount = row['transaction_amount'] print(f"client_id:{client_id} transaction_id: {transaction_id} product: {product_name}: {product_price} quantity: {product_quantity} transaction amount: {transaction_amount}") items = [ enhanced_item(product_name, Money(product_price, 'USD'), quantity=product_quantity)] data = enhanced_purchase(transaction_id, items, Money(transaction_amount, 'USD'), '/cart/') report(google_analytics_id, client_id, data) time.sleep(0.1)
def _report(client_id, what, extra_info=None, extra_headers=None): tracking_id = getattr(settings, 'GOOGLE_ANALYTICS_TRACKING_ID', None) if tracking_id and client_id: ga.report(tracking_id, client_id, what, extra_info=extra_info, extra_headers=extra_headers)
def _report_event(client_id, user_agent, tracking_id, **event_kwargs): # without a proper user agent, GA may consider the traffic a bot/crawler (though it may still blacklist us by ip) event_kwargs["extra_headers"] = {"User-Agent": user_agent} try: logger.info("sending ga event: %r", event_kwargs) event = gmp.event(**event_kwargs) gmp.report(tracking_id, client_id, event) except: # noqa logger.exception("failed to report event: %r", event_kwargs)
def gmp_report_event(self, client_id, category, action, label=None, value=None): """Send GMP event.""" tid = self.settings["TID"] gmp.report(tid, client_id, gmp.Event(category, action, label=label, value=value))
def exit_redirect(): rawurl = request.args.get('u', 'https://search.openoil.net') newurl = urllib.parse.unquote(rawurl) # XXX tracking happens here, right? user_id = request.cookies.get('oo_search_user', 'unknown user') ua = app.config.get('GOOGLE_ANALYTICS_UA') view = google_measurement_protocol.PageView(path=request.url, referrer=request.referrer) google_measurement_protocol.report(ua, user_id, view) return redirect(newurl)
def ga_report(tracking_id, client_id, payloads, extra_headers=None, **extra_data): ga.report(tracking_id, client_id, payloads, extra_headers=extra_headers, **extra_data)
def ga_report(tracking_id, client_id, what, extra_info=None, extra_headers=None): ga.report(tracking_id, client_id, what, extra_info=extra_info, extra_headers=extra_headers)
def exit_redirect(): rawurl = request.args.get('u', 'https://search.openoil.net') newurl = urllib.parse.unquote(rawurl) # XXX tracking happens here, right? user_id = request.cookies.get('oo_search_user', 'unknown user') ua = app.config.get('GOOGLE_ANALYTICS_UA') view = google_measurement_protocol.PageView( path=request.url, referrer = request.referrer) google_measurement_protocol.report( ua, user_id, view) return redirect(newurl)
def post(self): payload = json.loads(self.request.body) event = Event('spotlight', payload.get('action', 'unknown')) report('UA-37604830-8', payload.get('user', None), event) """a = Action( user = payload.get('user', None), action = payload.get('action', None) ) a.put()""" self.response.write("okay")
def metrics_event(request): request_data = json.loads(request.body) if 'ga_uuid' not in request_data: return JsonResponse({'msg': 'No GA uuid found'}, status=404) event_data = event( request_data.get('category', None), request_data.get('action', None), request_data.get('label', None), request_data.get('value', None), ) report(settings.GOOGLE_ANALYTICS_ID, request_data.get('ga_uuid'), event_data) return JsonResponse({'msg': 'OK'}, status=200)
def send_analytics(self, cmd_name): """Send event to google analytics.""" os_info = '%s %s' % (platform.system(), platform.release()) info = [ {'av': __version__}, {'an': 'Termius CLI'}, {'ua': os_info}, {'ostype': os_info} ] event = Event('cli', cmd_name) report( self.tracking_id, self.manager.analytics_id, event, extra_info=info )
def main(): parser = argparse.ArgumentParser( description='Send ecommerce transactions to Google Analytics') parser.add_argument('--google-analytics-id', '-g', dest='google_analytics_id', default=None, help='Google Analytics ID') parser.add_argument('--input-file', '-i', type=argparse.FileType('r')) args = parser.parse_args() google_analytics_id = args.google_analytics_id input_file = args.input_file with input_file as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row) client_id = row['userid'] transaction_id = '' product_name = 'Auction Win' product_price = 0 product_quantity = row['Transactions'] raw_transaction_amount = row['Revenue'] transaction_amount = raw_transaction_amount.replace('$', '') cd1 = 'purchase' url = row['Landing Page'] print( f"client_id:{client_id} url: {url} transaction_id: {transaction_id} product: {product_name}: {product_price} quantity: {product_quantity} transaction amount: {transaction_amount} cd1: {cd1}" ) items = [ enhanced_item(product_name, Money(product_price, 'USD'), quantity=product_quantity) ] data = enhanced_purchase(transaction_id, items, Money(transaction_amount, 'USD'), url, cd1=cd1) report(google_analytics_id, client_id, data) time.sleep(0.1)
def test_report(): (response, ) = report('UA-123456-78', 'CID', [{'t': 'mock'}]) data = response.json() assert data == { 'cid': ['CID'], 'tid': ['UA-123456-78'], 'v': ['1'], 'aip': ['1'], 't': ['mock'] }
def metrics_event(request): try: request_data = json.loads(request.body) except json.JSONDecodeError: return JsonResponse({'msg': 'Could not decode JSON'}, status=415) if 'ga_uuid' not in request_data: return JsonResponse({'msg': 'No GA uuid found'}, status=404) event_data = event( request_data.get('category', None), request_data.get('action', None), request_data.get('label', None), request_data.get('value', None), ) try: report(settings.GOOGLE_ANALYTICS_ID, request_data.get('ga_uuid'), event_data) except Exception as e: logger.error('metrics_event', extra={'error': e}) return JsonResponse({'msg': 'Unable to report metrics event.'}, status=500) return JsonResponse({'msg': 'OK'}, status=200)
def dispatch(self, data: Dict): ''' Figures out the right handler to use for reporting and calls it with event data. Returns False if sending any request failed, otherwise True. ''' if data['handler'] == 'ga': if not self.UA: raise ValueError('missing UA') # report offset between now and when we got the event (ms) data['args']['qt'] = str(self.get_ts() - data['ts']) if data['etype'] == 'event': payload = google_measurement_protocol.event(**data['args']) elif data['etype'] == 'pageview': payload = google_measurement_protocol.pageview(**data['args']) else: raise ValueError('unknown etype') # GA appears to ignore its own 'ua' override. # this is silly, but is the recommended solution. user_agent = data['args'].get('ua') if user_agent: extra_headers = {'user-agent': user_agent} else: extra_headers = {} # LOG.debug('payload: {}'.format(list(payload))) # send data (res is list of requests objs) res = google_measurement_protocol.report( self.UA, data['clientid'], payload, extra_headers=extra_headers) if not res: raise ValueError('nothing to send') for req in res: req.raise_for_status() return True else: raise ValueError('unknown handler')
def _trace_ga(action_name, auth_user, client_user, client_token, label): from google_measurement_protocol import Event, report try: username = auth_user or client_user or client_token logger.debug("Auth user / client_user: %s/%s/%s" % (auth_user, client_user, client_token)) logger.debug("Enter analytics with params: %s, %s, %s" % (action_name, username, label)) aes_manager = AESEncryption(BII_AES_SECRET_KEY) client_id = aes_manager.encrypt(username) logger.debug("Client id encoded: %s" % str(client_id)) event = Event('bii_api_call', action_name, label) ret = report(BII_GA_API_KEY, client_id, event) if ret[0].status_code == 200: logger.debug("ANALYTICS: Logged: %s to google analytics" " for visitor %s - %s" % (action_name, username, client_id)) else: logger.debug("Error logging to analytics: %s " % (ret[0].reason)) except Exception as exc: logger.warning("Error sending to action to ga: %s" % (exc))
def ga_report( tracking_id, client_id, payloads, extra_headers=None, **extra_data): ga.report( tracking_id, client_id, payloads, extra_headers=extra_headers, **extra_data)
def test_extra_params(): (response, ) = report('UA-123456-78', 'CID', [{'t': 'mock'}], ex='extra') data = response.json() assert data['ex'] == ['extra']
def _report_event(client_id, **event_kwargs): event = gmp.Event(**event_kwargs) gmp.report(settings.GA_CODE, client_id, event) logger.info("reported event %s: %r", client_id, event_kwargs)
def log_fetch(count, gender): label = GENDERS.get(gender, 'Gender Neutral') client_id = uuid.uuid4() event = Event('API', 'Fetch', label=label, value=count) report('UA-68765997-3', client_id, event)
def analyticsEvent(userid, category, action): event = Event(category,action) r = report(app.config['ANALYTICS_ID'],userid,event) return r
def gmp_report_pageview(self, client_id, path=None, title=None): """Send GMP Pageview.""" tid = self.settings["TID"] gmp.report(tid, client_id, gmp.PageView(path=path, title=title))
def voice_processing(message): data = event('voice', 'send_voice') report(ANALYTICS_TRACKING_ID, ANALYTICS_ACCOUNT_ID, data) duration = message.voice.duration if duration < 5: bot.send_message(message.chat.id, 'The voice message is too short.') elif duration > 30: bot.send_message(message.chat.id, 'The voice message is too long.') else: file_info = bot.get_file(message.voice.file_id) file = bot.download_file(file_info.file_path) my_file_path = f"bot/{file_info.file_path}" with open(my_file_path, 'wb') as f: f.write(file) data = acr.identify(my_file_path) if data['status']['code'] == 0: filename_w_ext = os.path.basename(file_info.file_path) json_filename, file_extension = os.path.splitext(filename_w_ext) with open(f'bot/json/{json_filename}.json', 'w', encoding='utf8') as outfile: json.dump(data, outfile, indent=4, sort_keys=True) artist = data['metadata']['music'][0]['artists'][0]['name'] song = data['metadata']['music'][0]['title'] if check_chinese(artist): bot.send_message(message.chat.id, 'Only English or Russian') else: if song.count(" - ") == 1: song, garbage = song.rsplit(" - ", 1) song = re.sub("[(\[].*?[)\]]", "", song).strip() about = f"{artist} - {song}" bot.send_message(message.chat.id, about) genres = get_genres(data) if genres != 'Classical': send_lyrics(message, artist, song) yid = media(data, 'youtube') if yid is not None: y_link = 'https://www.youtube.com/watch?v=' + yid bot.send_message(message.chat.id, y_link) else: y_link = get_youtube(artist, song) if y_link is not None: bot.send_message(message.chat.id, y_link) else: bot.send_message(message.chat.id, 'this is classical melody') sid = media(data, 'spotify') if sid is not None: s_link = f'https://open.spotify.com/track/{sid}' bot.send_message(message.chat.id, s_link) else: client.captureMessage( f"{artist} - {song} not found in spotify") did = media(data, 'deezer') if did is not None: d_link = f'http://www.deezer.com/track/{str(did)}' r = requests.get(d_link) if r.status_code != 404: bot.send_message(message.chat.id, d_link) else: client.captureMessage( f"{artist} - {song} not found in deezer") else: snf = 'songs not found' bot.send_message(message.chat.id, snf)