Creazione eventi

Immagina un'app che aiuti gli utenti a trovare i migliori percorsi di trekking. Aggiungendo il parametro un'escursione come un evento nel calendario, gli utenti ricevono un grande aiuto per organizzati automaticamente. Google Calendar le aiuta a condividere il piano li ricorda in modo che possano prepararsi senza stress. Inoltre, grazie a un'integrazione perfetta dei prodotti Google, Google Now invia un ping all'orario devono uscire e Google Maps li indirizzerà in tempo al punto dell'incontro.

Questo articolo spiega come creare eventi di calendario e aggiungerli ai tuoi utenti calendari.

Aggiungi un evento

Per creare un evento, chiama il metodo Metodo events.insert() che fornisce al almeno questi parametri:

  • calendarId è l'identificatore del calendario e può essere l'indirizzo email del calendario in cui creare l'evento o una parola chiave speciale 'primary' che utilizzerà il calendario principale dell'utente che ha eseguito l'accesso. Se non conosci l'indirizzo email del calendario che desideri utilizzare, puoi verificarlo nelle impostazioni del calendario in Google Calendar sul web UI (nella sezione "Indirizzo calendario") oppure puoi cercarlo nel risultato calendarList.list() chiamata.
  • event è l'evento da creare con tutti i dettagli necessari, come l'inizio e alla fine. Gli unici due campi obbligatori sono start e end. Consulta le Riferimento event per l'insieme completo dell'evento campi.

Per creare correttamente gli eventi, devi:

  • Imposta l'ambito OAuth su https://www.googleapis.com/auth/calendar in modo che disponi dell'accesso in modifica al calendario dell'utente.
  • Assicurati che l'utente autenticato disponga dell'accesso in scrittura al calendario con calendarId che hai fornito (ad esempio chiamando calendarList.get() per calendarId e controllo accessRole).

Aggiungi metadati dell'evento

Se vuoi, puoi aggiungere metadati evento quando crei un evento nel calendario. Se scegliere di non aggiungere metadati durante la creazione, puoi aggiornare molti campi utilizzando events.update(); ma alcuni campi come l'ID evento, possono essere impostati solo durante Operazione events.insert().

Località

L'aggiunta di un indirizzo nel campo della località attiva funzionalità come

"è ora di partire" o mostrare una mappa con le indicazioni stradali.

ID evento

Quando crei un evento, puoi scegliere di generare un ID evento personalizzato

conformi ai nostri requisiti per il formato. In questo modo puoi mantenere le entità nel tuo database locale sincronizzato con gli eventi di Google Calendar. Inoltre, impedisce la creazione di eventi duplicati se l'operazione non riesce in un determinato momento dopo viene eseguita correttamente nel backend di Calendar. In caso contrario che viene fornito, il server ne genera uno per te. Controlla l'ID evento riferimento per ulteriori informazioni.

Partecipanti

L'evento che crei appare in tutti i calendari Google principali di

i partecipanti che hai incluso con lo stesso ID evento. Se imposti sendNotifications a true sulla tua richiesta di inserimento, i partecipanti ricevere anche una notifica via email per il tuo evento. Vedi gli eventi con la guida alla presenza di più partecipanti per ulteriori informazioni.

I seguenti esempi mostrano la creazione di un evento e l'impostazione dei relativi metadati:

Vai

// Refer to the Go quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/go
// Change the scope to calendar.CalendarScope and delete any stored credentials.

event := &calendar.Event{
  Summary: "Google I/O 2015",
  Location: "800 Howard St., San Francisco, CA 94103",
  Description: "A chance to hear more about Google's developer products.",
  Start: &calendar.EventDateTime{
    DateTime: "2015-05-28T09:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  End: &calendar.EventDateTime{
    DateTime: "2015-05-28T17:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  Recurrence: []string{"RRULE:FREQ=DAILY;COUNT=2"},
  Attendees: []*calendar.EventAttendee{
    &calendar.EventAttendee{Email:"lpage@example.com"},
    &calendar.EventAttendee{Email:"sbrin@example.com"},
  },
}

calendarId := "primary"
event, err = srv.Events.Insert(calendarId, event).Do()
if err != nil {
  log.Fatalf("Unable to create event. %v\n", err)
}
fmt.Printf("Event created: %s\n", event.HtmlLink)

Java

// Refer to the Java quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/java
// Change the scope to CalendarScopes.CALENDAR and delete any stored
// credentials.

Event event = new Event()
    .setSummary("Google I/O 2015")
    .setLocation("800 Howard St., San Francisco, CA 94103")
    .setDescription("A chance to hear more about Google's developer products.");

DateTime startDateTime = new DateTime("2015-05-28T09:00:00-07:00");
EventDateTime start = new EventDateTime()
    .setDateTime(startDateTime)
    .setTimeZone("America/Los_Angeles");
event.setStart(start);

DateTime endDateTime = new DateTime("2015-05-28T17:00:00-07:00");
EventDateTime end = new EventDateTime()
    .setDateTime(endDateTime)
    .setTimeZone("America/Los_Angeles");
event.setEnd(end);

String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));

