Ejemplo n.º 1
1
def parseEventbrite(organizer):
	eventbrite = Eventbrite(config.EVENTBRITE_OAUTH_TOKEN)
	events = eventbrite.event_search(**{'organizer.id': organizer})

	event_list = []
	venues = {}

	for event in events["events"]:
		event_data = {
			"title": event["name"]["text"],
			"start": event["start"]["local"],
			"end": event["end"]["local"],
			"url": event["url"]
		}

		try:
			event_data["description"] = event["description"]["text"]
		except AttributeError:
			pass

		venue_id = event["venue_id"]
		try:
			venue_str = venues[venue_id]
		except KeyError:
			venue = eventbrite.get("/venues/%s" % venue_id)
			venue_str = "%s, %s, %s %s" % (venue["name"], venue["address"]["address_1"], venue["address"]["postal_code"], venue["address"]["city"])
			venues[venue_id] = venue_str

		event_data["location"] = venue_str

		event_list.append(event_data)

	return event_list
Ejemplo n.º 2
0
def get_eventbrite_events():
    """Get events from eventbrite."""
    eb = Eventbrite(config.EVENTBRITE_TOKEN)
    # me = eb.event_search(**{"user.id": eb.get_user()["id"]})
    # print(json.dumps(me))

    has_more = True
    events = []
    while has_more:
        search_results = eb.event_search(
            **{"location.address": "New+York", "location.within": "5mi"}
        )
        has_more = search_results.get("pagination", "").get(
            "has_more_items", False
        )
        for i in search_results.get("events", []):
            events.append(
                {
                    "id": i.get("id"),
                    "name": i.get("name").get("text"),
                    "description": i.get("description").get("text"),
                    "summary": i.get("summary"),
                    "start": i.get("start").get("local"),
                    "end": i.get("end").get("local"),
                    "status": i.get("status"),
                    "url": i.get("url"),
                }
            )

    return search_results["events"]
Ejemplo n.º 3
0
class Event:
    def __init__(self):
        self.eventbrite = Eventbrite(settings.EVENTBRITE_API_KEY)

    def get(self, events_id):
        """
        Given an eventbrite ID, returns the event object

        :param events_id:
        :return:
        """

        data = self.eventbrite.get_event(events_id)
        if data.status_code == 200:
            return data
        else:
            return None

    def get_multiple(self, category_ids, page_number):
        """
        Given a set of categories, returns relevant events
        :param category_ids:
        :param page_number:
        :return:
        """

        data = self.eventbrite.event_search(**{"page": page_number, "categories": category_ids})
        if data.status_code == 200:
            return data
        else:
            return None
Ejemplo n.º 4
0
def parseEventbrite(organizer):
    eventbrite = Eventbrite(config.EVENTBRITE_OAUTH_TOKEN)
    events = eventbrite.event_search(**{'organizer.id': organizer})

    event_list = []
    venues = {}

    for event in events["events"]:
        event_data = {
            "title": event["name"]["text"],
            "start": event["start"]["local"],
            "end": event["end"]["local"],
            "url": event["url"]
        }

        try:
            event_data["description"] = event["description"]["text"]
        except AttributeError:
            pass

        venue_id = event["venue_id"]
        try:
            venue_str = venues[venue_id]
        except KeyError:
            venue = eventbrite.get("/venues/%s" % venue_id)
            venue_str = "%s, %s, %s %s" % (
                venue["name"], venue["address"]["address_1"],
                venue["address"]["postal_code"], venue["address"]["city"])
            venues[venue_id] = venue_str

        event_data["location"] = venue_str

        event_list.append(event_data)

    return event_list
Ejemplo n.º 5
0
 def search_events(self):
   preferences = self.user_preferences
   eventbrite = Eventbrite(self.api_token)
   events = eventbrite.event_search(**{
       'venue.city': preferences.venue_city,
       'price' : preferences.price, 
       'categories' : ",".join(preferences.category_id),
       'start_date.keyword': preferences.start_date_keyword
     })
   list_of_events = []
   for i in events["events"]:
     try:
       list_of_events += [{
         'event_name':i['name']['text'] if len(i['name']['text'])<50 else i['name']['text'][:50]+"...",
         'description':i['description'].get("text","")[:150]+"..." if i['description'].get("text","") != None else "",
         'start':datetime.strptime(i['start']['local'],"%Y-%m-%dT%H:%M:%S").strftime("%a, %d %b, %I:%M %p"),
         'end':datetime.strptime(i['end']['local'],"%Y-%m-%dT%H:%M:%S").strftime("%a, %d %b, %I:%M %p"),
         'url':i['url'],
         'logo':i['logo']['url']
       }]
     except TypeError:
       list_of_events += [{
         'event_name':i['name']['text'] if len(i['name']['text'])<50 else i['name']['text'][:50]+"...",
         'description':i['description'].get("text","")[:150]+"..." if i['description'].get("text","") != None else "",
         'start':datetime.strptime(i['start']['local'],"%Y-%m-%dT%H:%M:%S").strftime("%a, %d %b, %I:%M %p"),
         'end':datetime.strptime(i['end']['local'],"%Y-%m-%dT%H:%M:%S").strftime("%a, %d %b, %I:%M %p"),
         'url':i['url']
       }]
   return list_of_events
