aiohttp-ai-chatbot 1.0.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.
@@ -0,0 +1,6 @@
1
+ """Adds the Asyntai AI chat assistant to aiohttp sites."""
2
+ from .middleware import DEFAULT_SKIP_PATHS, asyntai_middleware, setup
3
+ from .snippet import asyntai_widget, widget_snippet
4
+
5
+ __all__ = ['DEFAULT_SKIP_PATHS', 'asyntai_middleware', 'asyntai_widget', 'setup', 'widget_snippet']
6
+ __version__ = '1.0.0'
@@ -0,0 +1,121 @@
1
+ """Puts the chat widget on every HTML page of an aiohttp site, with no template edit.
2
+
3
+ The middleware only touches complete web.Response objects that carry an HTML
4
+ page with status 200. Everything else passes through untouched: JSON, files
5
+ from add_static or web.FileResponse, prepared streams, websockets and
6
+ redirects.
7
+ """
8
+ from aiohttp import web
9
+
10
+ from .snippet import MARKER, resolve_widget_id, widget_snippet
11
+ from .utils import clean_script_url
12
+
13
+ BODY_CLOSE = b'</body>'
14
+
15
+ #: Paths the widget never touches by default. A path that ends in * matches
16
+ #: the path itself and everything below it.
17
+ DEFAULT_SKIP_PATHS = ('/admin*',)
18
+
19
+ #: The key under which setup() stores its settings on the application.
20
+ APP_KEY = 'aiohttp_ai_chatbot'
21
+
22
+
23
+ def path_is_skipped(path, skip_paths):
24
+ """Answer whether the widget must stay off on this path."""
25
+ for rule in skip_paths:
26
+ if rule.endswith('*'):
27
+ base = rule[:-1].rstrip('/')
28
+ if path == base or path.startswith(base + '/'):
29
+ return True
30
+ elif path == rule:
31
+ return True
32
+ return False
33
+
34
+
35
+ def insert_snippet(body, snippet, charset='utf-8'):
36
+ """Return the page with the snippet before the last </body>, or None.
37
+
38
+ None means "leave the page as it is": the page has no closing body tag,
39
+ it already carries the widget, or it is not readable text.
40
+ """
41
+ if MARKER.encode() in body or b'data-asyntai-id' in body:
42
+ return None
43
+
44
+ if BODY_CLOSE not in body.lower():
45
+ return None
46
+
47
+ try:
48
+ html = body.decode(charset)
49
+ encoded_snippet = snippet.encode(charset)
50
+ except (UnicodeError, LookupError):
51
+ return None
52
+
53
+ # Split on the last closing tag, so a page that prints the tag inside an
54
+ # example or a code block is left alone.
55
+ index = html.lower().rfind('</body>')
56
+ if index < 0:
57
+ return None
58
+ return html[:index].encode(charset) + encoded_snippet + html[index:].encode(charset)
59
+
60
+
61
+ def asyntai_middleware(widget_id=None, skip_paths=DEFAULT_SKIP_PATHS, script_url=None):
62
+ """Return an aiohttp middleware that inserts the widget before </body>.
63
+
64
+ widget_id the ID from the Asyntai dashboard; without it, the
65
+ ASYNTAI_WIDGET_ID environment variable (read on every
66
+ request, so the ID can change without a code change)
67
+ skip_paths paths the widget never touches
68
+ script_url change only if Asyntai support asks
69
+
70
+ app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
71
+ """
72
+ skip = tuple(skip_paths or ())
73
+
74
+ @web.middleware
75
+ async def asyntai_widget_middleware(request, handler):
76
+ response = await handler(request)
77
+
78
+ if request.method == 'HEAD' or path_is_skipped(request.path or '/', skip):
79
+ return response
80
+
81
+ if not resolve_widget_id(widget_id) or not clean_script_url(script_url):
82
+ return response
83
+
84
+ if _can_carry_widget(response):
85
+ snippet = widget_snippet(widget_id, script_url)
86
+ new_body = insert_snippet(response.body, snippet, response.charset or 'utf-8') if snippet else None
87
+ if new_body is not None:
88
+ # The body setter also sets the new Content-Length.
89
+ response.body = new_body
90
+
91
+ return response
92
+
93
+ return asyntai_widget_middleware
94
+
95
+
96
+ def setup(app, widget_id=None, skip_paths=DEFAULT_SKIP_PATHS, script_url=None):
97
+ """Add the widget middleware to an application before it starts.
98
+
99
+ from aiohttp_ai_chatbot import setup
100
+ setup(app, widget_id="asyntai_ab12cd34")
101
+ """
102
+ middleware = asyntai_middleware(widget_id=widget_id, skip_paths=skip_paths, script_url=script_url)
103
+ app.middlewares.append(middleware)
104
+ return middleware
105
+
106
+
107
+ def _can_carry_widget(response):
108
+ # A FileResponse or a hand-made StreamResponse is not a web.Response,
109
+ # and a prepared response has already left; neither can change.
110
+ if not isinstance(response, web.Response) or response.prepared:
111
+ return False
112
+
113
+ if response.status != 200 or response.headers.get('Content-Encoding'):
114
+ return False
115
+
116
+ if response.content_type != 'text/html':
117
+ return False
118
+
119
+ # A body object (a file, a stream) is sent piece by piece; only plain
120
+ # bytes can be read and changed here.
121
+ return isinstance(response.body, (bytes, bytearray))
@@ -0,0 +1,82 @@
1
+ """The HTML that loads the chat widget, for the middleware and for templates."""
2
+ import os
3
+ from html import escape
4
+
5
+ from .utils import clean_script_url, clean_widget_id
6
+
7
+ #: Text that only this package writes. The middleware looks for it, so the
8
+ #: widget is never added twice.
9
+ MARKER = 'asyntai-widget-config'
10
+
11
+ _TEMPLATE = (
12
+ '<div class="' + MARKER + '" data-asyntai-widget="__WIDGET_ID__" '
13
+ 'data-asyntai-src="__SCRIPT_URL__" style="display: none"></div>\n'
14
+ '<script>\n'
15
+ ' // Loads the Asyntai chat widget after the page has finished loading,\n'
16
+ ' // so the site draws first and page speed does not change. The two\n'
17
+ ' // values arrive on a data attribute, so nothing is ever written into\n'
18
+ ' // the script itself.\n'
19
+ ' (function () {\n'
20
+ " var config = document.querySelector('." + MARKER + "');\n"
21
+ ' if (!config) { return; }\n'
22
+ '\n'
23
+ " var widgetId = config.getAttribute('data-asyntai-widget') || '';\n"
24
+ " var scriptUrl = config.getAttribute('data-asyntai-src') || '';\n"
25
+ " if (!widgetId || scriptUrl.indexOf('https://') !== 0) { return; }\n"
26
+ '\n'
27
+ ' var load = function () {\n'
28
+ " if (document.querySelector('script[data-asyntai-id]')) { return; }\n"
29
+ '\n'
30
+ " var script = document.createElement('script');\n"
31
+ ' script.src = scriptUrl;\n'
32
+ ' script.async = true;\n'
33
+ " script.setAttribute('data-asyntai-id', widgetId);\n"
34
+ ' document.head.appendChild(script);\n'
35
+ ' };\n'
36
+ '\n'
37
+ " if (document.readyState === 'complete') {\n"
38
+ ' load();\n'
39
+ ' } else {\n'
40
+ " window.addEventListener('load', load);\n"
41
+ ' }\n'
42
+ ' }());\n'
43
+ '</script>\n'
44
+ )
45
+
46
+
47
+ def resolve_widget_id(widget_id=None):
48
+ """The given ID, or the ASYNTAI_WIDGET_ID environment variable."""
49
+ if widget_id is None:
50
+ widget_id = os.environ.get('ASYNTAI_WIDGET_ID', '')
51
+ return clean_widget_id(widget_id)
52
+
53
+
54
+ def widget_snippet(widget_id=None, script_url=None):
55
+ """Return the widget HTML, or an empty string when the chat must stay off.
56
+
57
+ Without a widget_id, the ASYNTAI_WIDGET_ID environment variable is used.
58
+ """
59
+ clean_id = resolve_widget_id(widget_id)
60
+ clean_url = clean_script_url(script_url)
61
+ if not clean_id or not clean_url:
62
+ return ''
63
+
64
+ return (_TEMPLATE
65
+ .replace('__WIDGET_ID__', escape(clean_id, quote=True))
66
+ .replace('__SCRIPT_URL__', escape(clean_url, quote=True)))
67
+
68
+
69
+ def asyntai_widget(widget_id=None, script_url=None):
70
+ """Template helper: the same HTML, marked safe for Jinja2.
71
+
72
+ With aiohttp-jinja2, register it once, then write {{ asyntai_widget() }}
73
+ before </body>:
74
+
75
+ aiohttp_jinja2.get_env(app).globals['asyntai_widget'] = asyntai_widget
76
+ """
77
+ html = widget_snippet(widget_id, script_url)
78
+ try:
79
+ from markupsafe import Markup
80
+ except ImportError: # Jinja2 is optional.
81
+ return html
82
+ return Markup(html)
@@ -0,0 +1,57 @@
1
+ """Reading and checking the two values the widget needs.
2
+
3
+ Every decision the package makes about a configured value lives here, so the
4
+ tests can run it on its own.
5
+ """
6
+ import re
7
+
8
+ DEFAULT_SCRIPT_URL = 'https://widget.asyntai.com/static/js/chat-widget.js'
9
+
10
+ #: Shape of a widget identifier from the Asyntai dashboard.
11
+ ID_PATTERN = re.compile(r'^asyntai_[A-Za-z0-9]{6,64}$')
12
+
13
+ #: The identifier inside a pasted snippet.
14
+ SNIPPET_PATTERN = re.compile(r'data-asyntai-id\s*=\s*["\']([^"\']+)["\']')
15
+
16
+ _HTTPS_PATTERN = re.compile(r'^https://[^\s"\'<>]+$', re.IGNORECASE)
17
+
18
+
19
+ def clean_widget_id(raw):
20
+ """Return a usable widget identifier, or an empty string.
21
+
22
+ Accepts a bare identifier or the whole snippet from the Asyntai
23
+ dashboard, because people paste the snippet. An empty string means the
24
+ chat stays off, which is how you switch it off again.
25
+ """
26
+ if not isinstance(raw, str):
27
+ return ''
28
+
29
+ value = raw.strip()
30
+ if not value:
31
+ return ''
32
+
33
+ match = SNIPPET_PATTERN.search(value)
34
+ if match:
35
+ value = match.group(1).strip()
36
+
37
+ return value if ID_PATTERN.match(value) else ''
38
+
39
+
40
+ def clean_script_url(raw):
41
+ """Return the script address, or an empty string when the value is bad.
42
+
43
+ Only an https address is accepted, so a bad value can never put a
44
+ javascript: URL on every page of the site. No value means the Asyntai
45
+ address.
46
+ """
47
+ if raw is None:
48
+ return DEFAULT_SCRIPT_URL
49
+
50
+ if not isinstance(raw, str):
51
+ return ''
52
+
53
+ value = raw.strip()
54
+ if not value:
55
+ return DEFAULT_SCRIPT_URL
56
+
57
+ return value if _HTTPS_PATTERN.match(value) else ''
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiohttp-ai-chatbot
3
+ Version: 1.0.0
4
+ Summary: Adds the Asyntai AI chat assistant to aiohttp sites. It answers visitor questions from your own content, in more than 80 languages.
5
+ Author-email: Asyntai <hello@asyntai.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://asyntai.com
8
+ Project-URL: Documentation, https://asyntai.com/documentation/integrations/aiohttp/
9
+ Project-URL: Source, https://github.com/asyntai/aiohttp-ai-chatbot
10
+ Project-URL: Issues, https://github.com/asyntai/aiohttp-ai-chatbot/issues
11
+ Keywords: aiohttp,asyncio,middleware,chatbot,ai,ai-chatbot,live-chat,customer-support,widget
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Framework :: aiohttp
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: aiohttp>=3.8
30
+ Dynamic: license-file
31
+
32
+ # aiohttp-ai-chatbot
33
+
34
+ Adds the [Asyntai](https://asyntai.com) AI chat assistant to an aiohttp site.
35
+ The assistant answers visitor questions from your own content, day and night,
36
+ in more than 80 languages.
37
+
38
+ Free and open source. Works on every Asyntai plan, including the free plan.
39
+
40
+ - Requires Python 3.9 or newer and aiohttp 3.8 or newer
41
+ - Documentation: https://asyntai.com/documentation/integrations/aiohttp/
42
+
43
+ ## Install
44
+
45
+ ```
46
+ pip install aiohttp-ai-chatbot
47
+ ```
48
+
49
+ ```python
50
+ from aiohttp import web
51
+ from aiohttp_ai_chatbot import setup
52
+
53
+ app = web.Application()
54
+ app.router.add_get("/", index)
55
+ setup(app, widget_id="asyntai_ab12cd34")
56
+
57
+ web.run_app(app)
58
+ ```
59
+
60
+ Or pass the middleware yourself:
61
+
62
+ ```python
63
+ from aiohttp_ai_chatbot import asyntai_middleware
64
+
65
+ app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
66
+ ```
67
+
68
+ You get the widget ID from the Install page of your
69
+ [Asyntai dashboard](https://asyntai.com/dashboard). You can paste the whole
70
+ snippet; the package keeps only the ID.
71
+
72
+ That is all. The chat button appears on every HTML page of the site. JSON,
73
+ files, streams, websockets and redirects pass through untouched.
74
+
75
+ ## Options
76
+
77
+ ```python
78
+ setup(
79
+ app,
80
+ widget_id="asyntai_ab12cd34", # without it: the ASYNTAI_WIDGET_ID environment variable
81
+ skip_paths=["/admin*"], # the default
82
+ )
83
+ ```
84
+
85
+ - Leave out `widget_id` to read the `ASYNTAI_WIDGET_ID` environment variable.
86
+ It is read on every request, so you can change it without a code change.
87
+ An empty value switches the chat off.
88
+ - `skip_paths` lists paths that never get the widget. A path that ends in `*`
89
+ also matches everything below it, so `/admin*` covers `/admin` and
90
+ `/admin/users`, but not `/administrator`.
91
+
92
+ The middleware changes complete `web.Response` pages with status 200 and the
93
+ `text/html` content type. A response that uses `enable_compression()` still
94
+ gets the widget, because aiohttp compresses the body after the middleware.
95
+ Files from `add_static` or `web.FileResponse` and responses that you prepare
96
+ and stream yourself are sent as they are.
97
+
98
+ ## Placing the widget by hand
99
+
100
+ With aiohttp-jinja2, register the helper once:
101
+
102
+ ```python
103
+ import aiohttp_jinja2
104
+ from aiohttp_ai_chatbot import asyntai_widget
105
+
106
+ env = aiohttp_jinja2.setup(app, loader=...)
107
+ env.globals["asyntai_widget"] = asyntai_widget
108
+ ```
109
+
110
+ Then put it before the closing body tag:
111
+
112
+ ```html
113
+ {{ asyntai_widget() }}
114
+ </body>
115
+ ```
116
+
117
+ `widget_snippet()` returns the same HTML as a plain string. The middleware
118
+ never adds a second copy to a page that already has one.
119
+
120
+ ## How it loads
121
+
122
+ The widget script loads after the page has finished loading, so your page
123
+ draws first and page speed does not change.
124
+
125
+ ## License
126
+
127
+ MIT
@@ -0,0 +1,9 @@
1
+ aiohttp_ai_chatbot/__init__.py,sha256=sXwrQBkalN0n0wqTe_OXm3Wah6UtecHkSQDze-5QO5E,304
2
+ aiohttp_ai_chatbot/middleware.py,sha256=3Bh_iLXxZqOp76xnpDIWlxDOPlAELzlxuTOJO2Q09CM,4362
3
+ aiohttp_ai_chatbot/snippet.py,sha256=GTBLZlQxKCqtO2zwyRYZOhYJ4b8Sqvh-yzJGMIis0ik,3083
4
+ aiohttp_ai_chatbot/utils.py,sha256=FngblF1xb0fteWP-08pvPV6GbZVrysLKeRI-nKh2yKA,1632
5
+ aiohttp_ai_chatbot-1.0.0.dist-info/licenses/LICENSE,sha256=jGsodKzosaT2Pr7P3ahTkLrMTHQ6uvf111OMRXeGYUM,1064
6
+ aiohttp_ai_chatbot-1.0.0.dist-info/METADATA,sha256=5cIzj1osrKRnXQkCyxAkf7O7q6R7EXHfHYHVnPzjY_k,4251
7
+ aiohttp_ai_chatbot-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ aiohttp_ai_chatbot-1.0.0.dist-info/top_level.txt,sha256=51JcIn0ocvmFD2iVau7M_371V3XHQxL2MiVFoVJrkIw,19
9
+ aiohttp_ai_chatbot-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Asyntai
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 @@
1
+ aiohttp_ai_chatbot