chatapult 0.1.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.
- chatapult-0.1.0/.gitignore +207 -0
- chatapult-0.1.0/.pre-commit-config.yaml +35 -0
- chatapult-0.1.0/.vscode/settings.json +3 -0
- chatapult-0.1.0/CONTRIBUTING.md +90 -0
- chatapult-0.1.0/LICENSE +21 -0
- chatapult-0.1.0/PKG-INFO +115 -0
- chatapult-0.1.0/README.md +83 -0
- chatapult-0.1.0/images/banner.png +0 -0
- chatapult-0.1.0/pyproject.toml +47 -0
- chatapult-0.1.0/src/chatapult/__init__.py +28 -0
- chatapult-0.1.0/src/chatapult/async_client.py +82 -0
- chatapult-0.1.0/src/chatapult/client.py +85 -0
- chatapult-0.1.0/src/chatapult/exceptions.py +39 -0
- chatapult-0.1.0/src/chatapult/py.typed +0 -0
- chatapult-0.1.0/tests/test_clients.py +142 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
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
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
#poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
#pdm.lock
|
|
116
|
+
#pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
#pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# SageMath parsed files
|
|
135
|
+
*.sage.py
|
|
136
|
+
|
|
137
|
+
# Environments
|
|
138
|
+
.env
|
|
139
|
+
.envrc
|
|
140
|
+
.venv
|
|
141
|
+
env/
|
|
142
|
+
venv/
|
|
143
|
+
ENV/
|
|
144
|
+
env.bak/
|
|
145
|
+
venv.bak/
|
|
146
|
+
|
|
147
|
+
# Spyder project settings
|
|
148
|
+
.spyderproject
|
|
149
|
+
.spyproject
|
|
150
|
+
|
|
151
|
+
# Rope project settings
|
|
152
|
+
.ropeproject
|
|
153
|
+
|
|
154
|
+
# mkdocs documentation
|
|
155
|
+
/site
|
|
156
|
+
|
|
157
|
+
# mypy
|
|
158
|
+
.mypy_cache/
|
|
159
|
+
.dmypy.json
|
|
160
|
+
dmypy.json
|
|
161
|
+
|
|
162
|
+
# Pyre type checker
|
|
163
|
+
.pyre/
|
|
164
|
+
|
|
165
|
+
# pytype static type analyzer
|
|
166
|
+
.pytype/
|
|
167
|
+
|
|
168
|
+
# Cython debug symbols
|
|
169
|
+
cython_debug/
|
|
170
|
+
|
|
171
|
+
# PyCharm
|
|
172
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
173
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
174
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
175
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
176
|
+
#.idea/
|
|
177
|
+
|
|
178
|
+
# Abstra
|
|
179
|
+
# Abstra is an AI-powered process automation framework.
|
|
180
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
181
|
+
# Learn more at https://abstra.io/docs
|
|
182
|
+
.abstra/
|
|
183
|
+
|
|
184
|
+
# Visual Studio Code
|
|
185
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
186
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
188
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
189
|
+
# .vscode/
|
|
190
|
+
|
|
191
|
+
# Ruff stuff:
|
|
192
|
+
.ruff_cache/
|
|
193
|
+
|
|
194
|
+
# PyPI configuration file
|
|
195
|
+
.pypirc
|
|
196
|
+
|
|
197
|
+
# Cursor
|
|
198
|
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
|
199
|
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
|
200
|
+
# refer to https://docs.cursor.com/context/ignore-files
|
|
201
|
+
.cursorignore
|
|
202
|
+
.cursorindexingignore
|
|
203
|
+
|
|
204
|
+
# Marimo
|
|
205
|
+
marimo/_static/
|
|
206
|
+
marimo/_lsp/
|
|
207
|
+
__marimo__/
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# .pre-commit-config.yaml
|
|
2
|
+
# Run `pre-commit install` to set up the git hook scripts.
|
|
3
|
+
|
|
4
|
+
repos:
|
|
5
|
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
6
|
+
rev: v6.0.0
|
|
7
|
+
hooks:
|
|
8
|
+
- id: trailing-whitespace
|
|
9
|
+
- id: end-of-file-fixer
|
|
10
|
+
- id: check-yaml
|
|
11
|
+
- id: check-toml
|
|
12
|
+
- id: check-added-large-files
|
|
13
|
+
args: ['--maxkb=500']
|
|
14
|
+
- id: check-ast
|
|
15
|
+
- id: check-merge-conflict
|
|
16
|
+
- id: requirements-txt-fixer
|
|
17
|
+
|
|
18
|
+
- repo: https://github.com/psf/black
|
|
19
|
+
rev: 26.3.1
|
|
20
|
+
hooks:
|
|
21
|
+
- id: black
|
|
22
|
+
language_version: python3
|
|
23
|
+
|
|
24
|
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
|
25
|
+
rev: v0.15.7
|
|
26
|
+
hooks:
|
|
27
|
+
- id: ruff
|
|
28
|
+
args: [ --fix ]
|
|
29
|
+
- id: ruff-format
|
|
30
|
+
|
|
31
|
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
|
32
|
+
rev: v1.19.1
|
|
33
|
+
hooks:
|
|
34
|
+
- id: mypy
|
|
35
|
+
additional_dependencies: [types-requests]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Contributing to Chatapult
|
|
2
|
+
|
|
3
|
+
First, thank you for your interest in contributing to Chatapult. Building a robust, async-ready Python API wrapper for Google Chat webhooks is a community effort, and we welcome contributions of all kinds—from bug reports and documentation improvements to new feature implementations.
|
|
4
|
+
|
|
5
|
+
This document outlines the standard processes and coding guidelines for contributing to the Chatapult repository. By following these steps, you help ensure that the integration process is smooth, efficient, and transparent.
|
|
6
|
+
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
1. [Code of Conduct](#code-of-conduct)
|
|
10
|
+
2. [Reporting Bugs and Requesting Features](#reporting-bugs-and-requesting-features)
|
|
11
|
+
3. [Development Guidelines](#development-guidelines)
|
|
12
|
+
4. [Commit Message Stands](#commit-message-standards)
|
|
13
|
+
5. [Pull Request Process](#pull-request-process)
|
|
14
|
+
|
|
15
|
+
## Code of Conduct
|
|
16
|
+
|
|
17
|
+
We are committed to providing a welcoming and inspiring community for everyone. Be professional, respectful, and constructive in your communications. Harassment or abusive behavior will not be tolerated.
|
|
18
|
+
|
|
19
|
+
## Reporting Bugs and Requesting Features
|
|
20
|
+
|
|
21
|
+
GitHub Issues will be used to track public bugs and feature requests.
|
|
22
|
+
|
|
23
|
+
### Bug Reports
|
|
24
|
+
|
|
25
|
+
If you find a bug in the webhook client, please open an issue and include:
|
|
26
|
+
* A clear, descriptive title.
|
|
27
|
+
* The version of Python and Chatapult you are using.
|
|
28
|
+
* Steps to reproduce the unexpected behavior.
|
|
29
|
+
* Expected results versus actual results.
|
|
30
|
+
* Relevant tracebacks or error messages.
|
|
31
|
+
|
|
32
|
+
### Feature Requests
|
|
33
|
+
|
|
34
|
+
When requesting new features (such as support for new Google Workspace API cards or widgets), please provide:
|
|
35
|
+
* A clear description of the proposed feature.
|
|
36
|
+
* The specific use case or problem it solves.
|
|
37
|
+
* Any relevant links to the official Google Chat developer documentation.
|
|
38
|
+
|
|
39
|
+
## Development Guidelines
|
|
40
|
+
|
|
41
|
+
To ensure the codebase remains maintainable, highly adoptable, and standard across all contributors, we strictly adhere to automated code quality checks using `pre-commit`.
|
|
42
|
+
|
|
43
|
+
### Setting Up Pre-Commit Hooks
|
|
44
|
+
|
|
45
|
+
We use `pre-commit` to automatically run formatting (`black`), linting (`ruff`), and type-checking (`mypy`) every time you make a commit. This catches errors locally before the code is added to the codebase.
|
|
46
|
+
|
|
47
|
+
1. **Install the pre-commit package:**
|
|
48
|
+
```bash
|
|
49
|
+
pip install pre-commit
|
|
50
|
+
```
|
|
51
|
+
2. ** Install the git hooks:** Run this once in your local repository.
|
|
52
|
+
```bash
|
|
53
|
+
pre-commit install
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Now, every time you run `git commit`, the hooks will automatically format your code and check for errors.
|
|
57
|
+
|
|
58
|
+
### Coding Standards
|
|
59
|
+
|
|
60
|
+
* **Type Hinting:** All new functions, methods, and classes must include strict Python type hints (`typing` module). The `mypy` pre-commit hook will fail if types are missing or incorrect.
|
|
61
|
+
* **Manual Hook Execution:** If you want to run the checks manually across all files without making a commit, you can run:
|
|
62
|
+
```bash
|
|
63
|
+
pre-commit run --all-files
|
|
64
|
+
```
|
|
65
|
+
* **Testing:** We use `pytest` for our test suite. All new features must include corresponding unit tests. Bug fixes must include a test that verifies the fix. Run the test suite locally using:
|
|
66
|
+
```bash
|
|
67
|
+
pytest
|
|
68
|
+
```
|
|
69
|
+
* **Documentation:** If you change the behavior of the API client or add new models, you must update the `README.md` and inline docstrings accordingly.
|
|
70
|
+
|
|
71
|
+
## Commit Message Standards
|
|
72
|
+
|
|
73
|
+
We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification. This leads to more readable project history and allows us to automate release notes.
|
|
74
|
+
|
|
75
|
+
Format: `<type>(<scope>): <subject>`
|
|
76
|
+
|
|
77
|
+
**Examples:**
|
|
78
|
+
* `feat(client): add async support for sending v2 cards`
|
|
79
|
+
* `fix(auth): resolve environment variable loading error`
|
|
80
|
+
* `docs(readme): update advanced usage examples`
|
|
81
|
+
* `test(models): add unit tests for image widget`
|
|
82
|
+
|
|
83
|
+
## Pull Request Process
|
|
84
|
+
|
|
85
|
+
1. **Create a Branch:** Always branch off of `main`. Name your branch descriptively (e.g., `feature/async-client` or `bugfix/rate-limit-retry`).
|
|
86
|
+
2. **Draft your PR:** Push your branch to your fork and open a Pull Request against the upstream `main` branch.
|
|
87
|
+
3. **Fill out the PR Template:** Provide a clear summary of your changes, the rationale, and link to any related issues (e.g., "Closes #12").
|
|
88
|
+
4. **Review:** A maintainer will review your code. Be prepared to make requested changes. Once approved, your PR will be merged.
|
|
89
|
+
|
|
90
|
+
Thank you for helping make Chatapult the easiest way to integrate Google Chat notifications into Python!
|
chatapult-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Demetrios Lambropoulos
|
|
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.
|
chatapult-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chatapult
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A fast, Pythonic API wrapper for Google Chat webhooks.
|
|
5
|
+
Author-email: Demetrios Lambropoulos <d.lambropoulos@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: api,async,google chat,notifications,webhook,wrapper
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Communications :: Chat
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Requires-Dist: httpx>=0.24.0
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: black>=24.0; extra == 'dev'
|
|
24
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
25
|
+
Requires-Dist: pre-commit>=3.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-httpx>=0.22.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: ruff>=0.3; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
|
|
35
|
+
# Chatapult
|
|
36
|
+
|
|
37
|
+
A fast, Pythonic API wrapper for Google Chat webhooks.
|
|
38
|
+
|
|
39
|
+
Chatapult is designed to make sending automated notifications, CI/CD alerts, and rich UI cards to Google Workspace Spaces effortless. Whether you need a simple synchronous alert or a high-throughput async notification integration, Chatapult handles the boilerplate so you can focus on your application.
|
|
40
|
+
|
|
41
|
+

|
|
42
|
+
[](LICENSE)
|
|
43
|
+
[](https://github.com/psf/black)
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
* **Zero Boilerplate:** Send a message to a Google Chat Space in three lines of code.
|
|
48
|
+
* **Async Ready:** First-class support for `asyncio`, making it perfect for FastAPI, Discord bots, and high-concurrency event loops.
|
|
49
|
+
* **Rich V2 Cards (Coming Soon):** Construct complex Google Chat Cards and Widgets using clean Python objects instead of nested JSON.
|
|
50
|
+
* **Threaded Replies:** Easily group related alerts by replying to specific message threads.
|
|
51
|
+
* **Fully Typed:** Built with standard Python type hints for excellent IDE autocomplete and static checking.
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
Install via pip:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install chatapult
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Quick Start
|
|
62
|
+
|
|
63
|
+
**Security Note:** Never hardcode your webhook URLs. Always load them securely from environment variables or a secrets manager.
|
|
64
|
+
|
|
65
|
+
### Synchronous Usage
|
|
66
|
+
|
|
67
|
+
Perfect for simple scripts, cron jobs, or basic data pipelines.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import os
|
|
71
|
+
from chatapult import ChatClient, APIError
|
|
72
|
+
|
|
73
|
+
webhook_url = os.environ.get("GOOGLE_CHAT_WEBHOOK_URL")
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
with ChatClient(webhook_url) as client:
|
|
77
|
+
response = client.send_message("Hello from Chatapult!")
|
|
78
|
+
print("Message sent successfully!")
|
|
79
|
+
except APIError as e:
|
|
80
|
+
print(f"Failed to send message: {e}")
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Asynchronous Usage
|
|
84
|
+
|
|
85
|
+
Ideal for web servers, async task queues, or applications where you cannot block the main thread.
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import asyncio
|
|
89
|
+
import os
|
|
90
|
+
from chatapult import AsyncChatClient, NetworkError
|
|
91
|
+
|
|
92
|
+
async def main():
|
|
93
|
+
webhook_url = os.environ.get("GOOGLE_CHAT_WEBHOOK_URL")
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
async with AsyncChatClient(webhook_url) as client:
|
|
97
|
+
await client.send_message("Hello from the async event loop!")
|
|
98
|
+
print("Async message sent successfully!")
|
|
99
|
+
except NetworkError as e:
|
|
100
|
+
print(f"Network issue encountered: {e}")
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
asyncio.run(main())
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Advanced Usage
|
|
107
|
+
|
|
108
|
+
Documentation for sending V2 Cards, threaded replies, and handling rate-limit exceptions will be added here as features are released.
|
|
109
|
+
|
|
110
|
+
## Contributing
|
|
111
|
+
Contributions are welcome! If you'd like to help improve Chatapult, please review our [Contributing Guidelines](CONTRIBUTING.md) and open an issue or pull request.
|
|
112
|
+
|
|
113
|
+
## License
|
|
114
|
+
|
|
115
|
+
This project is licensed under the MIT License - see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# Chatapult
|
|
4
|
+
|
|
5
|
+
A fast, Pythonic API wrapper for Google Chat webhooks.
|
|
6
|
+
|
|
7
|
+
Chatapult is designed to make sending automated notifications, CI/CD alerts, and rich UI cards to Google Workspace Spaces effortless. Whether you need a simple synchronous alert or a high-throughput async notification integration, Chatapult handles the boilerplate so you can focus on your application.
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
[](LICENSE)
|
|
11
|
+
[](https://github.com/psf/black)
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
* **Zero Boilerplate:** Send a message to a Google Chat Space in three lines of code.
|
|
16
|
+
* **Async Ready:** First-class support for `asyncio`, making it perfect for FastAPI, Discord bots, and high-concurrency event loops.
|
|
17
|
+
* **Rich V2 Cards (Coming Soon):** Construct complex Google Chat Cards and Widgets using clean Python objects instead of nested JSON.
|
|
18
|
+
* **Threaded Replies:** Easily group related alerts by replying to specific message threads.
|
|
19
|
+
* **Fully Typed:** Built with standard Python type hints for excellent IDE autocomplete and static checking.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
Install via pip:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install chatapult
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
**Security Note:** Never hardcode your webhook URLs. Always load them securely from environment variables or a secrets manager.
|
|
32
|
+
|
|
33
|
+
### Synchronous Usage
|
|
34
|
+
|
|
35
|
+
Perfect for simple scripts, cron jobs, or basic data pipelines.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from chatapult import ChatClient, APIError
|
|
40
|
+
|
|
41
|
+
webhook_url = os.environ.get("GOOGLE_CHAT_WEBHOOK_URL")
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
with ChatClient(webhook_url) as client:
|
|
45
|
+
response = client.send_message("Hello from Chatapult!")
|
|
46
|
+
print("Message sent successfully!")
|
|
47
|
+
except APIError as e:
|
|
48
|
+
print(f"Failed to send message: {e}")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Asynchronous Usage
|
|
52
|
+
|
|
53
|
+
Ideal for web servers, async task queues, or applications where you cannot block the main thread.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import asyncio
|
|
57
|
+
import os
|
|
58
|
+
from chatapult import AsyncChatClient, NetworkError
|
|
59
|
+
|
|
60
|
+
async def main():
|
|
61
|
+
webhook_url = os.environ.get("GOOGLE_CHAT_WEBHOOK_URL")
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
async with AsyncChatClient(webhook_url) as client:
|
|
65
|
+
await client.send_message("Hello from the async event loop!")
|
|
66
|
+
print("Async message sent successfully!")
|
|
67
|
+
except NetworkError as e:
|
|
68
|
+
print(f"Network issue encountered: {e}")
|
|
69
|
+
|
|
70
|
+
if __name__ == "__main__":
|
|
71
|
+
asyncio.run(main())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Advanced Usage
|
|
75
|
+
|
|
76
|
+
Documentation for sending V2 Cards, threaded replies, and handling rate-limit exceptions will be added here as features are released.
|
|
77
|
+
|
|
78
|
+
## Contributing
|
|
79
|
+
Contributions are welcome! If you'd like to help improve Chatapult, please review our [Contributing Guidelines](CONTRIBUTING.md) and open an issue or pull request.
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
This project is licensed under the MIT License - see [LICENSE](LICENSE) for details.
|
|
Binary file
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "chatapult"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A fast, Pythonic API wrapper for Google Chat webhooks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Demetrios Lambropoulos", email = "d.lambropoulos@gmail.com" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["google chat", "webhook", "api", "wrapper", "notifications", "async"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.8",
|
|
22
|
+
"Programming Language :: Python :: 3.9",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Topic :: Communications :: Chat",
|
|
27
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
28
|
+
]
|
|
29
|
+
# httpx handles both sync and async requests, keeping our footprint small.
|
|
30
|
+
dependencies = [
|
|
31
|
+
"httpx>=0.24.0",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest>=7.0",
|
|
37
|
+
"pytest-httpx>=0.22.0",
|
|
38
|
+
"pytest-asyncio>=0.21.0",
|
|
39
|
+
"pytest-cov>=4.1.0",
|
|
40
|
+
"black>=24.0",
|
|
41
|
+
"ruff>=0.3",
|
|
42
|
+
"mypy>=1.8",
|
|
43
|
+
"pre-commit>=3.0",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.wheel]
|
|
47
|
+
packages = ["src/chatapult"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Chatapult: A fast, Pythonic API wrapper for Google Chat webhooks.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
# Explicitly define the version so developers can check it programmatically
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
# Import the core components to expose them at the top level of the package
|
|
9
|
+
from .client import ChatClient
|
|
10
|
+
from .async_client import AsyncChatClient
|
|
11
|
+
from .exceptions import (
|
|
12
|
+
APIError,
|
|
13
|
+
ChatapultError,
|
|
14
|
+
ConfigurationError,
|
|
15
|
+
NetworkError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
# The __all__ list strictly defines the public API of your module.
|
|
19
|
+
# It tells IDEs and linters exactly what is safe for end-users to import,
|
|
20
|
+
# and hides internal modules (like 'logging' or 'httpx') from autocomplete.
|
|
21
|
+
__all__ = [
|
|
22
|
+
"APIError",
|
|
23
|
+
"AsyncChatClient",
|
|
24
|
+
"ChatClient",
|
|
25
|
+
"ChatapultError",
|
|
26
|
+
"ConfigurationError",
|
|
27
|
+
"NetworkError",
|
|
28
|
+
]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
|
|
6
|
+
from .exceptions import APIError, ConfigurationError, NetworkError
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AsyncChatClient:
|
|
12
|
+
"""
|
|
13
|
+
An asynchronous client for interacting with Google Chat Webhooks.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, webhook_url: str, timeout: float = 10.0) -> None:
|
|
17
|
+
"""
|
|
18
|
+
Initialize the AsyncChatClient.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
webhook_url (str): The full Google Chat webhook URL.
|
|
22
|
+
timeout (float): Connection timeout in seconds. Defaults to 10.0.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
ConfigurationError: If the webhook_url is empty.
|
|
26
|
+
"""
|
|
27
|
+
if not webhook_url:
|
|
28
|
+
raise ConfigurationError("A valid webhook_url must be provided.")
|
|
29
|
+
|
|
30
|
+
self.webhook_url = webhook_url
|
|
31
|
+
self._client = httpx.AsyncClient(timeout=timeout)
|
|
32
|
+
|
|
33
|
+
async def send_message(
|
|
34
|
+
self, text: str, thread_name: Optional[str] = None
|
|
35
|
+
) -> Dict[str, Any]:
|
|
36
|
+
"""
|
|
37
|
+
Asynchronously send a simple text message to the Google Chat Space.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
text (str): The markdown-formatted text to send.
|
|
41
|
+
thread_name (Optional[str]): The ID of an existing thread to reply to.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
Dict[str, Any]: The JSON response from the Google Chat API.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
APIError: If the Google API returns a non-200 status code.
|
|
48
|
+
NetworkError: If the connection times out or fails.
|
|
49
|
+
"""
|
|
50
|
+
payload: Dict[str, Any] = {"text": text}
|
|
51
|
+
|
|
52
|
+
if thread_name:
|
|
53
|
+
payload["thread"] = {"name": thread_name}
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
response = await self._client.post(self.webhook_url, json=payload)
|
|
57
|
+
response.raise_for_status()
|
|
58
|
+
return response.json()
|
|
59
|
+
|
|
60
|
+
except httpx.HTTPStatusError as e:
|
|
61
|
+
logger.error(
|
|
62
|
+
f"Google Chat API error: {e.response.status_code} - {e.response.text}"
|
|
63
|
+
)
|
|
64
|
+
raise APIError(
|
|
65
|
+
message=f"API request failed: {e.response.text}",
|
|
66
|
+
status_code=e.response.status_code,
|
|
67
|
+
) from e
|
|
68
|
+
except httpx.RequestError as e:
|
|
69
|
+
logger.error(f"Network error while connecting to Google Chat: {e}")
|
|
70
|
+
raise NetworkError(f"Network request failed: {str(e)}") from e
|
|
71
|
+
|
|
72
|
+
async def aclose(self) -> None:
|
|
73
|
+
"""Close the underlying asynchronous HTTP client connections."""
|
|
74
|
+
await self._client.aclose()
|
|
75
|
+
|
|
76
|
+
async def __aenter__(self) -> "AsyncChatClient":
|
|
77
|
+
"""Enable usage as an asynchronous context manager."""
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
81
|
+
"""Ensure connections are closed when exiting the context manager."""
|
|
82
|
+
await self.aclose()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
|
|
6
|
+
# Import our new custom exceptions
|
|
7
|
+
from .exceptions import APIError, ConfigurationError, NetworkError
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ChatClient:
|
|
13
|
+
"""
|
|
14
|
+
A synchronous client for interacting with Google Chat Webhooks.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, webhook_url: str, timeout: float = 10.0) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Initialize the ChatClient.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
webhook_url (str): The full Google Chat webhook URL.
|
|
23
|
+
timeout (float): Connection timeout in seconds. Defaults to 10.0.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
ConfigurationError: If the webhook_url is empty or invalid.
|
|
27
|
+
"""
|
|
28
|
+
if not webhook_url:
|
|
29
|
+
raise ConfigurationError("A valid webhook_url must be provided.")
|
|
30
|
+
|
|
31
|
+
self.webhook_url = webhook_url
|
|
32
|
+
self._client = httpx.Client(timeout=timeout)
|
|
33
|
+
|
|
34
|
+
def send_message(
|
|
35
|
+
self, text: str, thread_name: Optional[str] = None
|
|
36
|
+
) -> Dict[str, Any]:
|
|
37
|
+
"""
|
|
38
|
+
Send a simple text message to the configured Google Chat Space.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
text (str): The markdown-formatted text to send.
|
|
42
|
+
thread_name (Optional[str]): The ID of an existing thread to reply to
|
|
43
|
+
(e.g., 'spaces/SPACE_ID/threads/THREAD_ID').
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Dict[str, Any]: The JSON response from the Google Chat API representing the message.
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
APIError: If the Google API returns a non-200 status code.
|
|
50
|
+
NetworkError: If the network connection times out or fails.
|
|
51
|
+
"""
|
|
52
|
+
payload: Dict[str, Any] = {"text": text}
|
|
53
|
+
|
|
54
|
+
if thread_name:
|
|
55
|
+
payload["thread"] = {"name": thread_name}
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
response = self._client.post(self.webhook_url, json=payload)
|
|
59
|
+
response.raise_for_status()
|
|
60
|
+
return response.json()
|
|
61
|
+
|
|
62
|
+
except httpx.HTTPStatusError as e:
|
|
63
|
+
logger.error(
|
|
64
|
+
f"Google Chat API error: {e.response.status_code} - {e.response.text}"
|
|
65
|
+
)
|
|
66
|
+
raise APIError(
|
|
67
|
+
message=f"API request failed: {e.response.text}",
|
|
68
|
+
status_code=e.response.status_code,
|
|
69
|
+
) from e
|
|
70
|
+
|
|
71
|
+
except httpx.RequestError as e:
|
|
72
|
+
logger.error(f"Network error while connecting to Google Chat: {e}")
|
|
73
|
+
raise NetworkError(f"Network request failed: {str(e)}") from e
|
|
74
|
+
|
|
75
|
+
def close(self) -> None:
|
|
76
|
+
"""Close the underlying HTTP client connections."""
|
|
77
|
+
self._client.close()
|
|
78
|
+
|
|
79
|
+
def __enter__(self) -> "ChatClient":
|
|
80
|
+
"""Enable usage as a context manager."""
|
|
81
|
+
return self
|
|
82
|
+
|
|
83
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
84
|
+
"""Ensure connections are closed when exiting the context manager."""
|
|
85
|
+
self.close()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom exceptions for the Chatapult library.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ChatapultError(Exception):
|
|
7
|
+
"""
|
|
8
|
+
Base exception class for all Chatapult errors.
|
|
9
|
+
All other custom exceptions in this library inherit from this base class,
|
|
10
|
+
allowing users to catch any Chatapult-related error with a single except block.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigurationError(ChatapultError):
|
|
17
|
+
"""
|
|
18
|
+
Raised when there is a configuration issue, such as an empty or invalid webhook URL.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class APIError(ChatapultError):
|
|
25
|
+
"""
|
|
26
|
+
Raised when the Google Chat API returns an HTTP error response (e.g., 400 or 404).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, message: str, status_code: int) -> None:
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.status_code = status_code
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class NetworkError(ChatapultError):
|
|
35
|
+
"""
|
|
36
|
+
Raised when a network connection fails, times out, or the host is unreachable.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
pass
|
|
File without changes
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
import json
|
|
3
|
+
import pytest
|
|
4
|
+
from pytest_httpx import HTTPXMock
|
|
5
|
+
|
|
6
|
+
from chatapult.client import ChatClient
|
|
7
|
+
from chatapult.async_client import AsyncChatClient
|
|
8
|
+
from chatapult.exceptions import APIError, ConfigurationError, NetworkError
|
|
9
|
+
|
|
10
|
+
# Dummy webhook URL for testing
|
|
11
|
+
WEBHOOK_URL = (
|
|
12
|
+
"https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
# Synchronous Client Tests
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_sync_client_init_empty_url() -> None:
|
|
22
|
+
"""Ensure ChatClient raises ConfigurationError if webhook is empty."""
|
|
23
|
+
with pytest.raises(ConfigurationError):
|
|
24
|
+
ChatClient(webhook_url="")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_sync_send_message_success(httpx_mock: HTTPXMock) -> None:
|
|
28
|
+
"""Test sending a basic text message successfully."""
|
|
29
|
+
mock_response = {"name": "spaces/SPACE/messages/MSG", "text": "Hello World!"}
|
|
30
|
+
httpx_mock.add_response(json=mock_response, status_code=200)
|
|
31
|
+
|
|
32
|
+
with ChatClient(WEBHOOK_URL) as client:
|
|
33
|
+
response = client.send_message("Hello World!")
|
|
34
|
+
|
|
35
|
+
assert response == mock_response
|
|
36
|
+
|
|
37
|
+
# Verify the correct payload was sent by parsing the JSON
|
|
38
|
+
request = httpx_mock.get_request()
|
|
39
|
+
assert request is not None
|
|
40
|
+
request_data = json.loads(request.read())
|
|
41
|
+
assert request_data["text"] == "Hello World!"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_sync_send_message_with_thread(httpx_mock: HTTPXMock) -> None:
|
|
45
|
+
"""Test sending a message to a specific thread."""
|
|
46
|
+
httpx_mock.add_response(json={}, status_code=200)
|
|
47
|
+
thread_id = "spaces/SPACE_ID/threads/THREAD_ID"
|
|
48
|
+
|
|
49
|
+
with ChatClient(WEBHOOK_URL) as client:
|
|
50
|
+
client.send_message("Reply message", thread_name=thread_id)
|
|
51
|
+
|
|
52
|
+
request = httpx_mock.get_request()
|
|
53
|
+
assert request is not None
|
|
54
|
+
|
|
55
|
+
# Verify thread payload is included by parsing the JSON
|
|
56
|
+
request_data = json.loads(request.read())
|
|
57
|
+
assert request_data["thread"]["name"] == "spaces/SPACE_ID/threads/THREAD_ID"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_sync_api_error(httpx_mock: HTTPXMock) -> None:
|
|
61
|
+
"""Test that HTTP errors are cleanly wrapped in our custom APIError."""
|
|
62
|
+
httpx_mock.add_response(status_code=400, text="Bad Request")
|
|
63
|
+
|
|
64
|
+
with ChatClient(WEBHOOK_URL) as client:
|
|
65
|
+
with pytest.raises(APIError) as exc_info:
|
|
66
|
+
client.send_message("This will fail")
|
|
67
|
+
|
|
68
|
+
assert exc_info.value.status_code == 400
|
|
69
|
+
assert "Bad Request" in str(exc_info.value)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_sync_network_error(httpx_mock: HTTPXMock) -> None:
|
|
73
|
+
"""Test that httpx connection errors are wrapped in our NetworkError."""
|
|
74
|
+
httpx_mock.add_exception(httpx.ReadTimeout("Connection timed out"))
|
|
75
|
+
|
|
76
|
+
with ChatClient(WEBHOOK_URL) as client:
|
|
77
|
+
with pytest.raises(NetworkError) as exc_info:
|
|
78
|
+
client.send_message("This will timeout")
|
|
79
|
+
|
|
80
|
+
assert "Connection timed out" in str(exc_info.value)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------------------------
|
|
84
|
+
# Asynchronous Client Tests
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_async_client_init_empty_url() -> None:
|
|
89
|
+
"""Ensure AsyncChatClient raises ConfigurationError if webhook is empty."""
|
|
90
|
+
with pytest.raises(ConfigurationError):
|
|
91
|
+
AsyncChatClient(webhook_url="")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@pytest.mark.asyncio
|
|
95
|
+
async def test_async_send_message_with_thread(httpx_mock: HTTPXMock) -> None:
|
|
96
|
+
"""Test sending a message to a specific thread (async)."""
|
|
97
|
+
httpx_mock.add_response(json={}, status_code=200)
|
|
98
|
+
thread_id = "spaces/SPACE_ID/threads/THREAD_ID"
|
|
99
|
+
|
|
100
|
+
async with AsyncChatClient(WEBHOOK_URL) as client:
|
|
101
|
+
await client.send_message("Async reply message", thread_name=thread_id)
|
|
102
|
+
|
|
103
|
+
request = httpx_mock.get_request()
|
|
104
|
+
assert request is not None
|
|
105
|
+
|
|
106
|
+
# Verify thread payload is included by parsing the JSON
|
|
107
|
+
request_data = json.loads(request.read())
|
|
108
|
+
assert request_data["thread"]["name"] == thread_id
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@pytest.mark.asyncio
|
|
112
|
+
async def test_async_send_message_success(httpx_mock: HTTPXMock) -> None:
|
|
113
|
+
"""Test sending a basic text message successfully (async)."""
|
|
114
|
+
mock_response = {"name": "spaces/SPACE/messages/MSG", "text": "Async Hello!"}
|
|
115
|
+
httpx_mock.add_response(json=mock_response, status_code=200)
|
|
116
|
+
|
|
117
|
+
async with AsyncChatClient(WEBHOOK_URL) as client:
|
|
118
|
+
response = await client.send_message("Async Hello!")
|
|
119
|
+
|
|
120
|
+
assert response == mock_response
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.mark.asyncio
|
|
124
|
+
async def test_async_api_error(httpx_mock: HTTPXMock) -> None:
|
|
125
|
+
"""Test that HTTP errors are cleanly wrapped in our custom APIError (async)."""
|
|
126
|
+
httpx_mock.add_response(status_code=404, text="Space not found")
|
|
127
|
+
|
|
128
|
+
async with AsyncChatClient(WEBHOOK_URL) as client:
|
|
129
|
+
with pytest.raises(APIError) as exc_info:
|
|
130
|
+
await client.send_message("This will fail")
|
|
131
|
+
|
|
132
|
+
assert exc_info.value.status_code == 404
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@pytest.mark.asyncio
|
|
136
|
+
async def test_async_network_error(httpx_mock: HTTPXMock) -> None:
|
|
137
|
+
"""Test that network errors are wrapped in our NetworkError (async)."""
|
|
138
|
+
httpx_mock.add_exception(httpx.ConnectError("Network unreachable"))
|
|
139
|
+
|
|
140
|
+
async with AsyncChatClient(WEBHOOK_URL) as client:
|
|
141
|
+
with pytest.raises(NetworkError):
|
|
142
|
+
await client.send_message("This will fail")
|