chatgraph 0.2.5__py3-none-any.whl → 0.3.0__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.

Potentially problematic release.


This version of chatgraph might be problematic. Click here for more details.

@@ -0,0 +1,32 @@
1
+ syntax = "proto3";
2
+
3
+ package messagevoll;
4
+
5
+ option go_package = "./pb/messagevoll";
6
+
7
+ service MessageService {
8
+ rpc SendButton(MessageRequest) returns (MessageResponse);
9
+ rpc SendList(MessageRequest) returns (MessageResponse);
10
+ rpc SendText(MessageRequest) returns (MessageResponse);
11
+ }
12
+
13
+ message MessageRequest {
14
+ string hook_id = 1;
15
+ string enterprise_id = 2;
16
+ string unique_customer_id = 3;
17
+ string message_title = 4;
18
+ string message_text = 5;
19
+ string message_caption = 6;
20
+ string button_title = 7;
21
+ repeated QuickOption options = 8;
22
+ }
23
+
24
+ message MessageResponse {
25
+ bool status = 1;
26
+ string message = 2;
27
+ }
28
+
29
+ message QuickOption {
30
+ string title = 1;
31
+ string description = 2;
32
+ }
@@ -0,0 +1,43 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: voll.proto
5
+ # Protobuf Python Version: 5.27.2
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 5,
15
+ 27,
16
+ 2,
17
+ '',
18
+ 'voll.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+
26
+
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\nvoll.proto\x12\x0bmessagevoll\"\xdb\x01\n\x0eMessageRequest\x12\x0f\n\x07hook_id\x18\x01 \x01(\t\x12\x15\n\renterprise_id\x18\x02 \x01(\t\x12\x1a\n\x12unique_customer_id\x18\x03 \x01(\t\x12\x15\n\rmessage_title\x18\x04 \x01(\t\x12\x14\n\x0cmessage_text\x18\x05 \x01(\t\x12\x17\n\x0fmessage_caption\x18\x06 \x01(\t\x12\x14\n\x0c\x62utton_title\x18\x07 \x01(\t\x12)\n\x07options\x18\x08 \x03(\x0b\x32\x18.messagevoll.QuickOption\"2\n\x0fMessageResponse\x12\x0e\n\x06status\x18\x01 \x01(\x08\x12\x0f\n\x07message\x18\x02 \x01(\t\"1\n\x0bQuickOption\x12\r\n\x05title\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t2\xe7\x01\n\x0eMessageService\x12G\n\nSendButton\x12\x1b.messagevoll.MessageRequest\x1a\x1c.messagevoll.MessageResponse\x12\x45\n\x08SendList\x12\x1b.messagevoll.MessageRequest\x1a\x1c.messagevoll.MessageResponse\x12\x45\n\x08SendText\x12\x1b.messagevoll.MessageRequest\x1a\x1c.messagevoll.MessageResponseB\x12Z\x10./pb/messagevollb\x06proto3')
28
+
29
+ _globals = globals()
30
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'voll_pb2', _globals)
32
+ if not _descriptor._USE_C_DESCRIPTORS:
33
+ _globals['DESCRIPTOR']._loaded_options = None
34
+ _globals['DESCRIPTOR']._serialized_options = b'Z\020./pb/messagevoll'
35
+ _globals['_MESSAGEREQUEST']._serialized_start=28
36
+ _globals['_MESSAGEREQUEST']._serialized_end=247
37
+ _globals['_MESSAGERESPONSE']._serialized_start=249
38
+ _globals['_MESSAGERESPONSE']._serialized_end=299
39
+ _globals['_QUICKOPTION']._serialized_start=301
40
+ _globals['_QUICKOPTION']._serialized_end=350
41
+ _globals['_MESSAGESERVICE']._serialized_start=353
42
+ _globals['_MESSAGESERVICE']._serialized_end=584
43
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,183 @@
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+ import warnings
5
+
6
+ import chatgraph.pb.voll_pb2 as voll__pb2
7
+
8
+ GRPC_GENERATED_VERSION = '1.66.2'
9
+ GRPC_VERSION = grpc.__version__
10
+ _version_not_supported = False
11
+
12
+ try:
13
+ from grpc._utilities import first_version_is_lower
14
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
15
+ except ImportError:
16
+ _version_not_supported = True
17
+
18
+ if _version_not_supported:
19
+ raise RuntimeError(
20
+ f'The grpc package installed is at version {GRPC_VERSION},'
21
+ + f' but the generated code in voll_pb2_grpc.py depends on'
22
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
23
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
24
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
25
+ )
26
+
27
+
28
+ class MessageServiceStub(object):
29
+ """Missing associated documentation comment in .proto file."""
30
+
31
+ def __init__(self, channel):
32
+ """Constructor.
33
+
34
+ Args:
35
+ channel: A grpc.Channel.
36
+ """
37
+ self.SendButton = channel.unary_unary(
38
+ '/messagevoll.MessageService/SendButton',
39
+ request_serializer=voll__pb2.MessageRequest.SerializeToString,
40
+ response_deserializer=voll__pb2.MessageResponse.FromString,
41
+ _registered_method=True)
42
+ self.SendList = channel.unary_unary(
43
+ '/messagevoll.MessageService/SendList',
44
+ request_serializer=voll__pb2.MessageRequest.SerializeToString,
45
+ response_deserializer=voll__pb2.MessageResponse.FromString,
46
+ _registered_method=True)
47
+ self.SendText = channel.unary_unary(
48
+ '/messagevoll.MessageService/SendText',
49
+ request_serializer=voll__pb2.MessageRequest.SerializeToString,
50
+ response_deserializer=voll__pb2.MessageResponse.FromString,
51
+ _registered_method=True)
52
+
53
+
54
+ class MessageServiceServicer(object):
55
+ """Missing associated documentation comment in .proto file."""
56
+
57
+ def SendButton(self, request, context):
58
+ """Missing associated documentation comment in .proto file."""
59
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
60
+ context.set_details('Method not implemented!')
61
+ raise NotImplementedError('Method not implemented!')
62
+
63
+ def SendList(self, request, context):
64
+ """Missing associated documentation comment in .proto file."""
65
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
66
+ context.set_details('Method not implemented!')
67
+ raise NotImplementedError('Method not implemented!')
68
+
69
+ def SendText(self, request, context):
70
+ """Missing associated documentation comment in .proto file."""
71
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
72
+ context.set_details('Method not implemented!')
73
+ raise NotImplementedError('Method not implemented!')
74
+
75
+
76
+ def add_MessageServiceServicer_to_server(servicer, server):
77
+ rpc_method_handlers = {
78
+ 'SendButton': grpc.unary_unary_rpc_method_handler(
79
+ servicer.SendButton,
80
+ request_deserializer=voll__pb2.MessageRequest.FromString,
81
+ response_serializer=voll__pb2.MessageResponse.SerializeToString,
82
+ ),
83
+ 'SendList': grpc.unary_unary_rpc_method_handler(
84
+ servicer.SendList,
85
+ request_deserializer=voll__pb2.MessageRequest.FromString,
86
+ response_serializer=voll__pb2.MessageResponse.SerializeToString,
87
+ ),
88
+ 'SendText': grpc.unary_unary_rpc_method_handler(
89
+ servicer.SendText,
90
+ request_deserializer=voll__pb2.MessageRequest.FromString,
91
+ response_serializer=voll__pb2.MessageResponse.SerializeToString,
92
+ ),
93
+ }
94
+ generic_handler = grpc.method_handlers_generic_handler(
95
+ 'messagevoll.MessageService', rpc_method_handlers)
96
+ server.add_generic_rpc_handlers((generic_handler,))
97
+ server.add_registered_method_handlers('messagevoll.MessageService', rpc_method_handlers)
98
+
99
+
100
+ # This class is part of an EXPERIMENTAL API.
101
+ class MessageService(object):
102
+ """Missing associated documentation comment in .proto file."""
103
+
104
+ @staticmethod
105
+ def SendButton(request,
106
+ target,
107
+ options=(),
108
+ channel_credentials=None,
109
+ call_credentials=None,
110
+ insecure=False,
111
+ compression=None,
112
+ wait_for_ready=None,
113
+ timeout=None,
114
+ metadata=None):
115
+ return grpc.experimental.unary_unary(
116
+ request,
117
+ target,
118
+ '/messagevoll.MessageService/SendButton',
119
+ voll__pb2.MessageRequest.SerializeToString,
120
+ voll__pb2.MessageResponse.FromString,
121
+ options,
122
+ channel_credentials,
123
+ insecure,
124
+ call_credentials,
125
+ compression,
126
+ wait_for_ready,
127
+ timeout,
128
+ metadata,
129
+ _registered_method=True)
130
+
131
+ @staticmethod
132
+ def SendList(request,
133
+ target,
134
+ options=(),
135
+ channel_credentials=None,
136
+ call_credentials=None,
137
+ insecure=False,
138
+ compression=None,
139
+ wait_for_ready=None,
140
+ timeout=None,
141
+ metadata=None):
142
+ return grpc.experimental.unary_unary(
143
+ request,
144
+ target,
145
+ '/messagevoll.MessageService/SendList',
146
+ voll__pb2.MessageRequest.SerializeToString,
147
+ voll__pb2.MessageResponse.FromString,
148
+ options,
149
+ channel_credentials,
150
+ insecure,
151
+ call_credentials,
152
+ compression,
153
+ wait_for_ready,
154
+ timeout,
155
+ metadata,
156
+ _registered_method=True)
157
+
158
+ @staticmethod
159
+ def SendText(request,
160
+ target,
161
+ options=(),
162
+ channel_credentials=None,
163
+ call_credentials=None,
164
+ insecure=False,
165
+ compression=None,
166
+ wait_for_ready=None,
167
+ timeout=None,
168
+ metadata=None):
169
+ return grpc.experimental.unary_unary(
170
+ request,
171
+ target,
172
+ '/messagevoll.MessageService/SendText',
173
+ voll__pb2.MessageRequest.SerializeToString,
174
+ voll__pb2.MessageResponse.FromString,
175
+ options,
176
+ channel_credentials,
177
+ insecure,
178
+ call_credentials,
179
+ compression,
180
+ wait_for_ready,
181
+ timeout,
182
+ metadata,
183
+ _registered_method=True)
@@ -1,6 +1,8 @@
1
+ from ..gRPC.gRPCCall import WhatsappServiceClient, UserStateServiceClient
2
+
1
3
  from dataclasses import dataclass
