ararahq-sdk 1.8.0__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.
Files changed (29) hide show
  1. ararahq_sdk-1.8.0/.gitignore +146 -0
  2. ararahq_sdk-1.8.0/LICENSE +21 -0
  3. ararahq_sdk-1.8.0/PKG-INFO +208 -0
  4. ararahq_sdk-1.8.0/README.md +170 -0
  5. ararahq_sdk-1.8.0/arara_api_sdk/__init__.py +23 -0
  6. ararahq_sdk-1.8.0/arara_api_sdk/client.py +78 -0
  7. ararahq_sdk-1.8.0/arara_api_sdk/config.py +14 -0
  8. ararahq_sdk-1.8.0/arara_api_sdk/exceptions.py +41 -0
  9. ararahq_sdk-1.8.0/arara_api_sdk/http/__init__.py +0 -0
  10. ararahq_sdk-1.8.0/arara_api_sdk/http/client.py +137 -0
  11. ararahq_sdk-1.8.0/arara_api_sdk/http/interceptors.py +0 -0
  12. ararahq_sdk-1.8.0/arara_api_sdk/models/__init__.py +0 -0
  13. ararahq_sdk-1.8.0/arara_api_sdk/models/auth.py +8 -0
  14. ararahq_sdk-1.8.0/arara_api_sdk/models/brain.py +28 -0
  15. ararahq_sdk-1.8.0/arara_api_sdk/models/campaign.py +30 -0
  16. ararahq_sdk-1.8.0/arara_api_sdk/models/message.py +42 -0
  17. ararahq_sdk-1.8.0/arara_api_sdk/models/organization.py +61 -0
  18. ararahq_sdk-1.8.0/arara_api_sdk/models/payment.py +37 -0
  19. ararahq_sdk-1.8.0/arara_api_sdk/models/template.py +45 -0
  20. ararahq_sdk-1.8.0/arara_api_sdk/models/user.py +22 -0
  21. ararahq_sdk-1.8.0/arara_api_sdk/resources/__init__.py +7 -0
  22. ararahq_sdk-1.8.0/arara_api_sdk/resources/brain.py +35 -0
  23. ararahq_sdk-1.8.0/arara_api_sdk/resources/campaign.py +35 -0
  24. ararahq_sdk-1.8.0/arara_api_sdk/resources/message.py +64 -0
  25. ararahq_sdk-1.8.0/arara_api_sdk/resources/organization.py +198 -0
  26. ararahq_sdk-1.8.0/arara_api_sdk/resources/payment.py +69 -0
  27. ararahq_sdk-1.8.0/arara_api_sdk/resources/template.py +139 -0
  28. ararahq_sdk-1.8.0/arara_api_sdk/resources/user.py +44 -0
  29. ararahq_sdk-1.8.0/pyproject.toml +113 -0
