Ejemplo n.º 1
0
def test_required_params():
    generator = event('category', 'action')
    assert list(generator) == [{
        't': 'event',
        'ec': 'category',
        'ea': 'action'
    }]
Ejemplo n.º 2
0
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!")
Ejemplo n.º 3
0
def test_extra_params():
    generator = event('category', 'action', ex='extra')
    assert list(generator) == [{
        't': 'event',
        'ec': 'category',
        'ea': 'action',
        'ex': 'extra'
    }]
Ejemplo n.º 4
0
def test_optional_params():
    generator = event('category', 'action', label='label', value=7)
    assert list(generator) == [{
        't': 'event',
        'ec': 'category',
        'ea': 'action',
        'el': 'label',
        'ev': '7'
    }]
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
    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')
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
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)
def test_required_params():
    generator = event('category', 'action')
    assert list(generator) == [{'t': 'event', 'ec': 'category', 'ea': 'action'}]
def test_extra_params():
    generator = event('category', 'action', ex='extra')
    assert list(generator) == [
        {'t': 'event', 'ec': 'category', 'ea': 'action', 'ex': 'extra'}]
def test_optional_params():
    generator = event('category', 'action', label='label', value=7)
    assert list(generator) == [
        {
            't': 'event', 'ec': 'category', 'ea': 'action', 'el': 'label',
            'ev': '7'}]