Ejemplo n.º 6
0
def get_events():
    eventbrite = Eventbrite(settings.EVENTBRITE_KEY)
    
    # Get my own User ID
    my_id = eventbrite.get_user()['id']
    
    # Get a raw list of events (includes pagination details)
    return eventbrite.event_search(**{'user.id': my_id})
Ejemplo n.º 7
0
def suggestEvents(flightJson, testDate=None):
    eventbrite = Eventbrite('JPFW2R7QDBH4J62PPDO2')

    flight = flightJson
    arrival_airport = flight["segmentReferences"]["arrivalAirport"]
    #print ("arrival airport", arrival_airport)

    if testDate is None:
        date = flight["segmentReferences"]['arrivalDate']
        time = flight["segmentReferences"]['arrivalTime']
        arrival_time = date[:-1] + 'T' + time + ":00"
    else:
        time = flight["segmentReferences"]['arrivalTime']
        arrival_time = testDate[:-1] + 'T' + time + ":00"

    #print (arrival_time)

    end_date = arrival_time[:8] + str(int(arrival_time[8:10]) +
                                      3) + arrival_time[10:]

    #print (end_date)

    airports = pd.read_csv(
        'https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat',
        header=None)
    latitude = airports[airports[4] == arrival_airport][6]
    longitude = airports[airports[4] == arrival_airport][7]

    events = eventbrite.event_search(
        **{
            'sort_by': 'best',
            'location.latitude': latitude,
            'location.longitude': longitude,
            "location.within": "70km",
            "start_date.range_start": arrival_time,
            "start_date.range_end": end_date,
            'high_affinity_categories': 'business'
        })
    #return events

    response = {}

    if type(events) is str:
        return None
    else:
        if len(events['events']) < 3:
            response.append(events['events']['name']['text'])
        else:

            #print ('ffdsfdsf')
            for event_name in events['events'][:3]:

                response[event_name['name']['text']] = event_name['url']
                #response.append(event_name['url'])

        return response
Ejemplo n.º 8
0
    def handle(self, *args, **options):
        "Pull events from Eventbrite and store them in the db as Event instances"
        # https://github.com/eventbrite/eventbrite-sdk-python/blob/master/eventbrite/client.py
        eventbrite = Eventbrite(settings.EVENTBRITE_OAUTH_TOKEN
                                or options.get('token'))
        number_of_events_to_parse = options['number_of_events']
        count = 0
        page = 1
        events = eventbrite.event_search(
            expand='ticket_availability,organizer', page=page)

        while count < number_of_events_to_parse:
            for event in events.get('events'):
                cost = int(
                    (float(event['ticket_availability']['minimum_ticket_price']['major_value']) \
                    + float(event['ticket_availability']['maximum_ticket_price']['major_value'])
                    )/2
                )
                try:
                    # only unique events with values for all fields will be saved
                    Event.objects.create(
                        name=event['name']['text'],
                        organization=event['organizer']['name'],
                        event_original_id=event['id'],
                        start_date=parser.parse(event['start']['local']),
                        cost=cost)
                    count += 1
                except:
                    pass

                if count >= number_of_events_to_parse:
                    break

            if events.get('pagination').get(
                    'has_more_items') and count < number_of_events_to_parse:
                page += 1
                events = eventbrite.event_search(
                    expand='ticket_availability,organizer', page=page)
            else:
                break

        print("\nSaved {} events in the database!\n".format(count))
Ejemplo n.º 9
0
class TestEvents(unittest.TestCase):

    def setUp(self):
        self.eventbrite = Eventbrite(OAUTH_TOKEN)

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(
        condition=skip_integration_tests,
        reason='Needs an OAUTH_TOKEN')
    def test_post_event(self):

        event_name = 'client_test_{0}'.format(datetime.now())

        event_data = {
            'event.name': {
                'html': event_name,
            },
            'event.start': {
                'utc': '2015-03-07T20:00:00Z',
                'timezone': 'America/Los_Angeles',
            },
            'event.end': {
                'utc': '2015-03-07T23:00:00Z',
                'timezone': 'America/Los_Angeles',
            },
            'event.currency': 'USD',
            'event.online_event': True,
            'event.listed': False,
            'event.category_id': '110',
            'event.format_id': '5',
            'event.password': "******",
            'event.capacity': 10,
        }
        event = self.eventbrite.post('/events/', data=event_data)
        self.assertEqual(event_name, event['name']['text'])
        self.assertEqual(event_name, event['name']['html'])
        # Just for access to see the event, not full authentication
        self.assertEqual(event['password'], "test")

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(
        condition=skip_integration_tests, reason='Needs an OAUTH_TOKEN')
    def test_search_events(self):
        data = {
            'location.latitude': '40.4313684',
            'start_date.keyword': 'today',
            'location.longitude': '-79.9805005',
            'location.within': '10km'
        }
        events = self.eventbrite.event_search(**data)
        self.assertLess(events['pagination'][u'object_count'], 1000)