EventAttendee[] attendees = new EventAttendee[] {
    new EventAttendee().setEmail("lpage@example.com"),
    new EventAttendee().setEmail("sbrin@example.com"),
};
event.setAttendees(Arrays.asList(attendees));

EventReminder[] reminderOverrides = new EventReminder[] {
    new EventReminder().setMethod("email").setMinutes(24 * 60),
    new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
    .setUseDefault(false)
    .setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);

String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());

JavaScript

// Refer to the JavaScript quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/js
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'}
  ],
  'reminders': {
    'useDefault': false,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10}
    ]
  }
};

const request = gapi.client.calendar.events.insert({
  'calendarId': 'primary',
  'resource': event
});

request.execute(function(event) {
  appendPre('Event created: ' + event.htmlLink);
});

Node.js

// Refer to the Node.js quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/node
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'},
  ],
  'reminders': {
    'useDefault': false,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10},
    ],
  },
};

calendar.events.insert({
  auth: auth,
  calendarId: 'primary',
  resource: event,
}, function(err, event) {
  if (err) {
    console.log('There was an error contacting the Calendar service: ' + err);
    return;
  }
  console.log('Event created: %s', event.htmlLink);
});

PHP

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
  'location' => '800 Howard St., San Francisco, CA 94103',
  'description' => 'A chance to hear more about Google\'s developer products.',
  'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);

Python

# Refer to the Python quickstart on how to setup the environment:
# https://developers.google.com/calendar/quickstart/python
# Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
# stored credentials.

event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'},
  ],
  'reminders': {
    'useDefault': False,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10},
    ],
  },
}

event = service.events().insert(calendarId='primary', body=event).execute()
print 'Event created: %s' % (event.get('htmlLink'))

Ruby

event = Google::Apis::CalendarV3::Event.new(
  summary: 'Google I/O 2015',
  location: '800 Howard St., San Francisco, CA 94103',
  description: 'A chance to hear more about Google\'s developer products.',
  start: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T09:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  end: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T17:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  recurrence: [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  attendees: [
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'lpage@example.com'
    ),
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'sbrin@example.com'
    )
  ],
  reminders: Google::Apis::CalendarV3::Event::Reminders.new(
    use_default: false,
    overrides: [
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'email',
        minutes: 24 * 60
      ),
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'popup',
        minutes: 10
      )
    ]
  )
)

result = client.insert_event('primary', event)
puts "Event created: #{result.html_link}"

Aggiungere allegati di Drive agli eventi

Puoi allegare Google Drive file come le note sulle riunioni in Documenti, i budget Fogli, presentazioni in Presentazioni o qualsiasi altra risorsa i file di Google Drive pertinenti agli eventi del calendario. Puoi aggiungere allegato quando crei un evento con events.insert() o versioni successive nell'ambito di un aggiorna come con events.patch()

Le due parti per allegare un file di Google Drive a un evento sono:

  1. Recupera l'URL del file alternateLink, title e mimeType dal Risorsa File dell'API Drive, in genere con il metodo files.get().
  2. Crea o aggiorna un evento con i campi attachments impostati nella richiesta corpo e il parametro supportsAttachments impostato su true.

Il seguente esempio di codice mostra come aggiornare un evento esistente da aggiungere un allegato:

Java

public static void addAttachment(Calendar calendarService, Drive driveService, String calendarId,
    String eventId, String fileId) throws IOException {
  File file = driveService.files().get(fileId).execute();
  Event event = calendarService.events().get(calendarId, eventId).execute();

  List<EventAttachment> attachments = event.getAttachments();
  if (attachments == null) {
    attachments = new ArrayList<EventAttachment>();
  }
  attachments.add(new EventAttachment()
      .setFileUrl(file.getAlternateLink())
      .setMimeType(file.getMimeType())
      .setTitle(file.getTitle()));

  Event changes = new Event()
      .setAttachments(attachments);
  calendarService.events().patch(calendarId, eventId, changes)
      .setSupportsAttachments(true)
      .execute();
}

