Add a function to tell the weather of today to slack bot (made by python)

What to do in this article

If you ask the bot "What's the weather today?", I will tell you the weather today as follows.

スクリーンショット 2017-08-17 16.27.56.png

Mounting method

The implementation is very easy, I will use the command created by the following person and return the result from the bot. [Code to quote]

curl -s https://weather.yahoo.co.jp/weather/jp/40/8210/40133/8100001.html | tr '\n' ' ' | sed -e 's/<[^>]*>//g' | grep -oE ' - [0-9].*tomorrow' | tr ' ' '\n' | grep -v ^$ | head -47 | tr '\n' '\t' | awk '{sub("time", "\ntime ");sub("weather", "\nweather ");sub("Temperature (℃)", "\nTemperature (℃)");sub("Humidity (%)", "\nHumidity (%)");sub("Precipitation (mm/h)", "\nPrecipitation (mm/h)");print}'

One line to get and display the weather forecast with Linux command

We will add functions to the python bot created below [Add conversation function to slack bot (made by python) using Recruit's Talk API](http://qiita.com/takahirono7/items/197375db24a03cbcd591#%E3%81%93%E3%81%AE%E8 % A8% 98% E4% BA% 8B% E3% 81% A7% E3% 82% 84% E3% 82% 8B% E3% 81% 93% E3% 81% A8)

File structure and directory

Create a new directory and file with a star. Take the route from my_mention.py to hit the modular confirm_weather.py

slackbot         #A directory that organizes programs. Any name is fine
├─ run.py        #Start the bot by running this program
├─ slackbot_settings.py   #File to write settings related to bot
└─ plugins                #Add bot functionality to this directory
   ├─ __init__.py         #A file to indicate the module. Sky is fine
   └─ my_mention.py       #Features each file. Any name is fine
★   └─ scripts           #script storage directory
★       ├─ confirm_weather.py     #Script to get the weather information this time
★       ├─ confirm_today_weather.sh     #A script that contains the curl command
★       ├─__init__.py

The current my_mention.py should look like this:

# coding: utf-8

from slackbot.bot import respond_to     # @botname:Decoder that reacts with
from slackbot.bot import listen_to      #Decoder that responds to in-channel remarks
from slackbot.bot import default_reply  #Decoder that reacts when there is no corresponding response

# @respond_to('string')Message to bot
#string can be a regular expression "r'string'」
# @listen_to('string')Posts other than to bots in the channel
#                           @botname:Note that it does not react
#React when mentioning to others
#Regular expression possible
# @default_reply()          DEFAULT_Same function as REPLY
#If you specify a regular expression, it will not hit other decoders,
#Reacts when matching a regular expression
#... But is it an error if I specify a regular expression?

# message.reply('string')   @Speaker name:Send message with string
# message.send('string')Send string
# message.react('icon_emoji')Reaction to the speaker's message(stamp)To do
#In the string':'I don't need
@respond_to('Mention')
def mention_func(message):
    message.reply('What do you do when you say mention to me') #Mention

@listen_to('Listen')
def listen_func(message):
    message.send('Someone seems to have posted with listen')      #Just a post
    message.reply('You?')                           #Mention

import pya3rt
@default_reply()
def send_message(message):
    apikey = "XXXXXXXXXXXXXXXXXXXXXXX"
    client = pya3rt.TalkClient(apikey)
    reply_message = client.talk(message.body['text'])
#Since json is returned in the following format, take out the reply part
# {'status': 0, 'message': 'ok', 'results': [{'perplexity': 1.2802554542585969, 'reply': 'I'm not sure'}]}
    message.reply(reply_message['results'][0]['reply'] + "Pome" )

I will add the following code here


from plugins.scripts.confirm_weather import ConfirmWeather
#A function that tells you the weather today
@respond_to('(^.*today.*weather.*)')
def confirm_today_weather(message, something):
    weather_class = ConfirmWeather()
    weather_class.return_today_weather(message)

It's okay to write the code in my_mention.py, but it will be long, so I will specialize the function that my_mention.py has for post-reservation registration and module calling. The actual confirmation code is described in confirm_weather.py and confirm_today_weather.sh under scripts.

confirm_weather.py

import json
import subprocess
import os


class ConfirmWeather():

    def __init__(self):
    pass

    def return_today_weather(self, message):
#Get the path where this script is located
        script_dir = os.path.abspath(os.path.dirname(__file__))
        cmd = os.path.join(script_dir, "confirm_today_weather.sh")
#Store the execution result of the shell script placed in the same directory in a variable
        weather_info = subprocess.check_output(cmd)
        print(weather_info.decode('utf-8'))
#POST to slack
        message.send("I'll tell you the weather today")
        message.send(weather_info)

The following points are important: The execution result of the shell script in the same directory is stored in a variable using the check_output method of the subprocess module.

#Store the execution result of the shell script placed in the same directory in a variable
        weather_info = subprocess.check_output(cmd)

confirm_today_weather.sh The one-liner command quoted at the beginning is stored in the same directory as a shell script file as shown below.

-Give execution permission with chmod 755 -Modularize __init__.py in the same directory Don't forget

curl -s https://weather.yahoo.co.jp/weather/jp/40/8210/40133/8100001.html | tr '\n' ' ' | sed -e 's/<[^>]*>//g' | grep -oE ' - [0-9].*tomorrow' | tr ' ' '\n' | grep -v ^$ | head -47 | tr '\n' '\t' | awk '{sub("time", "\ntime ");sub("weather", "\nweather ");sub("Temperature (℃)", "\nTemperature (℃)");sub("Humidity (%)", "\nHumidity (%)");sub("Precipitation (mm/h)", "\nPrecipitation (mm/h)");print}'

Run the bot with python run.py, what's the weather today? If you talk to the bot, the result at the beginning will come back.

Recommended Posts

Add a function to tell the weather of today to slack bot (made by python)
Add conversation function to slack bot (made by python) using Recruit's Talk API
I made a function to see the movement of a two-dimensional array (Python)
I made a function to check the model of DCGAN
Notification of weather forecast (rain, etc.) by DM as a part of the function of bot
Ask the bot to tell you the weather (precipitation information) using the weather information API (YOLP) provided by Yahoo ~ slack bot development with python ④ ~
I tried to make the weather forecast on the official line by referring to the weather forecast bot of "Dialogue system made with python".
I made a function to crop the image of python openCV, so please use it.
[Python3] Define a decorator to measure the execution time of a function
I made a slack bot that notifies me of the temperature
[Python] A simple function to find the center coordinates of a circle
I made a program to check the size of a file in Python
Python: I want to measure the processing time of a function neatly
Get the caller of a function in Python
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
[python] How to sort by the Nth Mth element of a multidimensional array
I made a script to record the active window using win32gui of Python
Python Note: The mystery of assigning a variable to a variable
Add a function to return the minimum value (min) to the stack made with Python, but push / pop / min is basic O (1) !!
Try to get the function list of Python> os package
[Python] How to make a list of character strings character by character
Create a Mastodon bot with a function to automatically reply with Python
Add a function to heat transfer + heat input by temperature to heatrapy
[Python3] Call by dynamically specifying the keyword argument of the function
[Python] I asked LINE BOT to answer the weather forecast.
Debug by attaching to the Python process of the SSH destination
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
I made a class to get the analysis result by MeCab in ndarray with python
Procedure from environment construction to operation test of testinfra, a server environment test tool made by Python
How to determine the existence of a selenium element in Python
I want to know the weather with LINE bot feat.Heroku + Python
[Introduction to Python] How to split a character string with the split function
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
[Python] Make the function a lambda function
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
Impressions of touching Dash, a data visualization tool made by python
Create a function to get the contents of the database in Go
I made a Discord chat reading bot by imitating the appearance
Attempt to extend a function in the library (add copy function to pathlib)
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of creating a bot that displays active members in a specific channel of slack with python
I found out by making a python script to record radiko while reading the code of the predecessors
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
Have Alexa run Python to give you a sense of the future
[Python] Explains how to use the range function with a concrete example
[Python] A program that calculates the number of socks to be paired
I'm stunned by the behavior of filter () due to different versions of Python
Various methods to numerically create the inverse function of a certain function Introduction
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[NNabla] How to add a quantization layer to the middle layer of a trained model
How to create a wrapper that preserves the signature of the function to wrap
I tried to verify and analyze the acceleration of Python by Cython
Allow Slack to notify you of the end of a time-consuming program process
[Introduction to Python] How to write a character string with the format function
Find the minimum value of a function by particle swarm optimization (PSO)
Python code to determine the monthly signal of a relative strength investment