2
4
  from typing import Optional
3
-
5
+ import json
4
6
 
5
7
  @dataclass
6
8
  class UserState:
@@ -15,11 +17,24 @@ class UserState:
15
17
  """
16
18
  customer_id: str
17
19
  menu: str
20
+ route: str
18
21
  lst_update: str
19
22
  obs: Optional[dict] = None
20
23
 
24
+
21
25
  @dataclass
22
- class Message:
26
+ class Element:
27
+ """
28
+ Representa um elemento de uma lista de opções.
29
+
30
+ Atributos:
31
+ title (str): O título do elemento.
32
+ description (str): A descrição do elemento.
33
+ """
34
+ title: str
35
+ description: Optional[str] = None
36
+
37
+ class UserCall:
23
38
  """
24
39
  Representa uma mensagem recebida ou enviada pelo chatbot.
25
40
 
@@ -32,10 +47,166 @@ class Message:
32
47
  company_phone (str): O número de telefone da empresa que está enviando ou recebendo a mensagem.
33
48
  status (Optional[str]): O status da mensagem (por exemplo, enviada, recebida, lida, etc.). Este campo é opcional.
34
49
  """
35
- type: str
36
- text: str
37
- user_state: UserState
38
- channel: str
39
- customer_phone: str
40
- company_phone: str
41
- status: Optional[str] = None
50
+ def __init__(
51
+ self,
52
+ type: str,
53
+ text: str,
54
+ user_state: UserState,
55
+ channel: str,
56
+ customer_phone: str,
57
+ company_phone: str,
58
+ grpc_uri: str,
59
+ status: Optional[str] = None,
60
+ ) -> None:
61
+
62
+ self.type = type
63
+ self.text = text
64
+ self.__user_state = user_state
65
+ self.channel = channel
66
+ self.customer_phone = customer_phone
67
+ self.company_phone = company_phone
68
+ self.status = status
69
+
70
+ self.grpc_uri = grpc_uri
71
+
72
+ self.__wpp_server_client = WhatsappServiceClient(self.grpc_uri)
73
+ self.__user_state_client = UserStateServiceClient(self.grpc_uri)
74
+
75
+ def send_text(self, text:str) -> None:
76
+
77
+ response = self.__wpp_server_client.send_text(
78
+ {
79
+ "hook_id": self.company_phone,
80
+ "enterprise_id": self.customer_phone,
81
+ "unique_customer_id": self.__user_state.customer_id,
82
+ "message_text": text
83
+ }
84
+ )
85
+
86
+ if not response.status:
87
+ raise ValueError("Erro ao enviar mensagem de texto.")
88
+
89
+ def send_button(
90
+ self,
91
+ text:str,
92
+ buttons:list,
93
+ title: str|None = None,
94
+ caption: str|None = None,
95
+ ) -> None:
96
+ if len(buttons) > 3:
97
+ raise ValueError("O número máximo de botões é 3.")
98
+
99
+ response = self.__wpp_server_client.send_button(
100
+ {
101
+ "hook_id": self.company_phone,
102
+ "enterprise_id": self.customer_phone,
103
+ "unique_customer_id": self.__user_state.customer_id,
104
+ "message_text": text,
105
+ "button_title": title,
106
+ "message_caption": caption,
107
+ "message_title": title,
108
+ "options": [{"title": b} for b in buttons],
109
+ }
110
+ )
111
+
112
+ if not response.status:
113
+ raise ValueError("Erro ao enviar mensagem de botões.")
114
+
115
+ def send_list(
116
+ self,
117
+ text:str,
118
+ title: str|None = None,
119
+ button_title: str|None = None,
120
+ element_list: list[Element] = None,
121
+ caption: str|None = None,
122
+ ) -> None:
123
+
124
+ if len(element_list) > 20:
125
+ raise ValueError("O número máximo de elementos é 20.")
126
+
127
+ response = self.__wpp_server_client.send_list(
128
+ {
129
+ "hook_id": self.company_phone,
130
+ "enterprise_id": self.customer_phone,
131
+ "unique_customer_id": self.__user_state.customer_id,
132
+ "message_text": text,
133
+ "button_title": button_title,
134
+ "message_caption": caption,
135
+ "message_title": title,
136
+ "options": [{"title": e.title, "description": e.description} for e in element_list],
137
+ }
138
+ )
139
+
140
+ if not response.status:
141
+ raise ValueError("Erro ao enviar mensagem de lista.")
142
+
143
+ def delete_user_state(self) -> None:
144
+ response = self.__user_state_client.delete_user_state(self.__user_state.customer_id)
145
+
146
+ if not response.status:
147
+ raise ValueError("Erro ao deletar estado do usuário.")
148
+
149
+ def update_user_state(
150
+ self,
151
+ menu: str,
152
+ route: str,
153
+ obs: dict,
154
+ ) -> None:
155
+
156
+ response = self.__user_state_client.update_user_state({
157
+ "user_id": self.__user_state.customer_id,
158
+ "menu_id": menu,
159
+ "route": route,
160
+ "obs": json.dumps(obs),
161
+ })
162
+
163
+ if not response.status:
164
+ raise ValueError("Erro ao atualizar estado do usuário.")
165
+
166
+ self.__user_state.menu = menu
167
+ self.__user_state.route = route
168
+ self.__user_state.obs = obs
169
+
170
+ @property
171
+ def menu(self):
172
+ return self.__user_state.menu
173
+
174
+ @property
175
+ def route(self):
176
+ return self.__user_state.route
177
+
178
+ @property
179
+ def obs(self):
180
+ return self.__user_state.obs
181
+
182
+ @property
183
+ def customer_id(self):
184
+ return self.__user_state.customer_id
185
+
186
+ @menu.setter
187
+ def menu(self, menu):
188
+
189
+ self.update_user_state(
190
+ menu,
191
+ self.__user_state.route,
192
+ self.__user_state.obs
193
+ )
194
+
195
+ @route.setter
196
+ def route(self, route):
197
+
198
+ self.update_user_state(
199
+ self.__user_state.menu,
200
+ route,
201
+ self.__user_state.obs
202
+ )
203
+
204
+ @obs.setter
205
+ def obs(self, obs):
206
+
207
+ self.update_user_state(
208
+ self.__user_state.menu,
209
+ self.__user_state.route,
210
+ obs
211
+ )
212
+
@@ -96,4 +96,32 @@ class TransferToHuman:
96
96
  'type': 'transfer',
97
97
  'campaign_id': self.campaign_id,
98
98
  'observations': self.observations,
99
+ }
100
+
101
+ class RedirectEntireChatbot:
102
+ """
103
+ Representa uma resposta que redireciona o fluxo do chatbot para um outro menu.
104
+
105
+ Atributos:
106
+ menu (str): O menu para o qual o chatbot deve redirecionar.
107
+ route (str): A rota para a qual o chatbot deve redirecionar.
108
+ """
109
+
110
+ def __init__(self, menu:str, route: str) -> None:
111
+ """
112
+ Inicializa a resposta de redirecionamento com a rota especificada.
113
+
114
+ Args:
115
+ route (str): A rota para a qual o chatbot deve redirecionar.
116
+ """
117
+ self.route = route
118
+ self.menu = menu
119
+ def json(self):
120
+ '''
121
+ Retorna o objeto em formato json.
122
+ '''
123
+ return {
124
+ 'type': 'redirect',
125
+ 'menu': self.menu,
126
+ 'route': self.route,
99
127
  }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: chatgraph
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: A user-friendly chatbot library
5
5
  Home-page: https://github.com/irissonnlima/chatgraph
6
6
  License: MIT
@@ -11,7 +11,10 @@ Requires-Python: >=3.12,<4.0
11
11
  Classifier: License :: OSI Approved :: MIT License
12
12
  Classifier: Programming Language :: Python :: 3
13
13
  Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: grpcio (>=1.66.2,<2.0.0)
15
+ Requires-Dist: grpcio-tools (>=1.66.2,<2.0.0)
14
16
  Requires-Dist: pika (>=1.3.2,<2.0.0)
17
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
15
18
  Requires-Dist: rich (>=13.8.1,<14.0.0)
16
19
  Project-URL: Repository, https://github.com/irissonnlima/chatgraph
17
20
  Description-Content-Type: text/markdown
@@ -0,0 +1,21 @@
1
+ chatgraph/__init__.py,sha256=OnPa3kE9pTXlxnkwwc45_2F6bqfR_GZAFal6-FFeT_U,648
2
+ chatgraph/auth/credentials.py,sha256=xsMEpLQnc66novPjL6upocMcnUnvFJ7yxINzUenkxmc,2388
3
+ chatgraph/bot/chatbot_model.py,sha256=qu8NG4rsKl_w8RFSFCDPOWV-vzMjmmwsvwkZdGcJUdI,7068
4
+ chatgraph/bot/chatbot_router.py,sha256=kZ_4X5AhhE2mntx4tcHiapaSKC1T4K1jqIVjLp1Pjg0,2817
5
+ chatgraph/error/chatbot_error.py,sha256=4sEcW8vz0eQk2QDmDygucVM4caHliZW5iH7XJvmLBuk,1897
6
+ chatgraph/error/route_error.py,sha256=CY8m82ap7-Sr-DXPsolltRW50TqD__5RyXBmNNJCWr8,793
7
+ chatgraph/gRPC/gRPCCall.py,sha256=g1VGr6z-_IN2J3tSFAXqM1E2F8xx_p5noH3e_klJiKc,4478
8
+ chatgraph/messages/message_consumer.py,sha256=8GOhBPE8ntSf74prw8STCUqi9jfW9gAmMdH9RAqnwEA,8978
9
+ chatgraph/pb/userstate.proto,sha256=3uWtonkgBG-5jk7Du7uKDQwFnoNQaUZYVr1lb77EJSA,630
10
+ chatgraph/pb/userstate_pb2.py,sha256=yJepkWX2mLQpY0I4qhfrObrYfRAmnq4mccPTMlCV-os,2363
11
+ chatgraph/pb/userstate_pb2_grpc.py,sha256=QS8-9X6WDeurl4DAI0dzvCdGbQusHlMON0_p1QqmuEs,8635
12
+ chatgraph/pb/voll.proto,sha256=qFV0_MLUTsVcDdEWz9EVWObn3Nu-tNwX2aGeKPxDtE8,716
13
+ chatgraph/pb/voll_pb2.py,sha256=aspT1ynrGTKh_SQcIoEb_uSJ7j_nKpxEdyj-hkr4lTI,2519
14
+ chatgraph/pb/voll_pb2_grpc.py,sha256=RFW3_dbzz_INJG8D1LQmmdyEr7ajLRqT1JPl0D-Hgso,6742
15
+ chatgraph/types/message_types.py,sha256=PN7hsXe8zNBM6PyYZ70NTn_aTYvS2EjZ0yQ1kMCNrgg,6439
16
+ chatgraph/types/output_state.py,sha256=XNbwkRYPpsmc4E3ZC1IrikRkBlwuGI-BOqiWWCdSawQ,3838
17
+ chatgraph/types/route.py,sha256=nKTqzwGl7d_Bu8G6Sr0EmmhuuiZWKEoSozITRrdyi1g,2587
18
+ chatgraph-0.3.0.dist-info/LICENSE,sha256=rVJozpRzDlplOpvI8A1GvmfVS0ReYdZvMWc1j2jV0v8,1090
19
+ chatgraph-0.3.0.dist-info/METADATA,sha256=aC92rC6MpBD1cu4Y3rQJjElZWBx2TSeJzwKnI086I1w,6000
20
+ chatgraph-0.3.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
21
+ chatgraph-0.3.0.dist-info/RECORD,,
@@ -1,40 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from typing import Any, Callable
3
-
4
-
5
- class MessageConsumer(ABC):
6
- """
7
- Classe base abstrata para consumidores de mensagens no sistema do chatbot.
8
-
9
- Esta classe define a interface que todos os consumidores de mensagens devem implementar para serem usados no sistema do chatbot.
10
- """
11
-
12
- @abstractmethod
13
- def start_consume(self, process_message: Callable) -> Any:
14
- """
15
- Inicia o consumo de mensagens e processa cada mensagem usando a função fornecida.
16
-
17
- Args:
18
- process_message (Callable): Função de callback que processa cada mensagem recebida.
19
-
20
- Returns:
21
- Any: O resultado do processo de consumo de mensagens, dependendo da implementação concreta.
22
- """
23
- pass
24
-
25
- @abstractmethod
26
- def load_dotenv(self) -> 'MessageConsumer':
27
- """
28
- Carrega variáveis de ambiente para configurar o consumidor de mensagens.
29
-
30
- Returns:
31
- MessageConsumer: A instância do consumidor de mensagens configurado.
32
- """
33
- pass
34
-
35
- @abstractmethod
36
- def reprer(self) -> str:
37
- '''
38
- Retorna uma representação textual do consumidor de mensagens.
39
- '''
40
- pass
@@ -1,23 +0,0 @@
1
- from abc import ABC, abstractmethod
2
-
3
- class MessageSender(ABC):
4
-
5
- @abstractmethod
6
- def load_dotenv(self) -> 'MessageSender':
7
- """
8
- Carrega variáveis de ambiente para configurar o disparador de mensagens.
9
-
10
- Returns:
11
- MessageSender: A instância do disparador de mensagens configurado.
12
- """
13
- pass
14
-
15
- @abstractmethod
16
- def send_message(self) -> None:
17
- """
18
- Envia uma mensagem para o destino especificado.
19
-
20
- Args:
21
- message (str): A mensagem a ser enviada.
22
- """
23
- pass
@@ -1,79 +0,0 @@
1
- from .base_message_sender import MessageSender
2
- from ..auth.credentials import Credential
3
- import pika
4
- import os
5
-
6
- class RabbitMessageSender(MessageSender):
7
- def __init__(
8
- self,
9
- credential: Credential,
10
- amqp_url: str,
11
- send_queue: str,
12
- virtual_host: str = '/',
13
- ) -> None:
14
- """
15
- Inicializa o consumidor de mensagens RabbitMQ com as configurações fornecidas.
16
-
17
- Args:
18
- credential (Credential): Credenciais de autenticação para o RabbitMQ.
19
- amqp_url (str): A URL de conexão AMQP do RabbitMQ.
20
- queue_consume (str): O nome da fila de consumo.
21
- prefetch_count (int, opcional): O número de mensagens pré-carregadas. Padrão é 1.
22
- virtual_host (str, opcional): O host virtual do RabbitMQ. Padrão é '/'.
23
- """
24
- self.__virtual_host = virtual_host
25
- self.__send_queue = send_queue
26
- self.__amqp_url = amqp_url
27
- self.__credentials = pika.PlainCredentials(
28
- credential.username, credential.password
29
- )
30
-
31
- @classmethod
32
- def load_dotenv(
33
- cls,
34
- user_env: str = 'RABBIT_USER',
35
- pass_env: str = 'RABBIT_PASS',
36
- uri_env: str = 'RABBIT_URI',
37
- queue_env: str = 'RABBIT_QUEUE',
38
- prefetch_env: str = 'RABBIT_PREFETCH',
39
- vhost_env: str = 'RABBIT_VHOST',
40
- ) -> 'RabbitMessageSender':
41
- """
42
- Carrega variáveis de ambiente para configurar o disparador de mensagens.
43
- Args:
44
- user_env (str): Nome da variável de ambiente para o usuário do RabbitMQ. Padrão é 'RABBIT_USER'.
45
- pass_env (str): Nome da variável de ambiente para a senha do RabbitMQ. Padrão é 'RABBIT_PASS'.
46
- uri_env (str): Nome da variável de ambiente para a URL do RabbitMQ. Padrão é 'RABBIT_URI'.
47
- queue_env (str): Nome da variável de ambiente para a fila de consumo do RabbitMQ. Padrão é 'RABBIT_QUEUE'.
48
- prefetch_env (str): Nome da variável de ambiente para o prefetch count. Padrão é 'RABBIT_PREFETCH'.
49
- vhost_env (str): Nome da variável de ambiente para o host virtual do RabbitMQ. Padrão é 'RABBIT_VHOST'.
50
- Raises:
51
- ValueError: Se as variáveis de ambiente não forem configuradas corret
52
- Returns:
53
- RabbitMessageSender: A instância do disparador de mensagens configurado.
54
- """
55
- username = os.getenv(user_env)
56
- password = os.getenv(pass_env)
57
- url = os.getenv(uri_env)
58
- queue = os.getenv(queue_env)
59
- vhost = os.getenv(vhost_env, '/')
60
-
61
- if not username or not password or not url or not queue:
62
- raise ValueError('Corrija as variáveis de ambiente!')
63
-
64
- return cls(
65
- credential=Credential(username=username, password=password),
66
- amqp_url=url,
67
- send_queue=queue,
68
- virtual_host=vhost,
69
- )
70
-
71
-
72
- def send_message(self) -> None:
73
- """
74
- Envia uma mensagem para o destino especificado.
75
-
76
- Args:
77
- message (str): A mensagem a ser enviada.
78
- """
79
- pass