Ejemplo n.º 10
0
    def handle(self, *args, **options):
        eventbrite = Eventbrite(generic_keys.eventbrite_oauth_token)
        # for getting all the events from washington DC
        # **{'venue.city': 'new york'}
        nyc_events = []
        for i in range(2, 500):
            try:
                nyc_events = eventbrite.event_search(**{'page': i})['events']
            except:
                pass
            for line in nyc_events:
                event_name, event_description, event_website, event_image, start_date, start_time, end_date, end_time, event_address, event_faq, phone_number = '', '', '', '', '', '', '', '', '', '', ''
                try:
                    event_name = line['name']['text']
                    event_description = line['description']['text']
                except:
                    pass
                try:
                    event_website = line['url']
                    event_image = line['logo']['url']
                except:
                    pass
                try:
                    start_time = line['start']['local'].split('T')[1]
                    start_date = line['start']['local'].split('T')[0]
                    end_time = line['end']['local'].split('T')[1]
                    end_date = line['end']['local'].split('T')[0]
                except:
                    pass
                try:
                    event_address = eventbrite.get('/venues/{}/'.format(
                        line['venue_id']))['address']['address_1']
                except Exception as e:
                    print e

                try:
                    Activity.objects.create(
                        event_name=event_name,
                        event_location=event_address,
                        event_address=event_address,
                        event_website=event_website,
                        event_description=event_description,
                        event_image=event_image,
                        start_time=start_time,
                        end_time=end_time,
                        start_date=start_date,
                        end_date=end_date,
                        event_faq=event_faq)
                except Exception as e:
                    print e
Ejemplo n.º 11
0
class TestEvents(unittest.TestCase):
    def setUp(self):
        self.eventbrite = Eventbrite(OAUTH_TOKEN)

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_post_event(self):

        event_name = 'client_test_{0}'.format(datetime.now())

        event_data = {
            'event.name': {
                'html': event_name,
            },
            'event.start': {
                'utc': '2015-03-07T20:00:00Z',
                'timezone': 'America/Los_Angeles',
            },
            'event.end': {
                'utc': '2015-03-07T23:00:00Z',
                'timezone': 'America/Los_Angeles',
            },
            'event.currency': 'USD',
            'event.online_event': True,
            'event.listed': False,
            'event.category_id': '110',
            'event.format_id': '5',
            'event.password': "******",
            'event.capacity': 10,
        }
        event = self.eventbrite.post('/events/', data=event_data)
        self.assertEqual(event_name, event['name']['text'])
        self.assertEqual(event_name, event['name']['html'])
        # Just for access to see the event, not full authentication
        self.assertEqual(event['password'], "test")

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_search_events(self):
        data = {
            'location.latitude': '40.4313684',
            'start_date.keyword': 'today',
            'location.longitude': '-79.9805005',
            'location.within': '10km'
        }
        events = self.eventbrite.event_search(**data)
        self.assertLess(events['pagination'][u'object_count'], 1000)
Ejemplo n.º 12
0
def tod_events(search_args, category, am_end, pm_st):
    eventbrite = Eventbrite(keys["eventbrite_key"])
    events = eventbrite.event_search(**search_args)
    ## Use this for filtering
#     events = [x for x in events['events'] if x['category_id'] == "103"]

    events = [x for x in events['events']]

    for item in events:
        location_id = eventbrite.get('/venues/' + str(item['venue_id']))
        item.update( {"latitude": location_id['latitude']})
        item.update( {"longitude": location_id['longitude']})
        item.update( {"address": location_id['address']})

    return events
Ejemplo n.º 13
0
def show_events_view(request):
    eventbrite = Eventbrite(eventtoken)
    my_id = eventbrite.get_user()['id']
    events = eventbrite.event_search(**{'user.id': my_id})
    existing_events = Event.objects.all().values("event_id")
    events_list = []
    for i in existing_events:
        events_list.append(i['event_id'])

    for x in events['events']:
        event_id = (x['id'])

        if event_id in events_list:
            pass
        else:
            start_time = parse_datetime(x['start']['local'])
            api_url = (x['url'])
            event_id = (x['id'])
            event_url = (x['url'])
            title = (x['name']['html'])
            name_code = title[4:7].lower()
            if name_code == "cor":
                code = "core"
            elif name_code == "int":
                code = "inter"
            elif name_code == "hig":
                code = "higher"

            else:
                code = "other"
            print(event_id)

            print(start_time)
            new_event = Event(api_url=api_url,
                              event_start=start_time,
                              title=title,
                              event_url=api_url,
                              event_code=code,
                              event_id=event_id)
            print(new_event)
            new_event.save()

    context = {}

    return render(request, 'showevents.html', context)
