Navigating the Cloud: A Journey into Weather Reporting with Python, Twitter API, and Google Cloud
Navigating the Cloud: A Journey into Weather Reporting with Python, Twitter API, and Google Cloud
Quick Links:
Github
Twitter Bot Account
Introduction:
Embarking on a quest to learn the intricacies of cloud functionality, APIs, and Python scripting, I found myself knee-deep in a project that not only satisfied my curiosity but also provided a practical solution to a daily need. In this blog, I'll walk you through the creation of a Twitter bot that reports the daily weather in my hometown, Nagpur, India, using the Twitter API, OpenWeather API, and the magic of Google Cloud.
The Spark of Curiosity:
Living in Nagpur, where weather can be as unpredictable as a plot twist in a mystery novel, I pondered on the idea of having a daily weather update delivered straight to my Twitter feed. With a background in Python, the allure of APIs, and a budding interest in cloud computing, I decided to turn this seemingly simple idea into a learning adventure.
Setting the Stage:
The first step in my journey involved getting cozy with the Twitter API. I created a Twitter Developer account, set up a new app, and obtained the necessary credentials. Armed with API keys and tokens, I was ready to make my bot sing on the social media stage.
Screenshot from twitter Developer portal
Next up was the OpenWeather API, a treasure trove of weather data waiting to be unlocked. With a few clicks, I had access to a vast array of weather information, perfect for keeping my fellow Nagpurians informed.
Screenshot from OpenWeather Services tab
Python in Action:
With APIs at my fingertips, it was time to let Python do its magic. I crafted a Python script that fetched the daily weather details from the OpenWeather API and composed a succinct tweet to be broadcasted on Twitter. Testing and debugging became my companions, as I fine-tuned the script to perfection.
Github Link: https://github.com/utkaxxh/Twitter-Weather-Bot
import requests
import json
from requests_oauthlib import OAuth1
from config import twitter_api_keys, openweather_api_key
from flask import Flask, request
app = Flask(__name__)
# Set up OAuth1 authentication
auth = OAuth1(
twitter_api_keys["consumer_key"],
twitter_api_keys["consumer_secret"],
twitter_api_keys["access_token"],
twitter_api_keys["access_token_secret"]
)
# Set up API endpoint and headers
url = "https://api.twitter.com/2/tweets"
headers = {"User-Agent": "v2FilteredStreamPython", "Content-Type": "application/json", "Accept-Encoding": "gzip"}
# Set up request data
city = "Nagpur" # Change this to the desired city
forecast_url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={openweather_api_key}"
response = requests.get(forecast_url)
forecast_data = response.json()
# Extract relevant weather information
temperature = round(forecast_data["list"][0]["main"]["temp"] - 273.15, 1)
feels_like = round(forecast_data["list"][0]["main"]["feels_like"] - 273.15, 1)
description = forecast_data["list"][0]["weather"][0]["description"]
icon = forecast_data["list"][0]["weather"][0]["icon"]
rain_chance = forecast_data["list"][0]["pop"] * 100
population = round(forecast_data["city"]["population"])
formatted_population = "{:,}".format(population)
# Map weather icons to emoji characters
emoji_mapping = {
"01d": "☀️", # Clear sky (day)
"01n": "🌙", # Clear sky (night)
"02d": "⛅", # Few clouds (day)
"02n": "🌥️", # Few clouds (night)
"03d": "☁️", # Scattered clouds (day)
"03n": "☁️", # Scattered clouds (night)
"04d": "☁️", # Broken clouds (day)
"04n": "☁️", # Broken clouds (night)
"09d": "🌧️", # Shower rain (day)
"09n": "🌧️", # Shower rain (night)
"10d": "🌦️", # Rain (day)
"10n": "🌧️", # Rain (night)
"11d": "⛈️", # Thunderstorm (day)
"11n": "⛈️", # Thunderstorm (night)
"13d": "❄️", # Snow (day)
"13n": "❄️", # Snow (night)
"50d": "🌫️", # Mist (day)
"50n": "🌫️", # Mist (night)
}
emoji = emoji_mapping.get(icon, "🤔") # Default emoji if icon is not found in the mapping
data = {
"text": f"Good morning Nagpur!\nCurrent temperature is {temperature}°C, and it feels like {feels_like}°C.\nIt will (be) {description} {emoji} most of the day with chances of rain being {rain_chance}%\nToday's population: {formatted_population}"
}
# Send POST request to create a new tweet
@app.route('/')
def my_tweet(request):
response = requests.post(url, headers=headers, data=json.dumps(data), auth=auth)
# Print response information
print("Response status code:", response.status_code)
print("Response JSON:", response.json())
return "Tweet sent successfully!"
if __name__ == '__main__':
app.run(debug=True)
Into the Cloud:
To elevate my project to new heights, I decided to deploy the Python script on Google Cloud Functions. The serverless architecture provided by Google Cloud Functions allowed my script to run seamlessly without the need for managing servers. This was the point where cloud computing truly started to make sense.
Screenshot from Google Cloud Platform's Cloud Function service
Scheduling the Symphony:
For the grand finale, I orchestrated the entire performance using Google Cloud Scheduler. With a few configurations, I set up a daily schedule for my function to run, ensuring that Nagpur woke up to a fresh weather update every morning. The simplicity of the setup was both empowering and awe-inspiring.
Screenshot from Google Cloud Platform's Cloud Scheduler service
Lessons Learned:
As I reflect on this project, the wealth of knowledge gained is immeasurable. I delved into the intricacies of API integration, mastered the art of Python scripting, and soared into the clouds with Google Cloud. The project not only provided a practical solution to a daily need but also served as a testament to the endless possibilities that emerge when curiosity meets technology.
Screenshot from Twitter Account of the bot
Conclusion:
What started as a personal quest for knowledge transformed into a full-fledged project that brought together the realms of Python, APIs, and cloud computing. Creating a Twitter bot to report the daily weather for Nagpur became more than just a technical endeavor—it became a symphony of learning, a testament to the limitless potential that emerges when one embraces the cloud.