<reponame>singleview-co-kr/django_etl<filename>svcommon/sv_slack.py
# pip install requests
import requests
from django.conf import settings
from slack_cleaner2 import *

# for logger
# import logging
# logger = logging.getLogger(__name__)  __file__ # logger.debug('debug msg')


class SvSlack:
	""" bot notice through slack messenger class for singleview only """
	# https://somjang.tistory.com/entry/Python-Slack-WebHooks-%EC%9D%84-%ED%86%B5%ED%95%B4-%EC%9E%91%EC%97%85-%EC%A7%84%ED%96%89%EC%83%81%ED%99%A9-%EC%95%8C%EB%A6%BC-%EB%B0%9B%EC%95%84%EB%B3%B4%EA%B8%B0-feat-Incoming-WebHooks
	# https://lsjsj92.tistory.com/594

	def __init__(self):
		# print(__file__ + ':' + sys._getframe().f_code.co_name)
		super().__init__()

	def send_msg(self, s_msg):
		if len(s_msg):
			dict_msg_body = {"channel": settings.SLACK_CHANNEL, "username": settings.SLACK_BOT_NAME, "text": s_msg}
			webhook_url = settings.SLACK_WEB_HOOK_URL
			response = requests.post(
				webhook_url, json=dict_msg_body, headers={'Content-Type': 'application/json'}
			)
			if response.status_code != 200:
				raise ValueError(
					'Request to slack returned an error %s, the response is:\n%s' % (response.status_code, response.text)
				)
		else:
			print(__file__ + ' has requested to send blank message!')

	def delete_all(self, s_channel_name):
		"""
		슬랙 메세지 일괄 삭제 https://brown.ezphp.net/entry/Slack-%EC%B1%84%EB%84%90-%EA%B8%B0%EB%A1%9D-%EC%9D%BC%EA%B4%84-%EC%82%AD%EC%A0%9C
		. https://api.slack.com/apps 접속
		. Create New App 버튼을 통해 App 이름과 Slack Workspace 지정
		. OAuth & Permissions 사이드 메뉴 선택
		. 중간 부분의 User Token Scopes에 해당하는 권한 추가
		users:read
		channels:read
		channels:history
		chat:write
		files:write
		. 상단의 Install App to Workspace 버튼으로 App 설치
		. permission 요청 수락 (Allow)
		. OAuth Access Token 복사해서 ./settings.py에 SLACK_USER_OAUTH_TOKEN 에 저장
		. pip install slack-cleaner2
		:return:
		"""
		s = SlackCleaner(settings.SLACK_USER_OAUTH_TOKEN)
		# list of users
		print(s.users)
		# list of all kind of channels
		# print(s.conversations)

		# s.conversations returns <class 'slack_cleaner2.model.SlackChannel'>
		lst_channels = [str(o_slack_ch) for o_slack_ch in s.conversations]
		if s_channel_name not in lst_channels:
			print('invalid channel title')
			return

		# delete all messages in general channels
		for msg in s.msgs(filter(match(s_channel_name), s.conversations)):
			# delete messages, its files, and all its replies (thread)
			msg.delete(replies=True, files=True)

		# delete all general messages and also iterate over all replies
		for msg in s.c.general.msgs(with_replies=True):
			msg.delete()

# pip install requests
import requests
from django.conf import settings
from slack_cleaner2 import *

# for logger
# import logging
# logger = logging.getLogger(__name__)  __file__ # logger.debug('debug msg')