Ejemplo n.º 14
0
def get_event_results(q, datestring):

    datestring = datetime.strptime(datestring, "%m/%d/%Y")
    datestring = datetime.strftime(datestring, "%Y-%m-%d")
    client = Eventbrite(auth_key)

    
    start_date = datestring+"T01:00:00"
    end_date = datestring+"T23:55:00"
    popular = True
    sort_by = "best"
    categories ="103,110"
    # expand = "https://www.eventbriteapi.com/v3/events/search/?location.address=Indore&expand=organizer,venue&token=JXPOFPSSCU4OQGRAG5RH"
    params = {"q": q, "start_date.range_start": start_date, 
              "start_date.range_end": end_date, "sort_by": sort_by, "popular": popular, "categories": categories, 'expand': 'venue'}
    search_response = client.event_search(**params)
    events = search_response.get('events', [])
    rendered_responses = []
    
    for event in events:
        if event.get('logo'):
            image_url = event['logo']['url']
        else:
            image_url = None
        rendered_responses.append({'name': event['name']['html'],
                                    'start': datetime.strptime(event['start']['local'], ('%Y-%m-%dT%H:%M:%S')),
                                    'status': event['status'],
                                    'url': event['url'], 
                                    'locale': event['locale'],
                                    'id': event['id'],
                                    'description': event['description']['text'],
                                    'image':image_url,
                                    'venue': event['venue']['address'],
                                    'latitude': event['venue']['latitude'],
                                    'longitude': event['venue']['longitude']})

    pprint.pprint(rendered_responses)
    return rendered_responses
Ejemplo n.º 15
0
    def handle(self, *args, **options):
        eventbrite = Eventbrite(generic_keys.eventbrite_oauth_token)
        # for getting all the events from washington DC
        # **{'venue.city': 'new york'}
        nyc_events = []
        for i in range(2, 500):
            try:
                nyc_events = eventbrite.event_search(**{'page': i})['events']
            except:
                pass
            for line in nyc_events:
                event_name, event_description, event_website, event_image, start_date, start_time, end_date, end_time, event_address, event_faq, phone_number = '', '', '', '', '', '', '', '', '', '', ''
                try:
                    event_name = line['name']['text']
                    event_description = line['description']['text']
                except:
                    pass
                try:
                    event_website = line['url']
                    event_image = line['logo']['url']
                except:
                    pass
                try:
                    start_time = line['start']['local'].split('T')[1]
                    start_date = line['start']['local'].split('T')[0]
                    end_time = line['end']['local'].split('T')[1]
                    end_date = line['end']['local'].split('T')[0]
                except:
                    pass
                try:
                    event_address = eventbrite.get('/venues/{}/'.format(line['venue_id']))['address']['address_1']
                except Exception as e:
                    print e

                try:
                    Activity.objects.create(event_name=event_name, event_location=event_address, event_address=event_address, event_website=event_website, event_description=event_description, event_image=event_image, start_time=start_time, end_time=end_time, start_date=start_date, end_date=end_date, event_faq=event_faq)
                except Exception as e:
                    print e
