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 | 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]( % 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 to hit the modular

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

The current should look like this:

# coding: utf-8

from import respond_to     # @botname:Decoder that reacts with
from import listen_to      #Decoder that responds to in-channel remarks
from 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
def mention_func(message):
    message.reply('What do you do when you say mention to me') #Mention

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

import pya3rt
def send_message(message):
    client = pya3rt.TalkClient(apikey)
    reply_message =['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
def confirm_today_weather(message, something):
    weather_class = ConfirmWeather()

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

import json
import subprocess
import os

class ConfirmWeather():

    def __init__(self):

    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, "")
#Store the execution result of the shell script placed in the same directory in a variable
        weather_info = subprocess.check_output(cmd)
#POST to slack
        message.send("I'll tell you the weather today")

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) 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 in the same directory Don't forget

curl -s | 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, 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