csc-cia-stne 0.0.43__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
csc_cia_stne/slack.py ADDED
@@ -0,0 +1,227 @@
1
+ import base64
2
+ from slack_sdk import WebClient
3
+ from pydantic import BaseModel, ValidationError, field_validator
4
+ from typing import Union
5
+
6
+
7
+ class InitParamsValidator(BaseModel):
8
+ """
9
+ Classe para validar os parâmetros de inicialização.
10
+ Atributos:
11
+ - token_slack: Union[str, dict] - O token do Slack, que pode ser uma string ou um dicionário.
12
+ - channel_id: str - O ID do canal do Slack.
13
+ - on_base64: bool - Indica se o token do Slack está em base64.
14
+ Métodos:
15
+ - validate_token_slack(value, info): Valida o token do Slack.
16
+ - validate_token_slack_dict(value, info): Valida o token do Slack quando é um dicionário.
17
+ - validate_token_slack(value, info): Valida o valor de on_base64.
18
+ """
19
+
20
+ token_slack: Union[str, dict]
21
+ channel_id:str
22
+ on_base64:bool
23
+
24
+ """
25
+ Valida o token do Slack.
26
+ Parâmetros:
27
+ - value: str - O valor do token do Slack.
28
+ - info: dict - Informações adicionais sobre o campo.
29
+ Retorna:
30
+ - str: O valor do token do Slack, se for válido.
31
+ Lança:
32
+ - ValueError: Se o valor não for uma string ou estiver vazio.
33
+ """
34
+ @field_validator('channel_id')
35
+ def validate_str(cls, value, info):
36
+ if not isinstance(value, str) or not value.strip():
37
+ raise ValueError(f"O campo '{info.field_name}' deve ser strings e não {type(value)}")
38
+ return value
39
+
40
+ """
41
+ Valida o token do Slack quando é um dicionário.
42
+ Parâmetros:
43
+ - value: dict - O valor do token do Slack.
44
+ - info: dict - Informações adicionais sobre o campo.
45
+ Retorna:
46
+ - dict: O valor do token do Slack, se for válido.
47
+ Lança:
48
+ - ValueError: Se o valor não for um dicionário ou uma string vazia.
49
+ """
50
+ @field_validator('token_slack')
51
+ def validate_dict(cls, value, info):
52
+ if not isinstance(value, dict) and (not isinstance(value, str) or not value.strip()):
53
+ raise ValueError(f"O campo '{info.field_name}' deve ser strings e não {type(value)}")
54
+ return value
55
+
56
+ """
57
+ Valida o valor de on_base64.
58
+ Parâmetros:
59
+ - value: bool - O valor de on_base64.
60
+ - info: dict - Informações adicionais sobre o campo.
61
+ Retorna:
62
+ - bool: O valor de on_base64, se for válido.
63
+ Lança:
64
+ - ValueError: Se o valor não for um booleano.
65
+ """
66
+ @field_validator('on_base64')
67
+ def validate_bool(cls, value, info):
68
+ if not isinstance(value, bool):
69
+ raise ValueError(f"O campo '{info.field_name}' deve ser strings e não {type(value)}")
70
+ return value
71
+
72
+
73
+ class SendSlackMessageParamsValidator(BaseModel):
74
+ """
75
+ Valida os parâmetros para enviar uma mensagem no Slack.
76
+ Atributos:
77
+ - message (str): A mensagem a ser enviada.
78
+ - highlights (list): Uma lista de destaques.
79
+ - files (list): Uma lista de arquivos.
80
+ Métodos:
81
+ - validate_message(value, info): Valida o campo 'message' para garantir que seja uma string não vazia.
82
+ - validate_list(value, info): Valida os campos 'highlights' e 'files' para garantir que sejam listas.
83
+ """
84
+
85
+ message:str
86
+ highlights:list
87
+ file_list:list
88
+
89
+ @field_validator('message')
90
+ def validate_message(cls, value, info):
91
+ if not isinstance(value, str) or not value.strip():
92
+ raise ValueError(f"O campo '{info.field_name}' deve ser strings e não {type(value)}")
93
+ return value
94
+
95
+ @field_validator('highlights','file_list')
96
+ def validate_list(cls, value, info):
97
+ if not isinstance(value, list):
98
+ raise ValueError(f"O campo '{info.field_name}' deve ser strings e não {type(value)}")
99
+ return value
100
+
101
+
102
+ class Slack():
103
+
104
+
105
+ def __init__(self, token_slack:Union[str, dict], channel_id, on_base64:bool=False):
106
+ """
107
+ Inicializa a classe Slack.
108
+ Parâmetros:
109
+ - token_slack (str): O token de autenticação do Slack.
110
+ - base64 (bool, opcional): Indica se o token_slack está codificado em base64. O padrão é False.
111
+ """
112
+
113
+ self.token_slack = token_slack
114
+ self.on_base64 = on_base64
115
+ self.channel_id = channel_id
116
+
117
+ try:
118
+
119
+ InitParamsValidator(token_slack=token_slack, on_base64=on_base64,channel_id=channel_id)
120
+
121
+ except ValidationError as e:
122
+
123
+ raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
124
+
125
+ if self.on_base64:
126
+
127
+ self.token_slack = base64.b64decode(self.token_slack).decode('utf-8')
128
+
129
+ self.client = WebClient(self.token_slack)
130
+
131
+
132
+ def send_message(self, message:str, highlights:list=[] , file_list:list=[]):
133
+ """
134
+ Envia uma mensagem para o canal do Slack.
135
+ Parâmetros:
136
+ - message: str - A mensagem a ser enviada.
137
+ - highlights: list - Uma lista de destaques (attachments) a serem exibidos junto com a mensagem.
138
+ - files: list (opcional) - Uma lista de arquivos a serem anexados à mensagem.
139
+ Retorna:
140
+ Um dicionário com as seguintes chaves:
141
+ - status: bool - Indica se o envio da mensagem foi bem-sucedido.
142
+ - message: dict - A resposta da API do Slack contendo informações sobre a mensagem enviada.
143
+ - success_attachments: list - Uma lista dos anexos que foram enviados com sucesso.
144
+ - failed_success_attachments: list - Uma lista dos anexos que falharam ao serem enviados.
145
+ Caso ocorra algum erro durante o envio da mensagem, o dicionário terá a seguinte estrutura:
146
+ - status: bool - Indica se ocorreu um erro durante o envio da mensagem.
147
+ - error: dict - A resposta da API do Slack contendo informações sobre o erro ocorrido.
148
+ - success_attachments: list - Uma lista dos anexos que foram enviados com sucesso.
149
+ - failed_attachments: list - Uma lista dos anexos que falharam ao serem enviados.
150
+ """
151
+
152
+ try:
153
+
154
+ SendSlackMessageParamsValidator(message=message, highlights=highlights, file_list=file_list)
155
+
156
+ except ValidationError as e:
157
+
158
+ raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
159
+
160
+
161
+ failed_attachments = []
162
+
163
+ success_attachments = []
164
+
165
+ result_message = self.client.chat_postMessage(
166
+ channel=self.channel_id,
167
+ text=message,
168
+ blocks=[
169
+ {
170
+ "type": "section",
171
+ "text": {
172
+ "type": "mrkdwn",
173
+ "text": message
174
+ }
175
+ },
176
+ ],
177
+ attachments=highlights
178
+ )
179
+
180
+ if file_list is not None and len(file_list) > 0:
181
+
182
+ # validar os arquivos anexados
183
+
184
+ for file_item in file_list:
185
+
186
+ if 'title' in file_item and 'file' in file_item:
187
+
188
+ if file_item['title'] is not None and len(str(file_item['title']).replace(" ","")) > 0 and file_item['file'] is not None and len(str(file_item['file']).replace(" ","")) > 0:
189
+
190
+ success_attachments.append(file_item)
191
+
192
+ else:
193
+
194
+ failed_attachments.append(file_item)
195
+
196
+ else:
197
+
198
+ failed_attachments.append(file_item)
199
+
200
+ if len(success_attachments) > 0:
201
+
202
+ # Enviar mensagem com anexos
203
+
204
+ result_message = self.client.files_upload_v2(
205
+ channel=self.channel_id,
206
+ initial_comment="anexos",
207
+ file_uploads=success_attachments
208
+ )
209
+
210
+ if result_message.get('ok', True):
211
+
212
+ return {
213
+ 'status':True,
214
+ 'message':result_message,
215
+ 'success_attachments':success_attachments,
216
+ 'failed_success_attachments':failed_attachments
217
+ }
218
+
219
+ else:
220
+
221
+ return {
222
+ 'status':False,
223
+ 'error':result_message,
224
+ 'success_attachments':success_attachments,
225
+ 'failed_attachments':failed_attachments
226
+ }
227
+