IBM Bluemix Weather Company API with Python

Here is a simple example of calling the IBM Weather Company REST API using Python. The program asks for a US ZIP code and then displays some of the data. A perfect program for an intro to programming class. Also, on GitHub.


# Using the IBM Bluemix Weather Company API
# Bruce Elgort
# July 9, 2016
# Version 1.0
# IBM Weather Company Docs: https://console.ng.bluemix.net/docs/services/Weather/weather_rest_apis.html#rest_apis

import requests
import json

def get_weather(zip):
    username = 'your username'
    password = 'your password'

    watsonUrl = 'https://twcservice.mybluemix.net/api/weather/v1/location/' + zip + ':4:US' + '/observations.json?language=en-US'

    try:
        r = requests.get(watsonUrl,auth=(username,password))
        return r.text
    except:
        return False

def display_weather(results):
    print()
    print('Here is the weather for {0}'.format(results['observation']['obs_name']))
    print('{0:20} {1:<10}'.format('Current Temperature:',str(results['observation']['temp']) + '° and ' + results['observation']['wx_phrase']))
    print('{0:20} {1:<10}'.format('Feels Like: ',str(results['observation']['feels_like']) + '°'))
    print('{0:20} {1:<10}'.format('Low Temp: ',str(results['observation']['min_temp']) + '°'))
    print('{0:20} {1:<10}'.format('High Temp: ',str(results['observation']['max_temp']) + '°'))
    print('{0:20} {1:<10}'.format('Winds:',str(results['observation']['wspd']) + ' mph coming from the ' + results['observation']['wdir_cardinal']))

def get_weather():
    zip = input('Enter US ZIP code to get weather for:\n')
    results = get_weather(zip)
    if results != False:
        results = json.loads(str(results))
        display_weather(results)
    else:
        print('Something went wrong :-(')

if __name__ == '__main__':
    get_weather()
Advertisement

And I’m Back

IMG_0221.png

I’m delighted to be part of Clark College for another year. This marks my fourth year at the college teaching web development. Here’s a list of all the courses that I have taught:

  • Intro to Programming and Problem Solving with Python (CTEC 121)
  • HTML Fundamentals (CTEC 122)
  • JavaScript (CTEC 126)
  • Business Web Practices (CTEC 165)
  • PHP with SQL 1 (CTEC 127)
  • PHP with SQL 2 (CTEC 227)
  • API & Advanced Integration (CTEC 228)
  • WordPress Development (CTEC 260)

Using the Slack API with Python – A Simple Example

Here is a simple Python program that can be used to:

  • Test the API
  • Get a list of Slack Users
  • Get a list of Slack Channels
  • Get information about a Slack Channel
  • Post a message to Slack Channel

Students in my Intro to Programming and Problems Solving class at Clark College learn how to build this and other things using Python.

Have fun with it!

On Github >

# CTEC 121 / Intro to Programming and Problem Solving
# Lab - Using the Slack API
# by Bruce Elgort, 2016

# pip install slackclient to install SlackClient library
from slackclient import SlackClient
import json

def test_slack(sc):
    # use for debugging
    print("Testing API")
    print(80 * "=")
    print (sc.api_call("api.test"))

def get_channel_info(sc,channel):
    # get info about the channel
    print("Getting Channel Info")
    print(80 * "=")
    print (sc.api_call("channels.info", channel=channel))

def get_list_of_channels(sc):
    print("Getting List of Channels")
    print(80 * "=")
    # get list of channels
    channels = sc.api_call("channels.list")
    channels = json.dumps(channels)
    channels = json.loads(str(channels))
    return channels

def display_channels(channels):
    print("Display Channels")
    print(80 * "=")
    for i in channels['channels']:
        print("Channel:",i['name'])

def post_message(sc,text,channel,icon_url,username):
    print("Posting Message to Slack")
    print(80 * "=")
    # post a message into the #general channel
    print (sc.api_call("chat.postMessage",channel=channel,text=text,username=username,icon_url=icon_url,unfurl_links="true"))

def get_users(sc):
    print("Get Users")
    print(80 * "=")
    #call the users.list api call and get list of users
    users = (sc.api_call("users.list"))
    users = json.dumps(users)
    users = json.loads(str(users))
    return users