Ejemplo n.º 16
0
def get_recommendation(desired_time):
    # GET EVENT RECOMMENDATION FROM EVENTBRITE

    # GET EVENTBRITE API KEY
    eventbrite_api_key = get_key('EVENTBRITE_TOKEN')
    eventbrite = Eventbrite(eventbrite_api_key)

    # GET ADDRESS FROM HOTEL NAME (GOOGLEMAPS)
    google_api_key = get_key('GOOGLE')
    gmaps = googlemaps.Client(key=google_api_key)
    places_result = gmaps.places(query=session.attributes['hotel'])
    hotel_address = [e['formatted_address'] for e in places_result['results']]

    # GET CATEGORY ID FROM CATEGORY NAME
    address = hotel_address
    category_input = 'Music'
    subcategory_input = session.attributes['music_cat_id']
    location_radius = '10mi'
    event_timing = desired_time
    categoryquery = eventbrite.get_categories()

    category_name = [c['name'] for c in categoryquery['categories']]
    category_ids = [c['id'] for c in categoryquery['categories']]
    categories = zip(category_name, category_ids)

    category_id = None
    for x in categories:
        if x[0] == category_input:
            category_id = x[1]

    # GET SUBCATEGORY ID FROM CATEGORY ID
    #subcategoryquery = eventbrite.get_subcategories()

    #subcategory_name = [c['name'] for c in subcategoryquery['subcategories']]
    #subcategory_ids = [c['id'] for c in subcategoryquery['subcategories']]
    #subcategories = zip(subcategory_name, subcategory_ids)

    subcategory_id = subcategory_input
    #for x in subcategories:
        #if x[0] == subcategory_input:
            #subcategory_id = x[1]

    # GET LIST OF EVENTS
    eventquery = eventbrite.event_search(**{'location.address': address,
                                            'categories': category_id,
                                            'subcategories': subcategory_id,
                                            'location.within': location_radius,
                                            'start_date.keyword': event_timing})

    eventnames = [e['name']['text'] for e in eventquery['events']]
    if not eventnames:
        return False
    event1 = eventnames[0]

    eventdescr = [e['description']['text'] for e in eventquery['events']]
    descr1 = eventdescr[0]

    # COLLECT ADDITIONAL INFO FOR FILES
    #eventdescr2 = []
    #for i in eventdescr:
        #if i is None:
            #eventdescr2.append("")
        #eventdescr2.append(((i.replace("\n", " ")).replace("\r", " "))[0:30])

    eventlogo = []
    for e in eventquery['events']:
        eventlogo.append(e['logo']['original']['url'] if e['logo'] else '')
    logo1 = eventlogo[0]

    eventkeys = []
    for i in eventnames:
        eventkeys.append(('event-' + i).replace(" ", "-"))

    eventlist = zip(eventkeys, eventnames, eventnames, eventlogo)

    eventstart = [l['local']
                  for l in (e['start'] for e in eventquery['events'])]
    start1 = eventstart[0]

    eventend = [l['local'] for l in (e['end'] for e in eventquery['events'])]
    end1 = eventend[0]

    eventvenue = [v['venue_id'] for v in eventquery['events']]
    venue1 = eventvenue[0]
    venuequery = eventbrite.get('/venues/{0}'.format(venue1))
    venue_list = venuequery['address']['localized_multi_line_address_display']
    venue_string = " ".join(str(x) for x in venue_list)

    eventurl = [u['url'] for u in eventquery['events']]
    url1 = eventurl[0]

    # CREATE EVENT TERMS

    eventterms = []
    for i in eventnames:
        eventterms.append((((category_input + '__' + session.attributes['music_cat']).replace(" ", "_")).replace("/", "and")).lower())

    termfile = zip(eventkeys, eventterms)
    with get_connection() as conn:
        with conn.cursor() as cursor:
            cursor.executemany("""
                INSERT INTO products (id, name, description, image_link)
                VALUES (%s, %s, %s, %s)
                """, eventlist)
            cursor.executemany("""
                INSERT INTO terms (event_key, event_term) VALUES (%s, %s)
                """, termfile)
    conn.close()

    # TEXT EVENT DETAILS

    account_sid = get_key('TWILIO_SID')
    auth_token = get_key('TWILIO_TOKEN')

    client = twilio.rest.Client(account_sid, auth_token)

    phone_number = session.attributes['phone_number']
    client.messages.create(
        to=phone_number,
        from_=get_key('TWILIO_PHONE'),
        body="Your IHG Concierge has sent you an event you may enjoy: " +
             '\n' + event1 + '\n' + descr1[:800] + '\n' + "Start Time: " +
             start1 + '\n' + "End Time: " + end1 + '\n' + "Venue: " +
             venue_string + '\n' + url1,
        media_url=logo1 if phone_number.startswith('+1') else None)

    return eventnames[0]
Ejemplo n.º 17
0
    def get_events(self):
        """
        Queries Eventful, LastFM, and Eventbrite APIs and returns events
        within an area based on geo parameters
        """

        # Datetime format for event start date/time
        datetime_format = '%b %d, %Y -- %I:%M %p'

        lst_events = []

        ###  -----  Eventful  -----   ###

        # Queries Eventful API and returns events within an area based on geo
        # parameters. Exception handling to prevent error in case no events
        # are found.
        api = eventful.API(Eventful_Key)
        try:
            eventful_events = api.call('/events/search',
                                       location=(str(self.latitude) + ',' +
                                                 str(self.longitude)),
                                       within=self.miles,
                                       sort_order="date")
        except:
            eventful_events = dict({'events': None})

        # Appends Eventful event details to 'lst_events' list. Two different
        # 'For Loops' are used because if only one event is found, it is returned
        # as a dict, otherwise it is returned as a list
        if eventful_events['events'] != None:
            if isinstance(eventful_events['events']['event'], list):
                for event in eventful_events['events']['event']:
                    tmp_event = []
                    tmp_time = []
                    tmp_event.append(event['title'][:35])
                    tmp_event.append(event['venue_name'][:20])
                    # converts datetime format
                    tmp_time = event['start_time']
                    tmp_time_adj = datetime.strptime(
                        tmp_time,
                        '%Y-%m-%d %H:%M:%S').strftime(datetime_format)
                    tmp_event.append(tmp_time_adj)
                    tmp_event.append(event['url'])
                    lst_events.append(tmp_event)

            elif isinstance(eventful_events['events']['event'], dict):
                tmp_event = []
                tmp_time = []
                tmp_event.append(
                    eventful_events['events']['event']['title'][:35])
                tmp_event.append(
                    eventful_events['events']['event']['venue_name'][:20])
                tmp_time = eventful_events['events']['event']['start_time']
                # converts datetime format
                tmp_time_adj = datetime.strptime(
                    tmp_time, '%Y-%m-%d %H:%M:%S').strftime(datetime_format)
                tmp_event.append(tmp_time_adj)
                tmp_event.append(eventful_events['events']['event']['url'])
                lst_events.append(tmp_event)

        ###  -----  LastFM  -----   ###

        # Queries LastFM API and returns events within an area based on geo
        # parameters. Exception handling to prevent error in case no events
        # are found.
        network = pylast.LastFMNetwork(api_key=Last_fm_Key,
                                       api_secret=Last_fm_Secret)
        try:
            lastfm_events = network.get_geo_events(longitude=self.longitude,
                                                   latitude=self.latitude,
                                                   distance=self.miles)
        except:
            lastfm_events = []

        # Appends LastFM event details to 'lst_events' list. Exception handling
        # in case no events are found or etracting certain event details creates
        # an error
        for i in range(len(lastfm_events)):
            try:
                tmp_event = []
                tmp_time = []
                tmp_event.append(lastfm_events[i].get_title())
                tmp_event.append(lastfm_events[i].get_venue().get_name())
                # converts datetime format
                tmp_time = lastfm_events[i].get_start_date()
                tmp_time_adj = datetime.strptime(
                    tmp_time,
                    '%a, %d %b %Y %H:%M:%S').strftime(datetime_format)
                tmp_event.append(tmp_time_adj)
                tmp_event.append(lastfm_events[i].get_url())
                lst_events.append(tmp_event)
            except:
                continue

        ###  -----  Eventbrite  -----   ###

        # Queries Eventbrite API and returns events within an area based on geo
        # parameters.
        eventbrite = Eventbrite(Eventbrite_API)
        # Eventbrite API requires radius ('within' param) to be integer
        # not less than 1.
        eventbrite_within = max('1', str(int(float(self.miles))))
        eventbrite_events = eventbrite.event_search(
            **{
                'location.within': eventbrite_within + "mi",
                'location.latitude': str(self.latitude),
                'location.longitude': str(self.longitude),
                'popular': 'true',
                'sort_by': 'date'
            })

        # Appends Eventbrite event details to 'lst_events' list. Exception handling
        # in case no events are found or extracting certain event details creates
        # an error
        for i in range(len(eventbrite_events)):
            try:
                tmp_event = []
                tmp_time = []
                tmp_event.append(
                    eventbrite_events['events'][i]['name']['text'][:35])
                tmp_event.append(
                    eventbrite_events['events'][i]['venue']['name'][:20])
                # converts datetime format
                tmp_time = eventbrite_events['events'][i]['start']['local']
                tmp_time_adj = datetime.strptime(
                    tmp_time, '%Y-%m-%dT%H:%M:%S').strftime(datetime_format)
                tmp_event.append(tmp_time_adj)
                tmp_event.append(eventbrite_events['events'][i]['url'])
                lst_events.append(tmp_event)
            except:
                continue

        # Events in lst_events are sorted by chronological order
        return sorted(lst_events,
                      key=lambda x: datetime.strptime(x[-2], datetime_format))


