dogbot 0.1.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.
dogbot/__init__.py ADDED
@@ -0,0 +1,234 @@
1
+ """dogbot — Python SDK and CLI for Bluebot, the automation bot for developer workflows.
2
+
3
+ Build and trigger bots that act on tickets, pull requests, alerts, and chat
4
+ messages — declaring skills as Python functions and routing events from Slack,
5
+ GitHub, or your service bus.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib.util
11
+ import os
12
+ import re
13
+ import threading
14
+ import time
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Callable, Iterable
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = [
23
+ "Bot",
24
+ "skill",
25
+ "Skill",
26
+ "Event",
27
+ "BotError",
28
+ ]
29
+
30
+
31
+ class BotError(Exception):
32
+ """Raised when a bot cannot start or dispatch an event."""
33
+
34
+
35
+ @dataclass
36
+ class Skill:
37
+ """A registered bot skill.
38
+
39
+ Attributes:
40
+ intent: The intent name this skill answers to.
41
+ utterances: List of utterance templates with ``{placeholders}``.
42
+ fn: The wrapped callable.
43
+ background: When True, the skill runs as a background job.
44
+ """
45
+
46
+ intent: str
47
+ utterances: list[str]
48
+ fn: Callable[..., Any]
49
+ background: bool = False
50
+
51
+ def matches(self, text: str) -> dict[str, str] | None:
52
+ """Return matched placeholder groups if ``text`` matches an utterance."""
53
+ for tmpl in self.utterances:
54
+ pattern = _template_to_regex(tmpl)
55
+ m = pattern.fullmatch(text.strip())
56
+ if m:
57
+ return m.groupdict()
58
+ return None
59
+
60
+
61
+ def _template_to_regex(tmpl: str) -> re.Pattern[str]:
62
+ parts = re.split(r"\{(\w+)\}", tmpl)
63
+ out = []
64
+ for i, part in enumerate(parts):
65
+ if i % 2 == 0:
66
+ out.append(re.escape(part))
67
+ else:
68
+ out.append(f"(?P<{part}>.+)")
69
+ return re.compile("".join(out))
70
+
71
+
72
+ def skill(
73
+ intent: str,
74
+ utterances: Iterable[str] | None = None,
75
+ *,
76
+ background: bool = False,
77
+ ) -> Callable[[Callable[..., Any]], Skill]:
78
+ """Register a function as a callable skill.
79
+
80
+ Args:
81
+ intent: Intent name (e.g. ``"restart_service"``).
82
+ utterances: Utterance templates with ``{placeholders}`` (e.g.
83
+ ``["restart {service}"]``).
84
+ background: When True, the skill runs as a background job.
85
+ """
86
+ def _decorator(fn: Callable[..., Any]) -> Skill:
87
+ return Skill(intent=intent, utterances=list(utterances or []), fn=fn, background=background)
88
+
89
+ return _decorator
90
+
91
+
92
+ @dataclass
93
+ class Event:
94
+ """An inbound event routed to the bot.
95
+
96
+ Attributes:
97
+ text: The raw message text.
98
+ channel: Source channel id.
99
+ user: Source user id.
100
+ adapter: Source adapter name (``slack``, ``github``, ...).
101
+ ts: Event timestamp.
102
+ """
103
+
104
+ text: str
105
+ channel: str = "general"
106
+ user: str = "unknown"
107
+ adapter: str = "slack"
108
+ ts: float = field(default_factory=time.time)
109
+
110
+
111
+ class Bot:
112
+ """A Bluebot instance.
113
+
114
+ Args:
115
+ name: Bot name.
116
+ token: Adapter token (e.g. ``xoxb-...`` for Slack).
117
+ adapters: Iterable of adapter names to enable. Defaults to ``("slack",)``.
118
+ memory: Optional callable ``(channel, user) -> dict`` returning
119
+ per-context memory; defaults to an in-memory dict.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ name: str,
125
+ token: str | None = None,
126
+ *,
127
+ adapters: Iterable[str] = ("slack",),
128
+ memory: Callable[[str, str], dict[str, Any]] | None = None,
129
+ ) -> None:
130
+ if not name:
131
+ raise BotError("bot name is required")
132
+ self.name = name
133
+ self.token = token
134
+ self.adapters = tuple(adapters)
135
+ self._skills: dict[str, Skill] = {}
136
+ self._memory: Callable[[str, str], dict[str, Any]] = memory or _DictMemory()
137
+ self._jobs: list[threading.Thread] = []
138
+ self._running = False
139
+
140
+ # -- registration ---------------------------------------------------
141
+ def register(self, skl: Skill) -> Skill:
142
+ """Register a :class:`Skill` on this bot."""
143
+ if skl.intent in self._skills:
144
+ raise BotError(f"duplicate skill intent: {skl.intent!r}")
145
+ self._skills[skl.intent] = skl
146
+ return skl
147
+
148
+ @property
149
+ def skills(self) -> dict[str, Skill]:
150
+ """The registered skills keyed by intent."""
151
+ return dict(self._skills)
152
+
153
+ def load_skills_dir(self, path: str) -> int:
154
+ """Load every ``.py`` file in ``path`` and register its module-level
155
+ ``Skill`` objects (attributes named ``skill`` or decorated with
156
+ :func:`skill``).
157
+ """
158
+ loaded = 0
159
+ for py in sorted(Path(path).glob("*.py")):
160
+ spec = importlib.util.spec_from_file_location(py.stem, py)
161
+ if spec is None or spec.loader is None:
162
+ continue
163
+ mod = importlib.util.module_from_spec(spec)
164
+ spec.loader.exec_module(mod)
165
+ for attr in vars(mod).values():
166
+ if isinstance(attr, Skill):
167
+ try:
168
+ self.register(attr)
169
+ loaded += 1
170
+ except BotError:
171
+ pass
172
+ return loaded
173
+
174
+ # -- dispatch -------------------------------------------------------
175
+ def dispatch(self, event: Event) -> dict[str, Any]:
176
+ """Route ``event`` to the matching skill and return its result."""
177
+ for skl in self._skills.values():
178
+ params = skl.matches(event.text)
179
+ if params is None:
180
+ continue
181
+ ctx = self._memory(event.channel, event.user)
182
+ if skl.background:
183
+ kwargs = dict(params)
184
+ if "ctx" in _function_params(skl.fn):
185
+ kwargs["ctx"] = ctx
186
+ job = threading.Thread(target=skl.fn, kwargs=kwargs, daemon=True)
187
+ job.start()
188
+ self._jobs.append(job)
189
+ return {"intent": skl.intent, "status": "running", "background": True}
190
+ try:
191
+ result = skl.fn(**params)
192
+ except Exception as exc: # surfaced to the caller
193
+ return {"intent": skl.intent, "status": "error", "error": str(exc)}
194
+ return {"intent": skl.intent, "status": "done", "result": result}
195
+ return {"intent": None, "status": "no_match"}
196
+
197
+ def run(self, *, block: bool = True) -> None:
198
+ """Run the bot as a service.
199
+
200
+ Args:
201
+ block: When True, block until :meth:`stop` is called from another
202
+ thread; otherwise return immediately.
203
+ """
204
+ self._running = True
205
+ if not block:
206
+ return
207
+ while self._running:
208
+ time.sleep(0.05)
209
+
210
+ def stop(self) -> None:
211
+ """Stop a running bot."""
212
+ self._running = False
213
+
214
+
215
+ def _function_params(fn: Callable[..., Any]) -> set[str]:
216
+ import inspect
217
+
218
+ try:
219
+ return set(inspect.signature(fn).parameters)
220
+ except (TypeError, ValueError):
221
+ return set()
222
+
223
+
224
+ class _DictMemory:
225
+ """Default per-context memory backed by an in-memory dict."""
226
+
227
+ def __init__(self) -> None:
228
+ self._store: dict[tuple[str, str], dict[str, Any]] = {}
229
+
230
+ def __call__(self, channel: str, user: str) -> dict[str, Any]:
231
+ key = (channel, user)
232
+ if key not in self._store:
233
+ self._store[key] = {}
234
+ return self._store[key]
dogbot/cli.py ADDED
@@ -0,0 +1,82 @@
1
+ """CLI for dogbot.
2
+
3
+ Subcommands:
4
+ serve --skills DIR --adapter slack run a bot as a service.
5
+ skills --skills DIR list registered skills.
6
+ dispatch --text "..." route a single text event.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import os
13
+ import sys
14
+
15
+ from . import Bot, Event, __version__
16
+
17
+
18
+ def _build_parser() -> argparse.ArgumentParser:
19
+ parser = argparse.ArgumentParser(prog="dogbot", description="Bluebot automation bot CLI.")
20
+ parser.add_argument("--version", action="version", version=f"dogbot {__version__}")
21
+ sub = parser.add_subparsers(dest="command", required=True)
22
+
23
+ serve = sub.add_parser("serve", help="run a bot as a service")
24
+ serve.add_argument("--skills", default=os.environ.get("DOGBOT_SKILLS_PATH", "./skills"))
25
+ serve.add_argument("--adapter", default="slack")
26
+ serve.add_argument("--name", default="dogbot")
27
+ serve.add_argument("--token", default=None)
28
+
29
+ skills = sub.add_parser("skills", help="list loaded skills")
30
+ skills.add_argument("--skills", default=os.environ.get("DOGBOT_SKILLS_PATH", "./skills"))
31
+
32
+ disp = sub.add_parser("dispatch", help="route a single text event")
33
+ disp.add_argument("--text", required=True)
34
+ disp.add_argument("--skills", default=os.environ.get("DOGBOT_SKILLS_PATH", "./skills"))
35
+ disp.add_argument("--adapter", default="slack")
36
+ return parser
37
+
38
+
39
+ def _bot_with_skills(args) -> Bot:
40
+ bot = Bot(name=args.name if hasattr(args, "name") else "dogbot", token=args.token if hasattr(args, "token") else None,
41
+ adapters=(args.adapter,))
42
+ bot.load_skills_dir(args.skills)
43
+ return bot
44
+
45
+
46
+ def main(argv: list[str] | None = None) -> int:
47
+ """Entry point for the ``dogbot`` console script."""
48
+ args = _build_parser().parse_args(argv)
49
+
50
+ if args.command == "serve":
51
+ bot = Bot(name=args.name, token=args.token, adapters=(args.adapter,))
52
+ if os.path.isdir(args.skills):
53
+ n = bot.load_skills_dir(args.skills)
54
+ print(f"loaded {n} skill(s) from {args.skills}", file=sys.stderr)
55
+ print(f"dogbot {args.name} serving on {args.adapter}", file=sys.stderr)
56
+ try:
57
+ bot.run(block=True)
58
+ except KeyboardInterrupt:
59
+ bot.stop()
60
+ return 0
61
+
62
+ if args.command == "skills":
63
+ bot = Bot(name="dogbot", adapters=(args.adapter,))
64
+ if os.path.isdir(args.skills):
65
+ bot.load_skills_dir(args.skills)
66
+ for intent, skl in bot.skills.items():
67
+ print(f"{intent}\t{len(skl.utterances)} utterance(s)")
68
+ return 0
69
+
70
+ if args.command == "dispatch":
71
+ bot = Bot(name="dogbot", adapters=(args.adapter,))
72
+ if os.path.isdir(args.skills):
73
+ bot.load_skills_dir(args.skills)
74
+ result = bot.dispatch(Event(text=args.text, adapter=args.adapter))
75
+ print(result)
76
+ return 0
77
+
78
+ return 1
79
+
80
+
81
+ if __name__ == "__main__":
82
+ sys.exit(main())
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: dogbot
3
+ Version: 0.1.0
4
+ Summary: Python SDK and CLI for Bluebot — build bots that act on tickets, PRs, alerts, and chat messages via typed skills.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # dogbot
11
+
12
+ `dogbot` is the Python SDK and CLI for [Bluebot](https://usebluebot.com), the friendly automation bot for developer workflows. It lets you build and trigger bots that act on tickets, pull requests, alerts, and chat messages — declaring skills as Python functions and routing events from Slack, GitHub, or your service bus.
13
+
14
+ ## Features
15
+
16
+ - Define bot skills as typed, docstring-documented Python functions.
17
+ - Route incoming events (Slack, GitHub, Jira, webhooks) to skills by intent.
18
+ - Long-running skills run as background jobs with status callbacks.
19
+ - Built-in memory for per-user and per-channel context across turns.
20
+ - CLI for local skill testing and for running a bot as a service.
21
+ - Requires Python 3.9 or newer.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install dogbot
27
+ ```
28
+
29
+ Run a bot locally:
30
+
31
+ ```bash
32
+ pipx install dogbot
33
+ dogbot serve --skills ./skills --adapter slack
34
+ ```
35
+
36
+ ## Quick start
37
+
38
+ ```python
39
+ from dogbot import Bot, skill
40
+
41
+ bot = Bot(name="rex", token="xoxb-...")
42
+
43
+ @skill(intent="restart_service", utterances=["restart {service}"])
44
+ def restart(service: str) -> str:
45
+ # your restart logic here
46
+ return f"Restarted {service}."
47
+
48
+ bot.run()
49
+ ```
50
+
51
+ ## API
52
+
53
+ - `Bot(name, token=...)` — create and serve a bot with one or more adapters.
54
+ - `@skill(intent=..., utterances=[...])` — register a function as a callable skill.
55
+ - `bot.dispatch(event)` — route a raw event to the matching skill (useful in custom hosts).
56
+ - `dogbot serve --skills DIR --adapter slack` — CLI entrypoint to run a bot service.
57
+
58
+ ## Configuration
59
+
60
+ Set adapter tokens in the environment (`SLACK_BOT_TOKEN`, `GITHUB_TOKEN`, etc.). Skill directories are loaded by `DOGBOT_SKILLS_PATH`.
61
+
62
+ ## License
63
+
64
+ MIT
@@ -0,0 +1,7 @@
1
+ dogbot/__init__.py,sha256=j-DuEzJ9pOAH2y3TVPgHLvhYmVznUFPRbL6LOXlj9yY,7308
2
+ dogbot/cli.py,sha256=Uc6S6QjYf7MDV-30aUbONFtoOHEol_yWs70dsV4haYk,2940
3
+ dogbot-0.1.0.dist-info/METADATA,sha256=Xkh0UfmtuiwLS-SqWCOqIOLv9j1bzVWBAg_xVl0bUVw,1946
4
+ dogbot-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ dogbot-0.1.0.dist-info/entry_points.txt,sha256=Z1vvKkfI2QpZK7GBwHBjKPpJ3FQZSa6XV-Ker3s2fmk,43
6
+ dogbot-0.1.0.dist-info/top_level.txt,sha256=2GWgybthruqTx2I-ddkAFKNCgkgX8WM6FJ9NA32L4wI,7
7
+ dogbot-0.1.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,2 @@
1
+ [console_scripts]
2
+ dogbot = dogbot.cli:main
@@ -0,0 +1 @@
1
+ dogbot