PHP

function addAttachment($calendarService, $driveService, $calendarId, $eventId, $fileId) {
  $file = $driveService->files->get($fileId);
  $event = $calendarService->events->get($calendarId, $eventId);
  $attachments = $event->attachments;

  $attachments[] = array(
    'fileUrl' => $file->alternateLink,
    'mimeType' => $file->mimeType,
    'title' => $file->title
  );
  $changes = new Google_Service_Calendar_Event(array(
    'attachments' => $attachments
  ));

  $calendarService->events->patch($calendarId, $eventId, $changes, array(
    'supportsAttachments' => TRUE
  ));
}

Python

def add_attachment(calendarService, driveService, calendarId, eventId, fileId):
    file = driveService.files().get(fileId=fileId).execute()
    event = calendarService.events().get(calendarId=calendarId,
                                         eventId=eventId).execute()

    attachments = event.get('attachments', [])
    attachments.append({
        'fileUrl': file['alternateLink'],
        'mimeType': file['mimeType'],
        'title': file['title']
    })

    changes = {
        'attachments': attachments
    }
    calendarService.events().patch(calendarId=calendarId, eventId=eventId,
                                   body=changes,
                                   supportsAttachments=True).execute()

Aggiungere videoconferenze e conferenze telefoniche agli eventi

È possibile associare gli eventi a Hangouts e Conferenze Google Meet per consentire agli utenti di incontrarsi da remoto con una telefonata o una videochiamata.

Il campo conferenceData può essere utilizzato per leggere, copiare e cancellare i dettagli della conferenza esistenti; ma può anche essere utilizzata per richiedere la generazione di nuove conferenze. Per consentire la creazione modifica dei dettagli della conferenza, imposta la richiesta conferenceDataVersion su 1.

Attualmente sono supportati tre tipi di conferenceData, come indicato dal simbolo conferenceData.conferenceSolution.key.type:

  1. Hangout per i consumatori (eventHangout)
  2. Versione classica di Hangouts per Google Workspace utenti (ritirato; eventNamedHangout)
  3. Google Meet (hangoutsMeet)

Puoi scoprire quale tipo di conferenza è supportato per ogni calendario di un l'utente osservando conferenceProperties.allowedConferenceSolutionTypes in i calendars e calendarList raccolte. Puoi anche scoprire se l'utente preferisce creare Hangout per tutti i suoi ha creato eventi controllando l'impostazione autoAddHangouts nella raccolta settings.

Oltre a type, conferenceSolution fornisce anche name e iconUri campi che puoi utilizzare per rappresentare la soluzione per conferenze come mostrato sotto:

JavaScript

const solution = event.conferenceData.conferenceSolution;

const content = document.getElementById("content");
const text = document.createTextNode("Join " + solution.name);
const icon = document.createElement("img");
icon.src = solution.iconUri;

content.appendChild(icon);
content.appendChild(text);

Puoi creare una nuova conferenza per un evento fornendo a createRequest un requestId appena generato che può essere un string casuale. Le conferenze sono vengono create in modo asincrono, ma puoi sempre controllare lo stato della tua richiesta far sapere agli utenti cosa sta succedendo.

Ad esempio, per richiedere la generazione di conferenze per un evento esistente:

JavaScript

const eventPatch = {
  conferenceData: {
    createRequest: {requestId: "7qxalsvy0e"}
  }
};

gapi.client.calendar.events.patch({
  calendarId: "primary",
  eventId: "7cbh8rpc10lrc0ckih9tafss99",
  resource: eventPatch,
  sendNotifications: true,
  conferenceDataVersion: 1
}).execute(function(event) {
  console.log("Conference created for event: %s", event.htmlLink);
});

La risposta immediata a questa chiamata potrebbe non contenere ancora il campo conferenceData; indicato dal codice di stato pending nel stato . Il codice di stato diventa success dopo che le informazioni sulla conferenza sono compilate. Il campo entryPoints contiene informazioni su quali video e gli URI dei telefoni sono disponibili per la connessione via telefono.

Se vuoi pianificare più eventi nel calendario con lo stesso i dettagli della conferenza, puoi copiare l'intero evento conferenceData da un evento un'altra.

La copia è utile in determinate situazioni. Ad esempio, supponiamo che tu stia sviluppando una domanda di selezione del personale che preveda eventi separati per il candidato e intervistatore: tu vuoi proteggere l'identità dell'intervistatore, ma anche vuoi fare in modo che tutti i partecipanti partecipino alla stessa chiamata in conferenza.