# x = GlocalAPI("1500 Massachusetts Ave NW", "washington","dc","1" )
# # # # x.get_instagram()
# x.get_events()
# # # # # y = GlocalAPI("","Sanaa","Yemen","10")
# # # y.get_events()
# # z = GlocalAPI("42 mar elias street","al-mina, tripoli", "lebanon","5")
# z.get_events()
def retrieve_events_for_states(us_states, oauth_token):
    for us_state in us_states:
        print(us_state)

        db = mysql.connect(host=config['mysql']['host'],
                           user=config['mysql']['user'],
                           passwd=config['mysql']['pass'],
                           database="state_of_music")

        cursor = db.cursor()

        eventbrite = Eventbrite(oauth_token)

        params = {
            'categories': categories,
            'formats': formats,
            'location.viewport.northeast.latitude': us_state[4],
            'location.viewport.northeast.longitude': us_state[3],
            'location.viewport.southwest.latitude': us_state[2],
            'location.viewport.southwest.longitude': us_state[1],
            'start_date.range_start': start_date,
            'start_date.range_end': end_date
        }

        events_response = eventbrite.event_search(**params)

        try:
            total_events = events_response['pagination']['object_count']
        except KeyError:
            eb_list = token_swap(oauth_token)
            oauth_token = eb_list[0]
            eventbrite = eb_list[1]
            events_response = eventbrite.event_search(**params)
            total_events = events_response['pagination']['object_count']

        pages_list = [
            1
        ] if events_response['pagination']['page_count'] == 1 else list(
            range(1, events_response['pagination']['page_count'] + 1))

        if total_events > 0:
            for page in pages_list:
                params = {
                    'categories': categories,
                    'formats': formats,
                    'location.viewport.northeast.latitude': us_state[4],
                    'location.viewport.northeast.longitude': us_state[3],
                    'location.viewport.southwest.latitude': us_state[2],
                    'location.viewport.southwest.longitude': us_state[1],
                    'start_date.range_start': start_date,
                    'start_date.range_end': end_date,
                    'page': page
                }

                events_response = eventbrite.event_search(**params)

                try:
                    events = events_response['events']
                except KeyError:
                    eb_list = token_swap(oauth_token)
                    oauth_token = eb_list[0]
                    eventbrite = eb_list[1]
                    events_response = eventbrite.event_search(**params)
                    events = events_response['events']

                for event in events:
                    event_id = event['id']
                    event_name = event['name']['text']
                    if (len(event_name) > 100):
                        event_name = event_name[0:99]
                    event_date = event['start']['local']
                    venue_id = event['venue_id']
                    subcategory_id = event['subcategory_id']

                    venue_url = '/venues/' + venue_id
                    venue_response = eventbrite.get(venue_url)
                    try:
                        venue_name = venue_response['name']
                    except KeyError:
                        eb_list = token_swap(oauth_token)
                        oauth_token = eb_list[0]
                        eventbrite = eb_list[1]
                        venue_response = eventbrite.get(venue_url)
                        venue_name = venue_response['name']

                    if (venue_name and len(venue_name) > 50):
                        venue_name = venue_name[0:49]
                    venue_lat = venue_response['latitude']
                    venue_long = venue_response['longitude']

                    if subcategory_id:
                        subcategory_url = '/subcategories/' + subcategory_id
                        subcategory_response = eventbrite.get(subcategory_url)
                        try:
                            subcategory_name = subcategory_response['name']
                        except KeyError:
                            eb_list = token_swap(oauth_token)
                            oauth_token = eb_list[0]
                            eventbrite = eb_list[1]
                            subcategory_response = eventbrite.get(
                                subcategory_url)
                            subcategory_name = subcategory_response['name']
                    else:
                        subcategory_name = ''

                    event_exists_query = """SELECT eventbrite_id
                                            FROM eventbrite_events
                                            WHERE eventbrite_id =
                                            '""" + event_id + "'"

                    cursor.execute(event_exists_query)
                    existing_event = cursor.fetchall()

                    if (not len(existing_event)):
                        query = """INSERT INTO eventbrite_events
                                (eventbrite_id, local_date, event_name,
                                venue_name, venue_lat, venue_long, genre)
                                VALUES (%s, %s, %s, %s, %s, %s, %s)"""
                        values = (event_id, event_date, event_name, venue_name,
                                  venue_lat, venue_long, subcategory_name)

                        cursor.execute(query, values)
                        db.commit()
        db.close()
