I made a slack bot that notifies me of the temperature

Get a token for Open Weather Map

Create an account at http://openweathermap.org/ and get API_KEY on the api_keys screen.

Get a token for Slack bot testing

The explanation of how to get the bot token is given in the slack api manual.

Reference URL: https://api.slack.com/bot-users

Program example

In this program, the latitude and longitude are specified and the temperature in the corresponding area is acquired.

In bot.py, the process of actually getting the temperature and tweeting it on the slack channel is described. Open Weather Map, slack token, etc. are set in settings.py.

Directory structure

norths_weather_bot
├── bot.py
└── settings.py

bot.py

#/usr/bin/env python2.7                                                                                                                                                                                     
#-*- coding: utf-8 -*-                                                                                                                                                                                      

import json
import urllib
import urllib2

import settings

class Weather(object):
    """                                                                                                                                                                                                     
    """
    def __init__(self):
        """                                                                                                                                                                                                 
        """
        params = {'appid' : settings.OPEN_WETHER_APP_ID,
                  'lat'   : settings.OPEN_WETHER_LAT,
                  'lon'   : settings.OPEN_WETHER_LON,
                  'units' : settings.OPEN_WETHER_UNITS,
                  }

        params = urllib.urlencode(params)
        response = urllib2.urlopen(settings.OPEN_WETHER_URL + '?' + params)

        self.json = json.loads(response.read())


    def get_temp(self):
        """                                                                                                                                                                                                 
        """
        return {'max' : self.json['main']['temp_max'],
                'min' : self.json['main']['temp_min'],
                'now' : self.json['main']['temp'], }


class Bot(object):
    """                                                                                                                                                                                                     
    """
    def __init__(self):
        """                                                                                                                                                                                                 
        """
        self.set_serif()

    def set_serif(self, serif=''):
        """                                                                                                                                                                                                 
        """
        self.serif = serif

    def speak(self):
        """                                                                                                                                                                                                 
        """
        params = {'token'  : settings.SLACK_TOKEN,
                  'channel': settings.SLACK_CHANNEL,
                  'text'   : self.serif,}

        params = urllib.urlencode(params)

        req = urllib2.Request(settings.SLACK_URL)

        req.add_header('Content-Type', 'application/x-www-form-urlencoded')
        req.add_data(params)

        res = urllib2.urlopen(req)

        body = res.read()


if __name__ == "__main__":
    """                                                                                                                                                                                                     
    entry point                                                                                                                                                                                             
    """
    temp = Weather().get_temp()

    bot = Bot()
    bot.set_serif('Current temperature: {0}℃ ,Highest temperature: {1}℃ ,Lowest Temperature: {2}℃'.format(temp['now'], temp['max'], temp['min']))
    bot.speak()

settings.py

#-*- coding: utf-8 -*-                                                                                                                                                                                      

OPEN_WETHER_URL = "" # API URL
OPEN_WETHER_APP_ID = "" # API KEY
OPEN_WETHER_LAT = "" #latitude
OPEN_WETHER_LON = "" #longitude
OPEN_WETHER_UNITS = "" #Specify whether it is Celsius or absolute temperature. In the case of metric, it is Celsius.

SLACK_URL = "" # URL
SLACK_TOKEN = "" #token
SLACK_CHANNEL = "" #The channel you want to post

GIT repository

https://bitbucket.org/ponsuke/norths_weather_bot

Recommended Posts

I made a slack bot that notifies me of the temperature
I made a github action that notifies Slack of the visual regression test
I made a SlackBot that notifies me of AtCoder contest information every week
I made a Linebot that notifies me of nearby evacuation sites on AWS
[Discode Bot] I created a bot that tells me the race value of Pokemon
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
I want a Slack bot that calculates and tells me the salary of a part-time job from the schedule of Google Calendar!
I made a calendar that automatically updates the distribution schedule of Vtuber
I wrote a Slack bot that notifies delay information with AWS Lambda
I made a Line bot that guesses the gender and age of a person from an image
I started to work at different times, so I made a bot that tells me the time to leave
Make a BOT that shortens the URL of Discord
With LINEBot, I made an app that informs me of the "bus time"
LINE Bot that notifies you of the stocks of interest
I made a discord bot
I made a LINE bot that tells me the type and strength of Pokemon in the Galar region with Heroku + Flask + PostgreSQL (Heroku Postgres)
I made a twitter app that decodes the characters of Pricone with heroku (failure)
A program that notifies slack of the operating status of fully automatic botanical photography equipment
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
I made a calendar that automatically updates the distribution schedule of Vtuber (Google Calendar edition)
Add a function to tell the weather of today to slack bot (made by python)
I made a dot picture of the image of Irasutoya. (part1)
I made a dot picture of the image of Irasutoya. (part2)
[Python] I made a Line bot that randomly asks English words.
I made a program that solves the spot the difference in seconds
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a Discord chat reading bot by imitating the appearance
I made a program that automatically calculates the zodiac with tkinter
[Kaggle] I made a collection of questions using the Titanic tutorial
The story of creating a bot that displays active members in a specific channel of slack with python
I made a Discord bot in Python that translates when it reacts
I wrote a corpus reader that reads the results of MeCab analysis
I made a simple timer that can be started from the terminal
I made a GAN with Keras, so I made a video of the learning process.
I made a library konoha that switches the tokenizer to a nice feeling
I made a program to check the size of a file in Python
I made a mistake in fetching the hierarchy with MultiIndex of pandas
I made a function to see the movement of a two-dimensional array (Python)
(Python) I made an app from Trello that periodically notifies slack of tasks that are about to expire.
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
I made a stamp substitute bot with line
I made a LINE Bot with Serverless Framework!
I made a Mattermost bot with Python (+ Flask)
I made a tool to estimate the execution time of cron (+ PyPI debut)
The story of IPv6 address that I want to keep at a minimum
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I made a tool to notify Slack of Connpass events and made it Terraform
I made a LINE Bot that sends recommended images every day on time
I made an appdo command to execute a command in the context of the app
I made a tool to automatically back up the metadata of the Salesforce organization
The story of making a Line Bot that tells us the schedule of competitive programming
In Python, I made a LINE Bot that sends pollen information from location information.
I made a script to record the active window using win32gui of Python
[Python] I made a web scraping code that automatically acquires the news title and URL of Nikkei Inc.
[AWS] I made a reminder BOT with LINE WORKS
A story that reduces the effort of operation / maintenance
I made a Twitter BOT with GAE (python) (with a reference)
[Python] A program that counts the number of valleys
I made a household account book bot with LINE Bot
〇✕ I made a game