หน้าเว็บ

วันพุธที่ 27 พฤศจิกายน พ.ศ. 2562

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Run ที่เครื่องที่ออกเน็ต ได้ ในที่นี้ใช้เครื่อง Extranet
1. ติดตั้งโปรแกรม
  1. sudo apt-get install python-pip

2. ติดตั้ง Slack Client
  1. pip install slackclient
3. สร้าง code removeSlack.py
  1. from slackclient import SlackClient
  2. #from time import sleep
  3. import time
  4. #import datetime
  5. from datetime import datetime, timedelta
  6.  
  7. legacy_token = 'xxxxxx'  # don't if you share your code
  8. channel = 'Cxxxxx'  # the id of the channel to delete all msgs inside
  9.  
  10. sc = SlackClient(legacy_token)
  11. response = sc.api_call('channels.info', channel=channel)
  12.  
  13. #oldest_ts = response['channel']['created']
  14. date_days_ago = datetime.now() - timedelta(days=60)
  15. oldest_ts = time.mktime(date_days_ago.timetuple())
  16. print(datetime.fromtimestamp(oldest_ts))
  17.  
  18. date_days_ago = datetime.now() - timedelta(days=30)
  19. latest_ts = time.mktime(date_days_ago.timetuple())
  20. print(datetime.fromtimestamp(latest_ts))
  21.  
  22. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  23. allmsgs = [item['ts'] for item in response['messages']]
  24. print(len(allmsgs))
  25. for msg in allmsgs:
  26.     sc.api_call('chat.delete', channel=channel, ts=msg)
  27.     time.sleep(1)
  28. ########### Chanel Server  ###################
  29. channel = 'Cxxxxx'
  30.  
  31. sc = SlackClient(legacy_token)
  32. response = sc.api_call('channels.info', channel=channel)
  33.  
  34. #oldest_ts = response['channel']['created']
  35. date_days_ago = datetime.now() - timedelta(days=60)
  36. oldest_ts = time.mktime(date_days_ago.timetuple())
  37. print(datetime.fromtimestamp(oldest_ts))
  38.  
  39. date_days_ago = datetime.now() - timedelta(days=30)
  40. latest_ts = time.mktime(date_days_ago.timetuple())
  41. print(datetime.fromtimestamp(latest_ts))
  42.  
  43. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  44. allmsgs = [item['ts'] for item in response['messages']]
  45. print(len(allmsgs))
  46. for msg in allmsgs:
  47.     sc.api_call('chat.delete', channel=channel, ts=msg)
  48.     time.sleep(1)
4. chmod ให้ Run ได้
5. สร้าง Cront ให้ run ตามที่ต้องการในที่นี้ run อาทิตย์ละครั้ง วันจันทร์
0 0 * * 1 python /home/pi/removeSlak.py >> /home/pi/removeSlack.log 2>&1

ไม่มีความคิดเห็น:

แสดงความคิดเห็น