def display_users(sc,users):
    print("User List")
    print(80 * "=")
    # display active users
    for i in users['members']:
        # don't display slackbot
        if i['profile']['real_name'] != "slackbot":
            # don't display deleted users
            if not i['deleted']:
                # display real name
                print (i['profile']['real_name'])
def main():
    # define variables
    token = "your token"
    channel = "a channel id"
    username = "Username to use display for message function"
    icon_url = "icon url for message function"
    # connect to Slack
    sc = SlackClient(token)
    # test slack
    test_slack(sc)
    # get channel info
    get_channel_info(sc,channel)
    # get list of channels
    channels = get_list_of_channels(sc)
    # display channels
    display_channels(channels)
    # post message
    post_message(sc,"Visit http://slack.com",channel,icon_url,username)
    # get users
    users = get_users(sc)
    # display users
    display_users(sc,users)

main()

Using IBM Watson Language Translation Services with Python

Here is a very simple example using Python of calling the IBM Watson Language Translation Service. Feel free to use and modify the code as needed. You will need an IBM Bluemix account in order to use the translation service.

# CTEC 121 Intro to Programming and Problem Solving
# Bruce Elgort / Clark College
# Using IBM Watson's Language Translator
# February 27, 2016
# Revised: May 24, 2016
# Version 1.1

import requests

def cls():
    print("\n" * 5)

def translate_text(text,source,target):
    username = 'your username'
    password = 'your password'
    watsonUrl = 'https://gateway.watsonplatform.net/language-translation/api/v2/translate?source=' + source + '&target=' + target + '&text=' + text
    try:
        r = requests.get(watsonUrl,auth=(username,password))
        #print(r)
        return r.text
    except:
        return False

def welcome():
    message = "Welcome to the IBM Watson Translator\n"
    print(message + "-" * len(message) + "\n")
    print("Have fun!\n")

def main():
    cls()
    welcome()

    data = input("Enter some text to be translated:\n")

    print()
    print("What language should I translate it to?")
    print("1) Spanish")
    print("2) Arabic")
    print("3) French")
    print("4) Portuguese")
    print()
    target = input("Select a language from the list above: ")

    if target == "1":
        target = 'es'
    elif target == "2":
        target = 'ar'
    elif target == "3":
        target = 'fr'
    elif target == "4":
        target = 'pt'

    results = translate_text(data,'en',target)
    print()
    print("Here is the text translated for you:")
    print(results)

main()

 

 

What I’m Teaching this Summer and Fall at Clark College

Registration for Clark College summer and fall quarters is now open! I’m teaching HTML Fundamentals (CTEC 122) this summer, and in the fall, Intro to Programming and Problem Solving (CTEC 121), PHP/MySQL (CTEC 127) and Business Web Practices (CTEC 165). If you are interested in taking any of these classes, please let me know.

Please share this with your friends who might be interested in taking any of these classes.

Did I mention that I’m approaching 3.5 years of teaching at Clark? Man, how the time goes by…

I’m Bringing IBM Bluemix and IBM Watson to the Classroom

bluemix-logo-right

I am very happy to announce that students enrolled in my “Intro to Programming and Problem Solving” class at Clark College in Vancouver, Washington will be using IBM Bluemix and IBM Watson this week in class. Students will be building a language translation program and a tone analyzer program using the Python programming language.

Many thanks to IBM for their “Academic Initiative” program which makes it easy for educators to get access to IBM Bluemix for a limited time.

Students in my other programming language course will also soon be using Bluemix and Watson.

Stay tuned.

Here’s what I am teaching this winter at Clark College

For the winter quarter I will be teaching the following courses at Clark College in Vancouver, Washington:

  1. CTEC 121: Intro to Programming and Problem Solving (Python) – 5 credits
  2. CTEC 122: HTML Fundamentals (HTML/HTML5/CSS) – 4 credits
  3. CTEC 127: PHP/MySQL 1 – 5 credits

If you are interested in taking any of these classes please let me know.

My Fall 2015 Schedule at Clark College

Here is my class schedule for the fall 2015 quarter:

Monday – API & Advanced Integration (CTEC 228) 6:30-8:50PM, room SHL 124

Tuesday/Thursday – Intro to Programming and Problem Solving (CTEC 121) 10:30AM-12:50PM, room SHL 125
Tuesday/Thursday – Business Web Practices (CTEC 165) 4:00-5:50pm, room SHL 125 (Tueday) / Foster Auditorium (Thursday)

Check the Clark College website to see when you can register.