Ejemplo n.º 19
0
class TestEvents(unittest.TestCase):
    def setUp(self):
        self.eventbrite = Eventbrite(OAUTH_TOKEN)

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_post_event(self):
        event_name = 'client_test_{0}'.format(datetime.now())
        event_data = self._get_event_data(event_name)
        event = self.eventbrite.post_event(event_data)
        self.assertEqual(event_name, event['name']['text'])
        self.assertEqual(event_name, event['name']['html'])
        # Just for access to see the event, not full authentication
        self.assertEqual(event['password'], "test")

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_search_events(self):
        data = {
            'location.latitude': '40.4313684',
            'start_date.keyword': 'today',
            'location.longitude': '-79.9805005',
            'location.within': '10km'
        }
        events = self.eventbrite.event_search(**data)
        self.assertLess(events['pagination'][u'object_count'], 1000)

    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_publish_unpublish_event(self):
        """ First, creat a draft event """
        event_data = self._get_event_data()
        event = self.eventbrite.post_event(event_data)
        self.assertTrue(event.ok, msg=event.get('error_description', None))
        """ Next, create a ticket class for the event, because an event
            can't be published without one """
        ticket_data = self._get_ticket_data()
        response = self.eventbrite.post_event_ticket_class(event['id'],
                                                           data=ticket_data)
        """Finally, try to publish the event"""
        response = self.eventbrite.publish_event(event['id'])
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))
        """Now try to unpublish the event"""
        response = self.eventbrite.unpublish_event(event['id'])
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))

    @unittest.skipIf(condition=skip_integration_tests,
                     reason='Needs an OAUTH_TOKEN')
    def test_create_ticket_class(self):

        event_data = self._get_event_data()
        event = self.eventbrite.post_event(event_data)

        ticket_data = self._get_ticket_data()
        response = self.eventbrite.post_event_ticket_class(event['id'],
                                                           data=ticket_data)
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))

    def _get_ticket_data(self):

        return {
            'ticket_class.name':
            'client_test_ticket_{0}'.format(datetime.now()),
            'ticket_class.description': 'Python API Client testing',
            'ticket_class.quantity_total': 100,
            'ticket_class.cost': 'USD,4500'
        }

    def _get_event_data(self,
                        event_name='client_test_{0}'.format(datetime.now())):
        """ Returns a dictionary representing a valid event """

        # if not event_name:
        #     event_name = 'client_test_{0}'.format(datetime.now())

        return {
            'event.name': {
                'html': event_name,
            },
            'event.start': {
                'utc':
                (datetime.now() + timedelta(days=1)).strftime(EB_ISO_FORMAT),
                'timezone': 'America/Los_Angeles',
            },
            'event.end': {
                'utc': (datetime.now() +
                        timedelta(days=1, hours=1)).strftime(EB_ISO_FORMAT),
                'timezone':
                'America/Los_Angeles',
            },
            'event.currency': 'USD',
            'event.online_event': True,
            'event.listed': False,
            'event.category_id': '110',
            'event.format_id': '5',
            'event.password': "******",
            'event.capacity': 10,
        }
Ejemplo n.º 20
0
search_location = '00000'  # Replace with zip code or postal code
search_radius = '20km'  # The search radius around the location to search for listed events

EVENTBRITE_TOKEN = 'MY_EVENTBRITE_TOKEN'
SENDGRID_API_KEY = 'MY_SENDGRID_API_KEY'