@@ -0,0 +1,146 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ # .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Used to bundle your script into a single file
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .nox/
42
+ .coverage
43
+ .coverage.*
44
+ .cache
45
+ nosetests.xml
46
+ coverage.xml
47
+ *.cover
48
+ *.py,cover
49
+ .hypothesis/
50
+ .pytest_cache/
51
+ cover/
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+ db.sqlite3-journal
62
+
63
+ # Flask stuff:
64
+ instance/
65
+ .webassets-cache
66
+
67
+ # Scrapy stuff:
68
+ .scrapy
69
+
70
+ # Sphinx documentation
71
+ docs/_build/
72
+
73
+ # PyBuilder
74
+ target/
75
+
76
+ # Jupyter Notebook
77
+ .ipynb_checkpoints
78
+
79
+ # IPython
80
+ profile_default/
81
+ ipython_config.py
82
+
83
+ # pyenv
84
+ .python-version
85
+
86
+ # pipenv
87
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
88
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
89
+ # having no cross-platform support, pipenv may install dependencies that don't work, or even
90
+ # fail to install.
91
+ #Pipfile.lock
92
+
93
+ # poetry
94
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
95
+ #poetry.lock
96
+
97
+ # pdm
98
+ .pdm.toml
99
+ .pdm-python
100
+ .pdm-build/
101
+
102
+ # PEP 582; used by e.g. github.com/pdm-project/pdm
103
+ __pypackages__/
104
+
105
+ # Celery stuff
106
+ celerybeat-schedule
107
+ celerybeat.pid
108
+
109
+ # SageMath parsed files
110
+ *.sage.py
111
+
112
+ # Environments
113
+ .env
114
+ .venv
115
+ env/
116
+ venv/
117
+ ENV/
118
+ env.bak/
119
+ venv.bak/
120
+
121
+ # Spyder project settings
122
+ .spyderproject
123
+ .spyproject
124
+
125
+ # Rope project settings
126
+ .ropeproject
127
+
128
+ # mkdocs documentation
129
+ /site
130
+
131
+ # mypy
132
+ .mypy_cache/
133
+ .dmypy.json
134
+ dmypy.json
135
+
136
+ # Pyre type checker
137
+ .pyre/
138
+
139
+ # pytype static analyzer
140
+ .pytype/
141
+
142
+ # Cython debug symbols
143
+ cython_debug/
144
+
145
+ # PyCharm
146
+ .idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Arara Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: ararahq-sdk
3
+ Version: 1.8.0
4
+ Summary: Official Python SDK for the Arara API
5
+ Project-URL: Homepage, https://github.com/ararahq/arara-python-sdk
6
+ Project-URL: Bug Tracker, https://github.com/ararahq/arara-python-sdk/issues
7
+ Author-email: Arara <contact@arara.io>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Requires-Python: >=3.8
20
+ Requires-Dist: httpx>=0.24.0
21
+ Requires-Dist: pydantic-settings>=2.0.0
22
+ Requires-Dist: pydantic[email]>=2.0.0
23
+ Requires-Dist: tenacity>=8.0.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: black>=23.0.0; extra == 'dev'
26
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
27
+ Requires-Dist: pre-commit>=3.0.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
29
+ Provides-Extra: lint
30
+ Requires-Dist: mypy>=1.0.0; extra == 'lint'
31
+ Requires-Dist: ruff>=0.1.0; extra == 'lint'
32
+ Provides-Extra: test
33
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
34
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
35
+ Requires-Dist: pytest>=7.0.0; extra == 'test'
36
+ Requires-Dist: respx>=0.20.0; extra == 'test'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # Arara Python SDK
40
+
41
+ O SDK oficial da Arara para Python. Esta biblioteca permite integrar facilmente as funcionalidades de mensageria (WhatsApp), gestão de templates, inteligência artificial (Brain), campanhas e pagamentos diretamente no seu aplicativo ou servidor.
42
+
43
+ ---
44
+
45
+ ## 🚀 Destaques (Features)
46
+
47
+ - **Suporte Nativo a Async/Sync**: Escolha entre operações bloqueantes ou assíncronas (`httpx` baseado).
48
+ - **Type Safety**: Utiliza **Pydantic V2** para validação rigorosa de dados e suporte total a autocompletar em IDEs.
49
+ - **Resiliência**: Lógica de **Retries** automática com backoff exponencial integrada.
50
+ - **Tratamento de Erros Profissional**: Hierarquia de exceções clara para cada status HTTP relevante.
51
+ - **Arquitetura Modular**: Recursos organizados por domínio (Messages, Templates, Brain, etc).
52
+
53
+ ---
54
+
55
+ ## 📦 Instalação
56
+
57
+ ```bash
58
+ pip install arara-api-sdk
59
+ ```
60
+
61
+ > **Nota:** Requer Python 3.8 ou superior.
62
+
63
+ ---
64
+
65
+ ## 🔑 Autenticação
66
+
67
+ A autenticação é feita via **Bear API Key**. Você pode obter sua chave no painel da Arara.
68
+
69
+ O SDK busca automaticamente a variável de ambiente `ARARA_API_KEY` caso nenhuma chave seja passada no construtor.
70
+
71
+ ```bash
72
+ export ARARA_API_KEY="ara_live_..."
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 🛠️ Uso Rápido (Quick Start)
78
+
79
+ ### Modo Síncrono (Standard)
80
+ Ideal para scripts simples ou servidores que não utilizam async/await.
81
+
82
+ ```python
83
+ from arara_api_sdk import AraraClient
84
+ from arara_api_sdk.models.message import SendMessageRequest
85
+
86
+ # O uso de Context Manager garante que os recursos sejam fechados corretamente
87
+ with AraraClient(api_key="your_api_key") as client:
88
+ request = SendMessageRequest(
89
+ receiver="5511999999999",
90
+ body="Hello World from Arara SDK!",
91
+ media_url="https://ararahq.com/l/FtFmja" # Opcional: Anexo
92
+ )
93
+ response = client.messages.send(request)
94
+ print(f"Message ID: {response.id} | Status: {response.status}")
95
+ ```
96
+
97
+ ### Modo Assíncrono (High Performance)
98
+ Recomendado para aplicações FastAPI, aiohttp ou volumes massivos de dados.
99
+
100
+ ```python
101
+ import asyncio
102
+ from arara_api_sdk import AraraClient
103
+ from arara_api_sdk.models.message import SendMessageRequest
104
+
105
+ async def send_bulk():
106
+ async with AraraClient() as client:
107
+ request = SendMessageRequest(
108
+ receiver="5511999999999",
109
+ template_name="welcome_message",
110
+ variables=["Amos"],
111
+ scheduled_at="2024-12-25T10:00:00Z" # Opcional: Agendamento ISO8601
112
+ )
113
+ response = await client.messages.send_async(request)
114
+ print(f"Async Sent: {response.id}")
115
+
116
+ asyncio.run(send_bulk())
117
+ ```
118
+
119
+ ---
120
+
121
+ ## 📂 Visão Geral dos Módulos
122
+
123
+ ### 💬 Mensagens (Messages)
124
+ Envio de mensagens de texto simples ou baseadas em templates aprovados.
125
+ ```python
126
+ client.messages.send(request)
127
+ client.messages.get(message_id)
128
+ ```
129
+
130
+ ### 📝 Templates
131
+ Gestão completa do ciclo de vida de modelos de mensagem do WhatsApp.
132
+ ```python
133
+ client.templates.list()
134
+ client.templates.create(create_request)
135
+ client.templates.get_status(template_id)
136
+ ```
137
+
138
+ ### 🧠 AI Brain
139
+ Interface direta com o motor de Inteligência Artificial da Arara.
140
+ ```python
141
+ response = client.brain.prompt(BrainRequest(prompt="Como configurar meu webhook?"))
142
+ print(response.answer)
143
+ ```
144
+
145
+ ### 🏢 Organizações & Webhooks
146
+ Gestão de membros, números de telefone e configuração de webhooks de recebimento.
147
+ ```python
148
+ webhook = client.organizations.get_webhook()
149
+ members = client.organizations.list_members()
150
+ ```
151
+
152
+ ---
153
+
154
+ ## ⚙️ Configuração Avançada
155
+
156
+ Você pode customizar o comportamento do HttpClient no momento da inicialização:
157
+
158
+ ```python
159
+ client = AraraClient(
160
+ api_key="...",
161
+ timeout=60.0, # Custom timeout in seconds
162
+ max_retries=5, # Exponential backoff retries
163
+ base_url="https://..." # Custom API endpoint
164
+ )
165
+ ```
166
+
167
+ ---
168
+
169
+ ## ⚠️ Tratamento de Erros (Error Handling)
170
+
171
+ O SDK mapeia erros da API para exceções Python específicas:
172
+
173
+ ```python
174
+ from arara_api_sdk.exceptions import (
175
+ AraraAuthError,
176
+ AraraValidationError,
177
+ AraraResourceNotFoundError
178
+ )
179
+
180
+ try:
181
+ client.messages.send(request)
182
+ except AraraAuthError:
183
+ # Error 401
184
+ pass
185
+ except AraraResourceNotFoundError:
186
+ # Error 404
187
+ pass
188
+ except AraraValidationError as e:
189
+ # Error 400 - Validation details are in e.response_body
190
+ print(e.response_body)
191
+ ```
192
+
193
+ ---
194
+
195
+ ## 👩‍💻 Desenvolvimento e Testes
196
+
197
+ Se você deseja contribuir ou rodar os testes localmente:
198
+
199
+ 1. Crie um ambiente virtual: `python -m venv .venv`
200
+ 2. Ative: `source .venv/bin/activate`
201
+ 3. Instale as dependências: `pip install -e ".[test]"`
202
+ 4. Rode os testes: `pytest tests/`
203
+
204
+ ---
205
+
206
+ ## 📄 Licença
207
+
208
+ Distribuído sob a licença MIT. Veja `LICENSE` para mais informações.
@@ -0,0 +1,170 @@
1
+ # Arara Python SDK
2
+
3
+ O SDK oficial da Arara para Python. Esta biblioteca permite integrar facilmente as funcionalidades de mensageria (WhatsApp), gestão de templates, inteligência artificial (Brain), campanhas e pagamentos diretamente no seu aplicativo ou servidor.
4
+
5
+ ---
6
+
7
+ ## 🚀 Destaques (Features)
8
+
9
+ - **Suporte Nativo a Async/Sync**: Escolha entre operações bloqueantes ou assíncronas (`httpx` baseado).
10
+ - **Type Safety**: Utiliza **Pydantic V2** para validação rigorosa de dados e suporte total a autocompletar em IDEs.
11
+ - **Resiliência**: Lógica de **Retries** automática com backoff exponencial integrada.
12
+ - **Tratamento de Erros Profissional**: Hierarquia de exceções clara para cada status HTTP relevante.
13
+ - **Arquitetura Modular**: Recursos organizados por domínio (Messages, Templates, Brain, etc).
14
+
15
+ ---
16
+
17
+ ## 📦 Instalação
18
+
19
+ ```bash
20
+ pip install arara-api-sdk
21
+ ```
22
+
23
+ > **Nota:** Requer Python 3.8 ou superior.
24
+
25
+ ---
26
+
27
+ ## 🔑 Autenticação
28
+
29
+ A autenticação é feita via **Bear API Key**. Você pode obter sua chave no painel da Arara.
30
+
31
+ O SDK busca automaticamente a variável de ambiente `ARARA_API_KEY` caso nenhuma chave seja passada no construtor.
32
+
33
+ ```bash
34
+ export ARARA_API_KEY="ara_live_..."
35
+ ```
36
+
37
+ ---
38
+
39
+ ## 🛠️ Uso Rápido (Quick Start)
40
+
41
+ ### Modo Síncrono (Standard)
42
+ Ideal para scripts simples ou servidores que não utilizam async/await.
43
+
44
+ ```python
45
+ from arara_api_sdk import AraraClient
46
+ from arara_api_sdk.models.message import SendMessageRequest
47
+
48
+ # O uso de Context Manager garante que os recursos sejam fechados corretamente
49
+ with AraraClient(api_key="your_api_key") as client:
50
+ request = SendMessageRequest(
51
+ receiver="5511999999999",
52
+ body="Hello World from Arara SDK!",
53
+ media_url="https://ararahq.com/l/FtFmja" # Opcional: Anexo
54
+ )
55
+ response = client.messages.send(request)
56
+ print(f"Message ID: {response.id} | Status: {response.status}")
57
+ ```
58
+
59
+ ### Modo Assíncrono (High Performance)
60
+ Recomendado para aplicações FastAPI, aiohttp ou volumes massivos de dados.
61
+
62
+ ```python
63
+ import asyncio
64
+ from arara_api_sdk import AraraClient
65
+ from arara_api_sdk.models.message import SendMessageRequest
66
+
67
+ async def send_bulk():
68
+ async with AraraClient() as client:
69
+ request = SendMessageRequest(
70
+ receiver="5511999999999",
71
+ template_name="welcome_message",
72
+ variables=["Amos"],
73
+ scheduled_at="2024-12-25T10:00:00Z" # Opcional: Agendamento ISO8601
74
+ )
75
+ response = await client.messages.send_async(request)
76
+ print(f"Async Sent: {response.id}")
77
+
78
+ asyncio.run(send_bulk())
79
+ ```
80
+
81
+ ---
82
+
83
+ ## 📂 Visão Geral dos Módulos
84
+
85
+ ### 💬 Mensagens (Messages)
86
+ Envio de mensagens de texto simples ou baseadas em templates aprovados.
87
+ ```python
88
+ client.messages.send(request)
89
+ client.messages.get(message_id)
90
+ ```
91
+
92
+ ### 📝 Templates
93
+ Gestão completa do ciclo de vida de modelos de mensagem do WhatsApp.
94
+ ```python
95
+ client.templates.list()
96
+ client.templates.create(create_request)
97
+ client.templates.get_status(template_id)
98
+ ```
99
+
100
+ ### 🧠 AI Brain
101
+ Interface direta com o motor de Inteligência Artificial da Arara.
102
+ ```python
103
+ response = client.brain.prompt(BrainRequest(prompt="Como configurar meu webhook?"))
104
+ print(response.answer)
105
+ ```
106
+
107
+ ### 🏢 Organizações & Webhooks
108
+ Gestão de membros, números de telefone e configuração de webhooks de recebimento.
109
+ ```python
110
+ webhook = client.organizations.get_webhook()
111
+ members = client.organizations.list_members()
112
+ ```
113
+
114
+ ---
115
+
116
+ ## ⚙️ Configuração Avançada
117
+
118
+ Você pode customizar o comportamento do HttpClient no momento da inicialização:
119
+
120
+ ```python
121
+ client = AraraClient(
122
+ api_key="...",
123
+ timeout=60.0, # Custom timeout in seconds
124
+ max_retries=5, # Exponential backoff retries
125
+ base_url="https://..." # Custom API endpoint
126
+ )
127
+ ```
128
+
129
+ ---
130
+
131
+ ## ⚠️ Tratamento de Erros (Error Handling)
132
+
133
+ O SDK mapeia erros da API para exceções Python específicas:
134
+
135
+ ```python
136
+ from arara_api_sdk.exceptions import (
137
+ AraraAuthError,
138
+ AraraValidationError,
139
+ AraraResourceNotFoundError
140
+ )
141
+
142
+ try:
143
+ client.messages.send(request)
144
+ except AraraAuthError:
145
+ # Error 401
146
+ pass
147
+ except AraraResourceNotFoundError:
148
+ # Error 404
149
+ pass
150
+ except AraraValidationError as e:
151
+ # Error 400 - Validation details are in e.response_body
152
+ print(e.response_body)
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 👩‍💻 Desenvolvimento e Testes
158
+
159
+ Se você deseja contribuir ou rodar os testes localmente:
160
+
161
+ 1. Crie um ambiente virtual: `python -m venv .venv`
162
+ 2. Ative: `source .venv/bin/activate`
163
+ 3. Instale as dependências: `pip install -e ".[test]"`
164
+ 4. Rode os testes: `pytest tests/`
165
+
166
+ ---
167
+
168
+ ## 📄 Licença
169
+
170
+ Distribuído sob a licença MIT. Veja `LICENSE` para mais informações.
@@ -0,0 +1,23 @@
1
+ from arara_api_sdk.client import AraraClient
2
+ from arara_api_sdk.exceptions import (
3
+ AraraError,
4
+ AraraAuthError,
5
+ AraraValidationError,
6
+ AraraRateLimitError,
7
+ AraraResourceNotFoundError,
8
+ AraraServerError,
9
+ AraraConnectionError,
10
+ AraraTimeoutError,
11
+ )
12
+
13
+ __all__ = [
14
+ "AraraClient",
15
+ "AraraError",
16
+ "AraraAuthError",
17
+ "AraraValidationError",
18
+ "AraraRateLimitError",
19
+ "AraraResourceNotFoundError",
20
+ "AraraServerError",
21
+ "AraraConnectionError",
22
+ "AraraTimeoutError",
23
+ ]
@@ -0,0 +1,78 @@
1
+ from typing import Optional
2
+ from arara_api_sdk.config import SDKConfig
3
+ from arara_api_sdk.http.client import HttpClient
4
+ from arara_api_sdk.resources.message import MessageResource
5
+ from arara_api_sdk.resources.template import TemplateResource
6
+ from arara_api_sdk.resources.organization import OrganizationResource
7
+ from arara_api_sdk.resources.user import UserResource
8
+ from arara_api_sdk.resources.brain import BrainResource
9
+ from arara_api_sdk.resources.campaign import CampaignResource
10
+ from arara_api_sdk.resources.payment import PaymentResource
11
+
12
+ class AraraClient:
13
+ """
14
+ Official Arara Python SDK Client.
15
+
16
+ Provides access to messages, templates, organizations, users, and AI brain features.
17
+ Supports both synchronous and asynchronous operations.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ api_key: Optional[str] = None,
23
+ base_url: Optional[str] = None,
24
+ timeout: Optional[float] = None,
25
+ max_retries: Optional[int] = None
26
+ ) -> None:
27
+ """Initializes the Arara SDK Client.
28
+
29
+ Args:
30
+ api_key: The Arara API Key. If not provided, will look for the
31
+ ARARA_API_KEY environment variable.
32
+ base_url: The base URL for the Arara API. Defaults to
33
+ https://api.arara.io.
34
+ timeout: Request timeout in seconds. Defaults to 30.0.
35
+ max_retries: Maximum number of request retries. Defaults to 3.
36
+ """
37
+ # Allow passing config directly or via env/defaults
38
+ config_kwargs = {}
39
+ if api_key: config_kwargs["api_key"] = api_key
40
+ if base_url: config_kwargs["base_url"] = base_url
41
+ if timeout: config_kwargs["timeout"] = timeout
42
+ if max_retries: config_kwargs["max_retries"] = max_retries
43
+
44
+ self.config = SDKConfig(**config_kwargs)
45
+ self._http = HttpClient(self.config)
46
+
47
+ # Initialize resources
48
+ self.messages = MessageResource(self._http)
49
+ self.templates = TemplateResource(self._http)
50
+ self.organizations = OrganizationResource(self._http)
51
+ self.users = UserResource(self._http)
52
+ self.brain = BrainResource(self._http)
53
+ self.campaigns = CampaignResource(self._http)
54
+ self.payments = PaymentResource(self._http)
55
+
56
+ def close(self) -> None:
57
+ """Closes the internal synchronous HTTP client."""
58
+ self._http.close()
59
+
60
+ async def aclose(self) -> None:
61
+ """Closes the internal asynchronous HTTP client."""
62
+ await self._http.aclose()
63
+
64
+ def __enter__(self) -> "AraraClient":
65
+ """Context manager entry point for synchronous use."""
66
+ return self
67
+
68
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
69
+ """Context manager exit point for synchronous use."""
70
+ self.close()
71
+
72
+ async def __aenter__(self) -> "AraraClient":
73
+ """Context manager entry point for asynchronous use."""
74
+ return self
75
+
76
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
77
+ """Context manager exit point for asynchronous use."""
78
+ await self.aclose()
@@ -0,0 +1,14 @@
1
+ from typing import Optional
2
+ from pydantic_settings import BaseSettings
3
+ from pydantic import Field
4
+
5
+ class SDKConfig(BaseSettings):
6
+ """SDK Configuration settings."""
7
+ api_key: str = Field(..., env="ARARA_API_KEY")
8
+ base_url: str = Field("https://api.arara.io", env="ARARA_BASE_URL")
9
+ timeout: float = Field(30.0, env="ARARA_TIMEOUT")
10
+ max_retries: int = Field(3, env="ARARA_MAX_RETRIES")
11
+
12
+ class Config:
13
+ env_prefix = "ARARA_"
14
+ case_sensitive = False
@@ -0,0 +1,41 @@
1
+ from typing import Optional, Dict, Any
2
+
3
+ class AraraError(Exception):
4
+ """Base exception for Arara SDK."""
5
+ def __init__(
6
+ self,
7
+ message: str,
8
+ status_code: Optional[int] = None,
9
+ response_body: Optional[Dict[str, Any]] = None
10
+ ):
11
+ super().__init__(message)
12
+ self.status_code = status_code
13
+ self.response_body = response_body
14
+
15
+ class AraraAuthError(AraraError):
16
+ """Raised when authentication fails."""
17
+ pass
18
+
19
+ class AraraValidationError(AraraError):
20
+ """Raised when request validation fails (400)."""
21
+ pass
22
+
23
+ class AraraRateLimitError(AraraError):
24
+ """Raised when rate limit is exceeded (429)."""
25
+ pass
26
+
27
+ class AraraResourceNotFoundError(AraraError):
28
+ """Raised when a resource is not found (404)."""
29
+ pass
30
+
31
+ class AraraServerError(AraraError):
32
+ """Raised when the server returns a 5xx error."""
33
+ pass
34
+
35
+ class AraraConnectionError(AraraError):
36
+ """Raised when a connection error occurs."""
37
+ pass
38
+
39
+ class AraraTimeoutError(AraraError):
40
+ """Raised when a request times out."""
41
+ pass
File without changes