[PYTHON] Detect over-retained MSG in Rocket Chat

There are cases where you want to operate RocketChat without storing messages for a long time. I don't want to have a lot of chat messages that look like emails, and it also encourages me to put together a chat conclusion on the wiki.

REST

Use /api/v1/channels.messages. It's convenient to bring it in a sled.

Output is dataframe

Since I have created a helper function for RocketChat posting separately, I am returning it with DataFrame.

Just a little attention

There is an upper limit on the number of API acquisitions in RocketChat by default. It is necessary to take measures such as performing this mitigation or looping with offset.

import requests
import pandas as pd
import datetime
import dateutil.parser

from pprint import pprint

#API parameters
HEADERS ={
    'X-Auth-Token': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'X-User-Id': 'xxxxxxxxxxtZDz',
    'Content-Type': 'application/json',
}

params = (
    ('roomId', 'GENERAL'),
)

#Message retention period
LIMIT = 1

#Helper function definition
'''ISO ->datetime type'''
def ISOtimeToDatetime(target):
    JST = datetime.timezone(datetime.timedelta(hours=+9), 'JST')
    return dateutil.parser.parse(target).astimezone(JST)

def judgeRocketChatMessage(target_date, limit):
    '''Retention period judgment'''
    today = datetime.date.today()
    diff_date = datetime.timedelta(limit)

    __DEBUG__ = False    
    if __DEBUG__:
        print(target_date.date())
        print(today)
        print(diff_date)
        print(today - target_date.date())
    
    return (today - target_date.date() > diff_date)

#Request execution
##TODO try ~ except processing
response = requests.get('http://xxx.xxx.xxx.xxx:3000/api/v1/channels.messages', 
                         headers=HEADERS, 
                         params=params)
#Check the result
pprint(response)
pprint(len(response.json()['messages']))

#Return the deletion target judgment result in DataFrame
_list = []
for _ in response.json()['messages']:
    # TODO _['_updatedAt']And the comparison with the current time
    #It is more efficient to perform at this timing and determine the deletion target.
    _list.append([_['rid'],
                  _['_id'], 
                  ISOtimeToDatetime(_['_updatedAt']),
                  judgeRocketChatMessage(ISOtimeToDatetime(_['_updatedAt']), LIMIT),
                  _['msg']])
#DataFrame conversion
df = pd.DataFrame(_list)
df.columns = ['Channel','MSG_ID','Update time','Target to be deleted','MSG']

Click here for results

df.head(5)
df.query('Target to be deleted== True').head(5)

Recommended Posts

Detect over-retained MSG in Rocket Chat
Detect keystrokes in python (tty)