# No need to edit below this line
eventbrite = Eventbrite(EVENTBRITE_TOKEN)
sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

# Alternatively, use a stored environment variable
#sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))

# Get a raw list of events (includes pagination details)
results = eventbrite.event_search(**{'q': search_term,\
                                     'location.address': search_location,\
                                     'location.within': search_radius})

# See what attributes you can pass to the event_search method at
# https://www.eventbrite.com/developer/v3/endpoints/events/#ebapi-get-events-search
#
# Eventbrite SDK for Python
# http://eventbrite-sdk-python.readthedocs.io/en/latest/cookbook.html

# Perform a search. If nothing found, exit.
try:
    events = results['events']
except:
    sys.exit(results)

start_time_fmt = '%A, %d %B %Y, %I:%M %p'
Ejemplo n.º 21
0
class TestEvents(unittest.TestCase):

    def setUp(self):
        self.eventbrite = Eventbrite(OAUTH_TOKEN)

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(
        condition=skip_integration_tests,
        reason='Needs an OAUTH_TOKEN')
    def test_post_event(self):
        event_name = 'client_test_{0}'.format(datetime.now())
        event_data = self._get_event_data(event_name)
        event = self.eventbrite.post_event(event_data)
        self.assertEqual(event_name, event['name']['text'])
        self.assertEqual(event_name, event['name']['html'])
        # Just for access to see the event, not full authentication
        self.assertEqual(event['password'], "test")

    @unittest.skipIf(condition=skip_user_id_tests, reason='Needs a USER_ID')
    @unittest.skipIf(
        condition=skip_integration_tests, reason='Needs an OAUTH_TOKEN')
    def test_search_events(self):
        data = {
            'location.latitude': '40.4313684',
            'start_date.keyword': 'today',
            'location.longitude': '-79.9805005',
            'location.within': '10km'
        }
        events = self.eventbrite.event_search(**data)
        self.assertLess(events['pagination'][u'object_count'], 1000)

    @unittest.skipIf(
        condition=skip_integration_tests, reason='Needs an OAUTH_TOKEN')
    def test_publish_unpublish_event(self):

        """ First, creat a draft event """
        event_data = self._get_event_data()
        event = self.eventbrite.post_event(event_data)
        self.assertTrue(event.ok,
                        msg=event.get('error_description', None))

        """ Next, create a ticket class for the event, because an event
            can't be published without one """
        ticket_data = self._get_ticket_data()
        response = self.eventbrite.post_event_ticket_class(event['id'],
                                                           data=ticket_data)

        """Finally, try to publish the event"""
        response = self.eventbrite.publish_event(event['id'])
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))

        """Now try to unpublish the event"""
        response = self.eventbrite.unpublish_event(event['id'])
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))

    @unittest.skipIf(
        condition=skip_integration_tests, reason='Needs an OAUTH_TOKEN')
    def test_create_ticket_class(self):

        event_data = self._get_event_data()
        event = self.eventbrite.post_event(event_data)

        ticket_data = self._get_ticket_data()
        response = self.eventbrite.post_event_ticket_class(event['id'],
                                                           data=ticket_data)
        self.assertTrue(response.ok,
                        msg=response.get('error_description', None))

    def _get_ticket_data(self):

        return {
            'ticket_class.name': 'client_test_ticket_{0}'.format(datetime.now()),
            'ticket_class.description': 'Python API Client testing',
            'ticket_class.quantity_total': 100,
            'ticket_class.cost': 'USD,4500'
        }

    def _get_event_data(self, event_name='client_test_{0}'.format(datetime.now())):
        """ Returns a dictionary representing a valid event """

        # if not event_name:
        #     event_name = 'client_test_{0}'.format(datetime.now())

        return {
            'event.name': {
                'html': event_name,
            },
            'event.start': {
                'utc': (datetime.now() + timedelta(days=1)).strftime(EB_ISO_FORMAT),
                'timezone': 'America/Los_Angeles',
            },
            'event.end': {
                'utc': (datetime.now() + timedelta(days=1,hours=1)).strftime(EB_ISO_FORMAT),
                'timezone': 'America/Los_Angeles',
            },
            'event.currency': 'USD',
            'event.online_event': True,
            'event.listed': False,
            'event.category_id': '110',
            'event.format_id': '5',
            'event.password': "******",
            'event.capacity': 10,
        }
Ejemplo n.º 22
0
#=====================

#import requests
#import json
#from config import MailChimpConfig

#=====================
# Get the current date
#=====================settings
today = time.strftime("%Y-%m-%d")
print(time.strftime("%Y-%m-%d"))

#===============================
# Get all of my event id numbers
#===============================
events = eventbrite.event_search(**{'user.id': my_id})

# HOW many events are there
total_events = events['pagination']['object_count']
print(total_events)

#print(events['events'])
# For the total number of events return an array of their id numbers -(Add later if too many people)(If the events are still live)
eventid = []

for x in range(0, total_events - 1):
    print(x)
    eventid.append(events['events'][x]['id'])
    print(eventid[x])
#=============================
# For each event get all eventbrite attendees