[PYTHON] What I found in "Mention to people who have not pressed reaction using slack API" [Mainly about json]

Overview

As the title says. I will summarize what you should be careful about when dealing with json mainly in python.

What I wanted to do (as shown in the image below)

① Get a member of slack (member_list.py) (2) Send a message with the API according to the attendance at the scheduled start. (postMessage.py) ③ Members react. ④ Get the person who reacted to ② above with the API. (Reac_result.py) ⑤ Create a list without pressing reaction. ⑥ Mention the list created in ⑤ above with API. (PostMessage_re.py)

01.jpg

Excerpts from what I found (①, ②, ④, ⑤, ⑥)

Code excerpt in ①, what I understood

■ The value of the dictionary (dict type object) can be extracted by selecting it with the key. The code below tries to extract the name from the obtained response.

def_member_list.py


    r = requests.get(url, params=payload)
    result_mem = []  #Prepare a list to put the results
    json_data = r.json()
    members = json_data["members"] 
    for i in members:
        result_mem.append(i["real_name"])#Add results
    ppront.pprint(result_mem)#['Slackbot']

json_data.


#json_The following data is stored in data.
{"ok": true,
"members": [ {"id": "USLACKBOT","team_id": "T012YMJ67V1","real_name": "Slackbot"

d = {'key1': 'aaa', 'key2': 'bbb', 'key3': 'ccc'} value = d['key1'] print(value) #aaa That is, {"key": value,}

** So, if you want to get the value ("Slackbot"), specify the key ("real_name"). ** **

Code excerpt in ②, what I understood

■ If you want to return an arbitrary value from the function to the caller of the function, you can use return. The code below tries to extract the time stamp from the obtained response.

def_postMessage.py


def postMessage():
    r = requests.post(url, params=payload)
    result_text = []  #Prepare a list to put the results
    json_data = r.json()
    ts = json_data['ts']
    return (ts)

postMessage.py


import datetime
import def_postMessage
a = def_postMessage.postMessage()
with open(str(datetime.date.today())+'_ts.txt', mode='a') as f:
    print(a,file=f)

The ts (timestamp) obtained by def_postMessage.py is the return value, which is used by postMessage.py. Since ts is unique in slack, you can identify the message.

Code excerpt in ④, what I understood

■ When nesting, if you want to get the value, you need to understand the structure of JSON ■ Reference is site here ■ Variables can be specified for the return value of return The code below tries to extract the person who reacted from the received response.

def_reaction.py


def reaction():
    r = requests.get(url, params=payload)
    json_data = r.json()
    reac_tmp1 = json_data['messages'][0]['reactions'][0]['users']
    reac_tmp2 = json_data['messages'][0]['reactions'][1]['users']
    reac_tmp3 = json_data['messages'][0]['reactions'][2]['users']
return(reac_tmp1,reac_tmp2,reac_tmp3)

json_data.


{'channel_actions_count': 0,
 'channel_actions_ts': None,
 'messages': [{'bot_id': 'B012YMHEVJN',
               'bot_profile': {'app_id': 'A0134SP1ZA8',
                               'id': 'B012YMHEVJN',
                               'name': 'test',
                               'team_id': 'T012YMJ67V1',
               'reactions': [{'count': 3,
                              'name': 'syukkin',
                              'users': ['U012JDYRD2T',
                                        'U013BQDLK6V',
                                        'U012ZC8AQ8K']},
                             {'count': 2,
                              'name': 'tikoku',
                              'users': ['U012XQBE63X', 'U012JDYSN07']},
                             {'count': 1,
                              'name': 'kekkin',
                              'users': ['U012JDYSN07']}]

■ What you are doing (when reac_tmp1 = json_data ['messages'] [0] ['reactions'] [0] ['users']) (1) Specify the variable name json_data (2) Since you want to access the'messages' property in it, specify [" messages "]. (3) An array of objects is stored in messages. Here, we will access the first object in the array, so specify [0]. (Access all of ['messages': [{'bot_id'] and so on) ④ Specify [" reactions "] to access the'reactions' property in the object. ⑤ I want the first of them, so write [0]. ([1] if you want a second, [2] if you want a third) ⑥ Specify [" users "] to access the'users' property in the object.

In other words ** The members (users) who made the reactions of the sent message are stored in reac_tmp. ** ** (There are 3 reac_tmp1-3, [Attendance], [Late], and [Absent], and I want to know who has made these 3 reactions.)

Code excerpt in ⑤, what I found

Posted in another article. https://qiita.com/nonono_kita/items/588ad61431e97724deab

Code excerpt in ⑥, what I found out

Posted in another article. https://qiita.com/nonono_kita/items/e83a3b918aa572b69adf

What you want to do in the future, what you can do

-Conditional branching for errors. -Process to prepare a DB and update it based on the information of the member who pressed the reaction. -Processing to mention the person who has not pressed the reaction after the update process.

Task

■ No conditional branch is prepared. for that reason -Error if there is no reaction in the message ・ Error if there are few reactions in the message -Error if the output file does not exist -Error if the output file name is different

What I thought

-When you get the data with json, it seems better to output it to the data once rather than processing the data in the function or process. Output and process the necessary data after that. That is more likely to use the function. ・ Since the article will be longer, it may be better to write an article for each item.

Recommended Posts

What I found in "Mention to people who have not pressed reaction using slack API" [Mainly about json]
[Python] Mention to multiple people with Slack API
Machine learning A story about people who are not familiar with GBDT using GBDT in Python