Whether deciding what to wear to and from the office or planning a team outing for the coming week, we’re constantly adjusting for the weather. Using the OpenWeatherMap API and Google Apps Script, you can make keeping track of the weather a little easier.
With this Typetalk bot, you can schedule regular weather updates and receive replies to current weather requests right in a Typetalk topic.
How to create a weather bot for Typetalk
Get an API Key
We are using the OpenWeatherMap API. You will need to sign up on their website to use the API.
Simply create an account, and retrieve a free API Key.
Reply with current weather
To start, we need to create a new Typetalk bot that you can mention with a city name and it will reply with the current weather in that city.
- Create Google Apps Script
First, we need to create the Google Apps Script and run a test to make sure the API call succeeds.
In your Google Drive, create a new Google Apps Script.
You can copy our code and replace the API Key with your own, or create your own code from scratch. Once you’ve finished, save the script.
var API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"; // replace this with your key
var IS_CELSIUS = true;
function requestJson(path) {
var url = "http://api.openweathermap.org/data/2.5/" + path + "&APPID=" + API_KEY;
if (IS_CELSIUS) {
url += "&units=metric";
}
var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
return JSON.parse(response.getContentText());
}
function getCurrent(query) {
var json = requestJson("weather?q=" + query);
if (json.cod == "200") {
var weather = json.weather[0];
return "Current weather in " + json.name + ", " + json.sys.country
+ ": " + weather.description + " " + json.main.temp + "°" + (IS_CELSIUS ? "C" : "F")
+ "\nhttp://openweathermap.org/img/w/" + weather.icon + ".png";
} else {
return json.message;
}
}
function testCurrent() {
Logger.log(getCurrent("Tokyo"));
}Select the “testCurrent” function in your dropdown menu, and click the triangle button to test the code.
After running the test, you can see a log by selecting View > Logs from the dropdown menu.
If the API call succeeded, you should see logs like the following.
- Deploy your script
Add a doPost function in the code to receive a webhook from Typetalk.
function doPost(e) {
var jsonString = e.postData.getDataAsString();
var post = JSON.parse(jsonString).post;
var query = post.message.replace(/@[-\w]+\+/g, "").trim();
var message = getCurrent(query);
var data = {"message": message, "replyTo": post.id };
return ContentService.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON);
}And then “Deploy as web app” from the Publish section of the drop-down menu.
For “Execute the app as:” select “Me” and for “Who has access to the app:” select “Anyone, even anonymous”.
Copy the web app URL in the dialog.
- Create a bot
In the Typetalk web app, click the Topic Settings icon and select the “BOTS” tab. Click the “Add New” button, and then create an ID and Full Name. Finally, check “Use Webhook”, and paste the URL that you copied in the previous step before clicking the “Create” button to save.
Finally, post a message like “@weather+ Tokyo” in the topic. Your new bot should reply with the current weather.
Scheduled weather forecast
Now we’ll update the weather bot you just created to post weather forecasts at a scheduled time.
- Update your script
Copy the following code into your script, or create your own.
var CITY = "Tokyo"; // Change this to city name you want to know
Run the “testForecast” function to check your script.
var EMOJI_BY_ID = {
"801": " :mostly_sunny:",
"802": " :partly_sunny:",
"803": " :barely_sunny:",
"804": " :cloud:"
}
var EMOJI_BY_MAIN = {
"Rain": " :rain_cloud:",
"Clouds": " :cloud:",
"Snow": " :snow_cloud:"
}
function getEmoji(weather, date) {
if (weather.id == 800) {
var h = date.getHours();
if (6 <= h && h < 18) {
return " :sunny:";
} else {
return " :crescent_moon:";
}
}
var emoji = EMOJI_BY_ID[weather.id];
if (emoji) {
return emoji;
}
emoji = EMOJI_BY_MAIN[weather.main];
return emoji ? emoji : "";
}
function getForecast() {
var json = requestJson("forecast?cnt=8&q=" + CITY);
if (json.cod == "200") {
var message = "Weather forecast in " + json.city.name + ", " + json.city.country
for (var i = 0; i < json.list.length; i++) {
var data = json.list[i];
var date = new Date(data.dt * 1000);
var time = Utilities.formatDate(date, Session.getScriptTimeZone(), "EEE, MMM d h:mm a");
var weather = data.weather[0];
message += "\n" + time + " - " + weather.description + getEmoji(weather, date) + " "
+ data.main.temp + "°" + (IS_CELSIUS ? "C" : "F");
}
return message;
} else {
return json.message;
}
}
function testForecast() {
Logger.log(getForecast());
} - Post a message to Typetalk
Under Topic Settings > BOTS > Bot Settings, check “topic.post” for the API Scope and copy the “Get or post messages URL” to your clipboard.
Add the following code to your script, but replace the POST_URL with your bot’s URL, and try to run a “postForecast” function.
var POST_URL = "https://typetalk.com/api/v1/topics/xxxxx?typetalkToken=xxxxxxxxxxx";
function postForecast() {
UrlFetchApp.fetch(POST_URL, {method: "post", payload:{message: getForecast()}});
} - Set a schedule
Click the “Current project’s trigger” button.
Add a trigger like the following making sure to select the “postForecast” function.
Next time your trigger time hits, you will see the weather forecast you selected.
And there you have it! Now you have your very own weather bot that can respond with current weather updates, and share recurring weather forecasts whenever you’d like.