Build an Appointment Bot using Twilio SMS and Google Calendar API with C# and ASP.NET Core
Time to read: 9 minutes
Let’s say you run a business where people have to make a call to schedule an appointment with you. When the call comes in, you have to check your calendar and make sure the date and time your customer suggests are available. If the date and time is available, you confirm the appointment, otherwise, you circle around to find an alternative date and time that's available.
But what if you could automate this by allowing your customers to make appointments with you using SMS? In this tutorial, you will build an SMS Scheduling System that allows your customers to make an appointment with your business and have this appointment sync with your Google Calendar. You will build this solution using Twilio SMS, Google Calendar API and .NET.
Prerequisites
You will need the following things to follow along
- A Twilio account. Sign up for a Twilio account here and get trial credit to spend on Twilio Products.
- A Google Account.
- A code editor or IDE (Recommended: Visual Studio Code with the C# plugin, Visual Studio, or JetBrains Rider)
- ngrok CLI, to expose your local development environment over the internet
- Some experience with ASP.NET Core and Razor Pages.
- A personal phone number that can be used for testing.
You can find the source code on this GitHub repository.
Solution Overview
The goal of the app is to have a customer send a text message to your Twilio Phone Number, and based on your existing schedule, it can either schedule an appointment for them, which creates an event in your Google Calendar, or tell the person you are not available for that date and time.
The app will contain these components:
- The Google Calendar integration, where you will connect your Google Calendar to the app, thereby giving it the authority to create a Google Calendar event for you.
- The Twilio SMS integration, where you will write the webhook to extract an appointment from a user’s message with all the details necessary
Create a Project in Google Developer Console.
In this section, you will create a Google Cloud project that configures the OAuth flow to request access to the Google Calendar of the business owner. This access will give you the ability to interact with the user’s calendar through the Google Calendar API.
Log on to the Google Cloud Console, and create a new project.
After the project has been created, click on the + ENABLE APIS AND SERVICES button. This redirects you to a search page for finding different Google APIs. Search for "Google Calendar", select the Google Calendar API, and enable it.
Next, you have to configure the Consent Screen.
On the left navigation panel, select the OAuth consent screen link.
The first page shows an option to select a User Type. Select the External option and click the Create button to continue.
The next page shows you a form to fill out more details about your application. For the sake of this tutorial, fill out the App name and User support email in the App Information section. Then fill out the developer contact information - at the tail end. Then click the Save and Continue button.
Next, you will add the different scopes (permissions) that you need for your app. Click on the Add or Remove Scopes button. Add …/auth/userinfo.email, .../auth/userinfo.profile, and openid scopes.
Then, filter by Google Calendar API and select the .../auth/calendar scope.
Click the Update Button to add your selection. Then, click on the Save and Continue button.
Next, add your own Google Account email address. This will be the account and associate Google Calendar that you'll give access to the application.
Only Google accounts that are added as test users can give their consent to your app while in "Testing" status. Once you go live, anyone with a valid Google account can give their consent.
Finally, click on the Save and Continue button to complete the registration.
Then, create the credentials for your app. Use the left panel to navigate to the Credentials section and Create OAuth Client ID using the Create Credentials button at the top bar.
Select Web Application when asked about the Application type, then proceed to enter the application name, add http://localhost:8080 to the Authorized redirect URIs the URIs
The Authorized redirect URIs are where you want the response of the OAuth flow to be sent - in this application it should go to the homepage.
Once you click the Create button, you are shown the Client ID and Client Secret. Take note of the Client ID and Client Secret, as you'll need them later.
Build the User Configuration Razor Page
In this section, you will build the User Configuration Page which will allow you to do two things:
- Connect your Google account to the app, thereby giving you the access token needed to modify your Google Calendar
- Configure the days and time slots you will be taking appointments.
To begin, create an ASP.NET Core Razor Pages project with the following command, and open it in your code editor.
Setup Google Credentials.
Set up the Google credentials you took note of earlier. Firstly, add the client secret using the Secrets Manager:
Replace [CLIENT_SECRET]
with the Client Secret you took note of earlier.
Then add the other properties like the client ID, redirect URL, and scopes in the appsettings.json to look like the one shown below:
Replace [GOOGLE_API_CLIENT_ID]
with the Client ID you took note of earlier.
Storing the User Configurations
When the user grants access to their Google Calendar, you'll need to retrieve an access token, refresh token, and expiry time. These values need to be persisted somewhere so they can be used when a text message comes in. Additionally, the open hours and days also need to be stored somewhere. For the sake of the demo, this information will be stored in memory, using the singleton pattern. In production, you would store this in some data store and expand the application to support more than one business user and phone number.
Create the UserConfiguration
class and update the code like below:
Now, you will update the Index Page and create the UI for managing the user configuration.
User Configuration UI
Update the Index.cshtml with the following code:
The Index.cshtml file creates a button that redirects to the consent screen for you to log into your Google account. The redirect link, @Model.RedirectLink
, is generated from the code behind using the Google credentials.
Also on the Index page is the form to set the opening time and closing time and check the available days. The form is also posted and saved into the configuration singleton.
Here is the code that generates the redirect link and handles the form:
The redirect link to the consent screen is generated on the OnGet
method based on the Google identity docs by passing the different parameters that are required and specified in the documentation. The OnGet
method also accepts a string parameter, but it is not currently in use as it comes into play when you want to receive a response from the Google API.
The OnPost
method is hit when you submit the form and retrieves the different fields from the form uses userConfig
to persist the necessary information.
Finally, add the code to OnGet
to receive the Google OAuth response and makes a request for the tokens you will need to access the Google Calendar API.
When Google sends a response to your app, the string parameter, code
, is no longer null, and it is used to make a request to the Google API using the requestTokenUrl
which returns with a token object that contains the access token, refresh token, expiry date.
After the JSON properties are extracted from the response, the individual properties are accessed using the JSON accessor pattern. The expiring date is expressed in a C# DateTime
object by adding seconds to the current DateTime
.
To ensure the app runs on port 8080, edit the launch setting, Properties/launchSettings.json, and update the applicationUrl
property with the port number:
Run the app to test. Remember to log in with the test Google account that you added when setting up the project in Google console.
Next, you will write the SMS Webhook.
Build the SMS Webhook
The SMS webhook is a web API controller that will (i) receive the customer SMS, (ii) extract an appointment from it and (iii) proceed to add it to the user’s calendar. The details of the appointment would include time, date and a short description.
Here is an example of a message you might be receiving from your customer, "Hello, I would like to make an appointment for a full body massage on the 3rd of November at 10 am". This message then uses an algorithm to extract the necessary details that are needed to create the appointment and also the same format needed to create an event on a Google Calendar. Here is the resulting structure below.
The time is specified in a 24 hour format with the time zone appended to the end of the time e.g. +01:00 indicates a timezone of UTC+1
To begin, install the following Twilio package to build the Twilio messaging response.
Next, update the Program.cs to add access for mapping API controllers with the following line of code.
Extract Appointment from SMS
To begin the extraction, create an AppointmentDetails
class in a file to describe the structure of the appointment details and Google Calendar event.
These classes will also be used to submit the data to the Google Calendar API in the expected format, hence the usage of the [JsonProperty]
to configure the correct property names.
Then create an AppointmentDetailsExtractor
class and update it with the code below:
The AppointmentDetailsExtractor.Extract
method is the implementation of the extractor algorithm that takes in the smsBody
, timezone
, and the senderPhoneNo
. Through a series of manipulation that involves regular expressions, string manipulations, and data conversions, the summary, day, month, year and time component are extracted from the message. The method then returns an object of type AppointmentDetails
.
SMS Webhook API Controller
Then create the webhook API controller, Api/WebhookController.cs, and add the following code:
The WebhookController
injects a number of objects and serves a single HTTP POST method, IncomingMessage
, that receives the SMS and retrieves the content using the Request
object. Then the UserConfiguraton
instance is retrieved to get the necessary details, which is used in the GetAccessToken
method to get the access token from the Google API.
Thereafter, the AppointmentDetailsExtractor.Extract
method extracts the details of the schedule from the message and checks if the appointment date and time falls within days and time that you have previously selected. If the appointment is within your settings, a request is sent to the Google Calendar API to create an event and a message is sent back to the user.
Prevent Appointment conflicts
To prevent appointment conflicts, you need to get all events that are on the day of the request appointment date. The request to get the events for that day in your calendar returns a JSON response which is deserialized to objects of classes you will create next.
Create the CalendarResponse
class and add the following code to it:
Then update the IncomingMessage
method in the WebhookController
file to make a call to the Google Calendar API to check if there is already an existing event on the appointment date. If there is one, a corresponding message is sent back to the user.
Configure the SMS Webhook
To begin testing, start the app with the dotnet run
command and then run the following ngrok command:
ngrok generates a Forwarding URL that exposes the http://localhost:8080 over the internet. The generated URL is what you will use in the Twilio Console. The full URL of the webhook will look like https://7626-41-184-42-209.eu.ngrok.io/api/Webhook.
Log on to the Twilio Console. Click on Explore Products option on the left panel and search for the Phone Number feature under the Super Network section. Click on the Phone Number option. This opens up a list of Active Numbers. Click on the Twilio Phone Number that you wish to use. Once the new page opens, navigate to the messaging section, and update the Webhook for the A MESSAGE COMES IN section with the ngrok URL.
Next, navigate to your app running locally on port 8080 to set up your account.
Then, send a text message: "Hello, I would like to make an appointment for a full body massage on the 10th of November at 2 pm" to your Twilio number.
Conclusion
In this tutorial, you have connected a Google account to your app giving you access to your Google Calendar, and then you added a number of other configurations like the days of the week and work hours. Then you proceeded to write a method that extracted details of an appointment from the SMS that the customer sent, and finally created an event for yourself in the Google Calendar.
To continue learning, here are a couple of tutorials you can check out:
- Get notified of new magazine issues using web scraping and SMS with C# .NET
- How to Send Scheduled SMS with Twilio
- Build an Emergency Contact Notification System with Twilio SMS
Check out the full code on GitHub.
Similoluwa Adegoke is a Software Engineer who currently works in Banking. His day-to-day bothers from working with new technologies to updating legacy code. If Simi is not coding or writing, he is watching tv shows and playing video games. Simi can be reached at adegokesimi[at]gmail.com
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.