I want to improve efficiency with Python even in the experimental system (5) I want to send a notification at the end of the experiment with the slack API

Synopsis up to the last time

Up to the last time, automatic measurement has become possible in consideration of errors. This time, we will use slack's API to notify slack of the end of measurement. Even with other chat tools (Discord, Line, etc.), the flow of acquiring tokens and sending requests to the API is the same, so I think that it can be used for various purposes.

environment

What you are doing

The python slackclient package didn't work in my environment, so

--Send a message to Slack from python --Qiita -How to send to Slack using Python --Qiita

With reference to

--using the requests package --Using the token obtained from the slack web page

You can send any message to any channel using the slack API. What should be changed in the code below

You should be able to send it only

How to add mention

-How to skip mentions with Incoming Webhooks in Slack --Qiita

Please refer to this site

import serial
import time
import pandas as pd

##Constant specification
MAX = 40000
COMampere = "COM10"
COMpulse = "COM9"
bitRate = 9600
##Variable initialization
pulse = 0
ampere_list = []
pulse_list = []
ampere_average_list =[]
##Move to the back origin(Initialization)
ser = serial.Serial(COMsigma, bitRate, timeout=0.1)

ser.write(b"H:2-\r\n")

# time.sleep(0.1)
# print(ser.read_all())

ser.close()

import requests

class SlackDriver:
    def __init__(self, _token):
        self._token = _token  # api_token
        self._headers = {'Content-Type': 'application/json'}

    def send_message(self, message, channel):
        params = {"token": self._token, "channel": channel, "text": message}

        r = requests.get('https://slack.com/api/chat.postMessage',
                          headers=self._headers,
                          params=params)
        print("return ", r.json())
token = 'xxxx-oooooooooooo-000000000000-hogehoge' #Please use the token you got this part
slack = SlackDriver(token)
#Start measurement
try:
    while 1:
        if pulse >= MAX:
            ##End the while statement when the position reaches MAX
            break
        if pulse ==2000:
            slack.send_message("<@IDhogehoge>1000 is over", "#bot-test") #The acquired ID is<>Please enclose
        if pulse ==30000:
            slack.send_message("<@IDhogehoge>15000 is over", "#bot-test")
        ##Record current location information
        pulse_list.append(pulse/2)
        ##Measure the current(Take 5 times and average it as the value at that position)
        for i in range(5):
            ser = serial.Serial(COMampere,bitRate,timeout=0.1)
            ser.write(b"F5, R0,PR2\r\n")
            time.sleep(1)
            ser.write(b"MD?\r\n")
            time.sleep(1)
            tmp = ser.read_all()
            #Skip if no current is available
            if len(tmp)== 0:
                ser.close()
                continue
            ampere = float(tmp.split()[2])
            ampere_average_list.append(ampere)
            time.sleep(1)
            ser.close()
        ##Current and pulse(position)To list
        ampere_list.append(sum(ampere_average_list)/len(ampere_average_list))
        ampere_average_list = []

        ##Move the optical table
        pulse += 1000
        position = "A:2+P"+str(pulse)+"\r\n"
        ser = serial.Serial(COMpulse,bitRate,timeout=0.1)
        ser.write(bytes(position, 'UTF-8'))
        time.sleep(1)
        ser.write(b"G:\r\n")
        ser.close()

    ##Turn the list into a dataframe
    print(ampere_list)
    print(pulse_list)
    df = pd.DataFrame({'ampere(A)':ampere_list,'pulse':pulse_list})
    def pulseToMilliMeter(pulse):
        return pulse*0.006
    df["position(mm)"] = df["pulse"].map(pulseToMilliMeter)
    df.to_csv('./csv/result.csv',index=False)
    plt.figure()
    df.plot(x='position(mm)',y='ampere(A)',marker='o')
    plt.savefig('./img/sample.png')
    plt.close('all')
except IndexError:
    ser.close()
    slack.send_message("<@IDhogehoge>The measurement has failed", "#bot-test")
#I want to notify slack
slack.send_message("<@IDhogehoge>The measurement is over", "#bot-test")

##Variable initialization
pulse = 0
ampere_list = []
pulse_list = []
ampere_average_list =[]
##Move to the back origin(Initialization)
ser = serial.Serial(COMpulse, bitRate, timeout=0.1)

ser.write(b"H:2-\r\n")

time.sleep(0.1)
print(ser.read_all())

ser.close()

Recommended Posts

I want to improve efficiency with Python even in the experimental system (5) I want to send a notification at the end of the experiment with the slack API
I want to improve efficiency with Python even in an experimental system (2) RS232C and pySerial
I want to improve efficiency with Python even in an experimental system (1) Install Anaconda with Chocolatey
I want to improve efficiency with Python even in an experimental system (3) I want to do something like Excel with Pandas
I want to improve efficiency with Python even in an experimental system (4) Use ser.close () when an error is thrown using try syntax
I tried to improve the efficiency of daily work with Python
I want to work with a robot in python.
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I want to output the beginning of the next month with Python
How to send a request to the DMM (FANZA) API with python
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I tried to get the authentication code of Qiita API with Python.
I want to sort a list in the order of other lists
I want to color a part of an Excel string in Python
I tried to get the movie information of TMDb API with Python
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
I want to make a game with Python
Send Gmail at the end of the process [Python]
Sample to send slack notification with python lambda
I want to write to a file with Python
I want to display the progress in Python!
[LINE Messaging API] I want to send a message from the program to everyone's LINE
How to mention a user group in slack notification, how to check the id of the user group
The story of IPv6 address that I want to keep at a minimum
I want to send Gmail with Python, but I can't because of an error
To output a value even in the middle of a cell with Jupyter Notebook
I want to set a life cycle in the task definition of ECS
I want to see a list of WebDAV files in the Requests module
To automatically send an email with an attachment using the Gmail API in Python
How to get a list of files in the same directory with python
I tried to automatically send the literature of the new coronavirus to LINE with Python
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
[Python & SQLite] I tried to analyze the expected value of a race with horses in the 1x win range ①
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to transition with a button in flask
I want to write in Python! (2) Let's write a test
[Python] I made a system to introduce "recipes I really want" from the recipe site!
Even in JavaScript, I want to see Python `range ()`!
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I'm tired of Python, so I tried to analyze the data with nehan (I want to go live even with corona sickness-Part 2)
I want to write in Python! (3) Utilize the mock
I'm tired of Python, so I tried to analyze the data with nehan (I want to go live even with corona sickness-Part 1)
I want to use the R dataset in python
I want to run a quantum computer with Python
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
Make a note of what you want to do in the future with Raspberry Pi
I made a class to get the analysis result by MeCab in ndarray with python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I also tried to imitate the function monad and State monad with a generator in Python
How to insert a specific process at the start and end of spider with scrapy
I tried to find the entropy of the image with python
I want to specify another version of Python with pyvenv
I want to start a lot of processes from python
I evaluated the strategy of stock system trading with Python.
Send experiment results (text and images) to slack with Python
[Python] I want to use the -h option with argparse