class SvSlack:
	""" bot notice through slack messenger class for singleview only """
	# https://somjang.tistory.com/entry/Python-Slack-WebHooks-%EC%9D%84-%ED%86%B5%ED%95%B4-%EC%9E%91%EC%97%85-%EC%A7%84%ED%96%89%EC%83%81%ED%99%A9-%EC%95%8C%EB%A6%BC-%EB%B0%9B%EC%95%84%EB%B3%B4%EA%B8%B0-feat-Incoming-WebHooks
	# https://lsjsj92.tistory.com/594

	def __init__(self):
		# print(__file__ + ':' + sys._getframe().f_code.co_name)
		super().__init__()

	def send_msg(self, s_msg):
		if len(s_msg):
			dict_msg_body = {"channel": settings.SLACK_CHANNEL, "username": settings.SLACK_BOT_NAME, "text": s_msg}
			webhook_url = settings.SLACK_WEB_HOOK_URL
			response = requests.post(
				webhook_url, json=dict_msg_body, headers={'Content-Type': 'application/json'}
			)
			if response.status_code != 200:
				raise ValueError(
					'Request to slack returned an error %s, the response is:\n%s' % (response.status_code, response.text)
				)
		else:
			print(__file__ + ' has requested to send blank message!')

	def delete_all(self, s_channel_name):
		"""
		슬랙 메세지 일괄 삭제 https://brown.ezphp.net/entry/Slack-%EC%B1%84%EB%84%90-%EA%B8%B0%EB%A1%9D-%EC%9D%BC%EA%B4%84-%EC%82%AD%EC%A0%9C
		. https://api.slack.com/apps 접속
		. Create New App 버튼을 통해 App 이름과 Slack Workspace 지정
		. OAuth & Permissions 사이드 메뉴 선택
		. 중간 부분의 User Token Scopes에 해당하는 권한 추가
		users:read
		channels:read
		channels:history
		chat:write
		files:write
		. 상단의 Install App to Workspace 버튼으로 App 설치
		. permission 요청 수락 (Allow)
		. OAuth Access Token 복사해서 ./settings.py에 SLACK_USER_OAUTH_TOKEN 에 저장
		. pip install slack-cleaner2
		:return:
		"""
		s = SlackCleaner(settings.SLACK_USER_OAUTH_TOKEN)
		# list of users
		print(s.users)
		# list of all kind of channels
		# print(s.conversations)

		# s.conversations returns <class 'slack_cleaner2.model.SlackChannel'>
		lst_channels = [str(o_slack_ch) for o_slack_ch in s.conversations]
		if s_channel_name not in lst_channels:
			print('invalid channel title')
			return

		# delete all messages in general channels
		for msg in s.msgs(filter(match(s_channel_name), s.conversations)):
			# delete messages, its files, and all its replies (thread)
			msg.delete(replies=True, files=True)

		# delete all general messages and also iterate over all replies
		for msg in s.c.general.msgs(with_replies=True):
			msg.delete()
# pip install requests # for logger # import logging # logger = logging.getLogger(__name__)  __file__ # logger.debug('debug msg') bot notice through slack messenger class for singleview only # https://somjang.tistory.com/entry/Python-Slack-WebHooks-%EC%9D%84-%ED%86%B5%ED%95%B4-%EC%9E%91%EC%97%85-%EC%A7%84%ED%96%89%EC%83%81%ED%99%A9-%EC%95%8C%EB%A6%BC-%EB%B0%9B%EC%95%84%EB%B3%B4%EA%B8%B0-feat-Incoming-WebHooks # https://lsjsj92.tistory.com/594 # print(__file__ + ':' + sys._getframe().f_code.co_name) 슬랙 메세지 일괄 삭제 https://brown.ezphp.net/entry/Slack-%EC%B1%84%EB%84%90-%EA%B8%B0%EB%A1%9D-%EC%9D%BC%EA%B4%84-%EC%82%AD%EC%A0%9C 		. https://api.slack.com/apps 접속 		. Create New App 버튼을 통해 App 이름과 Slack Workspace 지정 		. OAuth & Permissions 사이드 메뉴 선택 		. 중간 부분의 User Token Scopes에 해당하는 권한 추가 		users:read 		channels:read 		channels:history 		chat:write 		files:write 		. 상단의 Install App to Workspace 버튼으로 App 설치 		. permission 요청 수락 (Allow) 		. OAuth Access Token 복사해서 ./settings.py에 SLACK_USER_OAUTH_TOKEN 에 저장 		. pip install slack-cleaner2 		:return: # list of users # list of all kind of channels # print(s.conversations) # s.conversations returns <class 'slack_cleaner2.model.SlackChannel'> # delete all messages in general channels # delete messages, its files, and all its replies (thread) # delete all general messages and also iterate over all replies