chatgraph 0.2.3__tar.gz → 0.2.6__tar.gz

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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: chatgraph
3
- Version: 0.2.3
3
+ Version: 0.2.6
4
4
  Summary: A user-friendly chatbot library
5
5
  Home-page: https://github.com/irissonnlima/chatgraph
6
6
  License: MIT
@@ -12,6 +12,7 @@ Classifier: License :: OSI Approved :: MIT License
12
12
  Classifier: Programming Language :: Python :: 3
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Requires-Dist: pika (>=1.3.2,<2.0.0)
15
+ Requires-Dist: rich (>=13.8.1,<14.0.0)
15
16
  Project-URL: Repository, https://github.com/irissonnlima/chatgraph
16
17
  Description-Content-Type: text/markdown
17
18
 
@@ -98,8 +98,9 @@ class ChatbotApp(ABC):
98
98
  """
99
99
  Inicia o consumo de mensagens pelo chatbot, processando cada mensagem recebida.
100
100
  """
101
+ self.__message_consumer.reprer()
101
102
  self.__message_consumer.start_consume(self.process_message)
102
-
103
+
103
104
  def process_message(self, message: Message):
104
105
  """
105
106
  Processa uma mensagem recebida, identificando a rota correspondente e executando a função associada.
@@ -138,7 +139,13 @@ class ChatbotApp(ABC):
138
139
 
139
140
  if type(message_response) in (str, float, int):
140
141
  response = ChatbotResponse(message_response)
141
- return response.json()
142
+ response = message_response.json()
143
+ response['user_state'] = {
144
+ 'customer_id': customer_id,
145
+ 'menu': menu,
146
+ 'obs': user_state.obs,
147
+ }
148
+ return json.dumps(response)
142
149
  elif type(message_response) == ChatbotResponse:
143
150
  route = self.__adjust_route(message_response.route, menu)
144
151
  response = message_response.json()
@@ -148,8 +155,14 @@ class ChatbotApp(ABC):
148
155
  'obs': user_state.obs,
149
156
  }
150
157
  return json.dumps(response)
151
- elif type(message_response) in (ChatbotResponse, EndChatResponse, TransferToHuman):
152
- return json.dumps(message_response.json())
158
+ elif type(message_response) in (EndChatResponse, TransferToHuman):
159
+ response = message_response.json()
160
+ response['user_state'] = {
161
+ 'customer_id': customer_id,
162
+ 'menu': None,
163
+ 'obs': None,
164
+ }
165
+ return json.dumps(response)
153
166
  elif type(message_response) == RedirectResponse:
154
167
  route = self.__adjust_route(message_response.route, menu)
155
168
  message.user_state.menu = route
@@ -174,4 +187,4 @@ class ChatbotApp(ABC):
174
187
  if 'start' not in route:
175
188
  route = absolute_route + route
176
189
 
177
- return route
190
+ return route
@@ -31,3 +31,10 @@ class MessageConsumer(ABC):
31
31
  MessageConsumer: A instância do consumidor de mensagens configurado.
32
32
  """
33
33
  pass
34
+
35
+ @abstractmethod
36
+ def reprer(self) -> str:
37
+ '''
38
+ Retorna uma representação textual do consumidor de mensagens.
39
+ '''
40
+ pass
@@ -0,0 +1,23 @@
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
@@ -6,7 +6,10 @@ from typing import Callable
6
6
  from ..auth.credentials import Credential
7
7
  from ..types.message_types import Message, UserState
8
8
  from .base_message_consumer import MessageConsumer
9
-
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+ from rich.text import Text
12
+ from rich.panel import Panel
10
13
 
11
14
  class RabbitMessageConsumer(MessageConsumer):
12
15
  """
@@ -161,17 +164,46 @@ class RabbitMessageConsumer(MessageConsumer):
161
164
  Returns:
162
165
  Message: Uma instância da classe Message com os dados extraídos do dicionário.
163
166
  """
167
+
168
+ user_state = message.get('user_state', {})
164
169
  return Message(
165
170
  type=message.get('type', ''),
166
171
  text=message.get('text', ''),
167
172
  user_state=UserState(
168
- customer_id=message.get('customer_id', ''),
169
- menu=message.get('menu', ''),
170
- lst_update=message.get('lst_update', ''),
171
- obs=message.get('obs', {}),
173
+ customer_id=user_state.get('customer_id', ''),
174
+ menu=user_state.get('menu', ''),
175
+ lst_update=user_state.get('lst_update', ''),
176
+ obs=user_state.get('obs', {}),
172
177
  ),
173
178
  channel=message.get('channel', ''),
174
179
  customer_phone=message.get('customer_phone', ''),
175
180
  company_phone=message.get('company_phone', ''),
176
181
  status=message.get('status'),
177
182
  )
183
+
184
+ def reprer(self):
185
+ console = Console()
186
+
187
+ # Título "ChatGraph" destacado em vermelho e negrito dentro de um painel
188
+ title_text = Text("ChatGraph", style="bold red", justify="center")
189
+ title_panel = Panel.fit(title_text, title=" ", border_style="bold red", padding=(1, 4))
190
+
191
+ # Linha separadora com emojis
192
+ separator = Text("🐇🐇🐇 RabbitMessageConsumer 📨📨📨", style="cyan", justify="center")
193
+
194
+ # Criação da tabela com os atributos
195
+ table = Table(show_header=True, header_style="bold magenta", title="RabbitMQ Consumer")
196
+ table.add_column("Atributo", justify="center", style="cyan", no_wrap=True)
197
+ table.add_column("Valor", justify="center", style="magenta")
198
+
199
+ table.add_row("Virtual Host", self.__virtual_host)
200
+ table.add_row("Prefetch Count", str(self.__prefetch_count))
201
+ table.add_row("Queue Consume", self.__queue_consume)
202
+ table.add_row("AMQP URL", self.__amqp_url)
203
+ table.add_row("Username", self.__credentials.username)
204
+ table.add_row("Password", "******") # Oculta a senha
205
+
206
+ # Imprime o título, separador e a tabela centralizada
207
+ console.print(title_panel, justify="center")
208
+ console.print(separator, justify="center")
209
+ console.print(table, justify="center")
@@ -0,0 +1,79 @@
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
@@ -30,7 +30,7 @@ class ChatbotResponse:
30
30
  '''
31
31
  return {
32
32
  'type': 'message',
33
- 'message': self.message,
33
+ 'text': self.message,
34
34
  }
35
35
 
36
36
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "chatgraph"
3
- version = "0.2.3"
3
+ version = "0.2.6"
4
4
  description = "A user-friendly chatbot library"
5
5
  authors = ["Irisson N. Lima <irisson.lima@verdecard.com.br>"]
6
6
  readme = "README.md"
@@ -12,6 +12,7 @@ license = "MIT"
12
12
  [tool.poetry.dependencies]
13
13
  python = "^3.12"
14
14
  pika = "^1.3.2"
15
+ rich = "^13.8.1"
15
16
 
16
17
  [tool.poetry.group.dev.dependencies]
17
18
  ruff = "^0.5.1"
File without changes
File without changes