toucan-teams-bot 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.
- toucan_teams_bot-0.1.0/.gitignore +13 -0
- toucan_teams_bot-0.1.0/LICENSE +21 -0
- toucan_teams_bot-0.1.0/PKG-INFO +20 -0
- toucan_teams_bot-0.1.0/pyproject.toml +35 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/__init__.py +1 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/assets/toucan.png +0 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/catchup.py +165 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/cli.py +368 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/config.py +173 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/media.py +407 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/names.py +108 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/package.py +84 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/pages.py +146 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/server.py +363 -0
- toucan_teams_bot-0.1.0/src/toucan_bot/store.py +412 -0
- toucan_teams_bot-0.1.0/tests/test_catchup.py +911 -0
- toucan_teams_bot-0.1.0/tests/test_config.py +98 -0
- toucan_teams_bot-0.1.0/tests/test_ingest.py +843 -0
- toucan_teams_bot-0.1.0/tests/test_names.py +71 -0
- toucan_teams_bot-0.1.0/tests/test_react.py +127 -0
- toucan_teams_bot-0.1.0/tests/test_send.py +138 -0
- toucan_teams_bot-0.1.0/tests/test_setup.py +211 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Toucan Router contributors
|
|
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,20 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: toucan-teams-bot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Teams bot for Toucan Router: receive approved requests and post replies.
|
|
5
|
+
Project-URL: Homepage, https://github.com/salalaslam/toucan-router
|
|
6
|
+
Project-URL: Repository, https://github.com/salalaslam/toucan-router
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: agents,bot,teams,toucan
|
|
10
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Requires-Python: <3.14,>=3.11
|
|
14
|
+
Requires-Dist: microsoft-teams-apps==2.1.1
|
|
15
|
+
Requires-Dist: pillow>=11
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
18
|
+
Description-Content-Type: text/plain
|
|
19
|
+
|
|
20
|
+
Teams bot for Toucan Router. See the project homepage for setup instructions.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "toucan-teams-bot"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Teams bot for Toucan Router: receive approved requests and post replies."
|
|
9
|
+
readme = {text = "Teams bot for Toucan Router. See the project homepage for setup instructions.", content-type = "text/plain"}
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
keywords = ["teams", "bot", "toucan", "agents"]
|
|
13
|
+
classifiers = ["Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Operating System :: POSIX :: Linux"]
|
|
14
|
+
requires-python = ">=3.11,<3.14"
|
|
15
|
+
dependencies = [
|
|
16
|
+
"microsoft-teams-apps==2.1.1",
|
|
17
|
+
"pillow>=11",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/salalaslam/toucan-router"
|
|
22
|
+
Repository = "https://github.com/salalaslam/toucan-router"
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
test = ["pytest>=8"]
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
toucan-bot = "toucan_bot.cli:main"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/toucan_bot"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
35
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Toucan's Microsoft Teams bot."""
|
|
Binary file
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Reconcile installed chats through Graph using only the bot's application identity."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from datetime import datetime, timedelta, timezone
|
|
9
|
+
from urllib.parse import quote, unquote, urlencode, urlsplit
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from . import media, store
|
|
14
|
+
|
|
15
|
+
GRAPH = 'https://graph.microsoft.com/v1.0'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def message_base(chat, message):
|
|
19
|
+
return f'{GRAPH}/chats/{quote(chat, safe="")}/messages/{quote(message, safe="")}'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def normalise(message, bot_id):
|
|
23
|
+
sender = message.get('from') or {}
|
|
24
|
+
user, app = sender.get('user') or {}, sender.get('application') or {}
|
|
25
|
+
body = message.get('body') or {}
|
|
26
|
+
raw = body.get('content') or ''
|
|
27
|
+
# Keep cards, file references, quotes and forwards intact in the same JSON shape as push.
|
|
28
|
+
attachments = message.get('attachments') or []
|
|
29
|
+
mentions = message.get('mentions') or []
|
|
30
|
+
# The prior Graph-backed router passed m['id'] directly to Connector reactions.
|
|
31
|
+
# Keep that per-chat ID contract: activity.id and Graph id deduplicate one row.
|
|
32
|
+
return dict(id=message['id'], ts=message.get('createdDateTime'),
|
|
33
|
+
sender_aad_id=user.get('id') if not app else None,
|
|
34
|
+
sender_app_id=app.get('id'), sender_name=app.get('displayName') or user.get('displayName'),
|
|
35
|
+
text=store.plain_text(raw) if body.get('contentType') == 'html' else raw, raw_html=raw,
|
|
36
|
+
mentioned=any((m.get('mentioned', {}).get('application') or {}).get('id') == bot_id for m in mentions),
|
|
37
|
+
reply_to_id=message.get('replyToId'), attachments_json=json.dumps(attachments),
|
|
38
|
+
quoted_json=json.dumps(mentions), edited_at=message.get('lastEditedDateTime'),
|
|
39
|
+
deleted=bool(message.get('deletedDateTime')), deleted_at=message.get('deletedDateTime'),
|
|
40
|
+
modified_at=message.get('lastModifiedDateTime') or message.get('createdDateTime'), source='graph')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def sync_chat(con, client, token, chat, settings, bot_id):
|
|
44
|
+
state = con.execute('SELECT * FROM catchup WHERE conversation_id=?', (chat,)).fetchone()
|
|
45
|
+
if state and state['retry_at'] and state['retry_at'] > time.time():
|
|
46
|
+
return
|
|
47
|
+
base = f'{GRAPH}/chats/{quote(chat, safe="")}/messages'
|
|
48
|
+
if state and state['next_url']:
|
|
49
|
+
url, upper = state['next_url'], state['upper_bound']
|
|
50
|
+
else:
|
|
51
|
+
upper = datetime.now(timezone.utc).isoformat()
|
|
52
|
+
lower = (datetime.fromisoformat(state['cursor'].replace('Z', '+00:00')) - timedelta(seconds=1)
|
|
53
|
+
if state and state['cursor'] else datetime.fromisoformat(upper) - timedelta(days=settings['catchup_lookback_days']))
|
|
54
|
+
url = base + '?' + urlencode({'$top': 50, '$orderby': 'lastModifiedDateTime desc',
|
|
55
|
+
'$filter': f'lastModifiedDateTime gt {lower.isoformat()} and lastModifiedDateTime lt {upper}'})
|
|
56
|
+
con.execute('INSERT INTO catchup (conversation_id,next_url,upper_bound) VALUES (?,?,?) '
|
|
57
|
+
'ON CONFLICT(conversation_id) DO UPDATE SET next_url=excluded.next_url,upper_bound=excluded.upper_bound',
|
|
58
|
+
(chat, url, upper))
|
|
59
|
+
con.commit()
|
|
60
|
+
seen_pages = set()
|
|
61
|
+
while url:
|
|
62
|
+
parts = urlsplit(url)
|
|
63
|
+
# Don't send Graph tokens to a nextLink outside this chat's message endpoint.
|
|
64
|
+
if (parts.scheme != 'https' or parts.netloc != 'graph.microsoft.com' or parts.fragment or
|
|
65
|
+
unquote(parts.path) != unquote(urlsplit(base).path) or url in seen_pages):
|
|
66
|
+
raise ValueError('invalid Graph paging URL')
|
|
67
|
+
seen_pages.add(url)
|
|
68
|
+
for attempt in range(4):
|
|
69
|
+
state = con.execute('SELECT last_request_at,retry_at FROM catchup WHERE conversation_id=?', (chat,)).fetchone()
|
|
70
|
+
due = max((state['last_request_at'] or 0) + 1, state['retry_at'] or 0)
|
|
71
|
+
if due > time.time():
|
|
72
|
+
await asyncio.sleep(due - time.time()) # cancellation propagates, retaining this page
|
|
73
|
+
con.execute('UPDATE catchup SET last_request_at=?,retry_at=NULL WHERE conversation_id=?', (time.time(), chat))
|
|
74
|
+
con.commit()
|
|
75
|
+
try:
|
|
76
|
+
response = await client.get(url, headers={'Authorization': 'Bearer ' + token})
|
|
77
|
+
response.raise_for_status()
|
|
78
|
+
break
|
|
79
|
+
except (httpx.HTTPStatusError, httpx.TransportError) as error:
|
|
80
|
+
response = getattr(error, 'response', None)
|
|
81
|
+
status = response.status_code if response is not None else None
|
|
82
|
+
transient = status in (429, 503) or isinstance(error, httpx.TransportError)
|
|
83
|
+
if transient:
|
|
84
|
+
delay = media.retry_delay(response, attempt)
|
|
85
|
+
con.execute('UPDATE catchup SET retry_at=? WHERE conversation_id=?', (time.time() + delay, chat))
|
|
86
|
+
con.commit()
|
|
87
|
+
# Bound each pass. Long Retry-After values defer this chat without
|
|
88
|
+
# blocking all other chats. The persisted next_url stays unchanged.
|
|
89
|
+
if not transient or attempt == 3 or delay > 30:
|
|
90
|
+
raise
|
|
91
|
+
page = response.json()
|
|
92
|
+
for message in page['value']:
|
|
93
|
+
values = normalise(message, bot_id)
|
|
94
|
+
if message.get('messageType', 'message') != 'message':
|
|
95
|
+
values['sender_aad_id'] = None
|
|
96
|
+
attachments = json.loads(values['attachments_json'])
|
|
97
|
+
if not values['deleted']:
|
|
98
|
+
attachments += media.hosted_images(values['raw_html'], message_base(chat, message['id']))
|
|
99
|
+
values['attachments_json'] = json.dumps(attachments)
|
|
100
|
+
store.record_message(con, conversation_id=chat, **values)
|
|
101
|
+
url = page.get('@odata.nextLink')
|
|
102
|
+
# Retain the failed page across scheduled passes and process restarts.
|
|
103
|
+
# The final page and cursor are committed together below.
|
|
104
|
+
if url:
|
|
105
|
+
con.execute('UPDATE catchup SET next_url=?,retry_at=NULL WHERE conversation_id=?', (url, chat))
|
|
106
|
+
con.commit()
|
|
107
|
+
with con:
|
|
108
|
+
con.execute('UPDATE catchup SET next_url=NULL,upper_bound=NULL,retry_at=NULL WHERE conversation_id=?', (chat,))
|
|
109
|
+
store.catchup_result(con, chat, cursor=upper)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def sync(con, client, app, settings):
|
|
113
|
+
chats = [r for r in store.conversations(con) if r['type'] != 'personal']
|
|
114
|
+
if not chats:
|
|
115
|
+
return
|
|
116
|
+
try:
|
|
117
|
+
token = await app.token_provider.get_app_token('https://graph.microsoft.com/.default', settings['tenant_id'])
|
|
118
|
+
if token is None:
|
|
119
|
+
raise ValueError('Graph token unavailable')
|
|
120
|
+
except Exception as error:
|
|
121
|
+
for chat in chats:
|
|
122
|
+
failure(con, chat['id'], error)
|
|
123
|
+
return
|
|
124
|
+
for chat in chats:
|
|
125
|
+
try:
|
|
126
|
+
await sync_chat(con, client, str(token), chat['id'], settings, app.id)
|
|
127
|
+
except Exception as error:
|
|
128
|
+
failure(con, chat['id'], error)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def failure(con, chat, error):
|
|
132
|
+
status = getattr(getattr(error, 'response', None), 'status_code', None)
|
|
133
|
+
reason = ('HTTP 403: no RSC grant for this chat or unsupported chat type; upgrade and consent in this chat'
|
|
134
|
+
if status == 403 else f'HTTP {status}' if status else type(error).__name__)
|
|
135
|
+
store.catchup_result(con, chat, error=reason, status=status)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
async def roster(con, app, chat):
|
|
139
|
+
generation = store.invalidate_roster(con, chat['id'])
|
|
140
|
+
key = 'roster_generation:' + chat['id']
|
|
141
|
+
try:
|
|
142
|
+
# Chat rosters are not paginated. This is the Bot Connector, not Graph.
|
|
143
|
+
members = await app.api.from_service_url(chat['service_url']).conversations.members(chat['id']).get_all()
|
|
144
|
+
with con:
|
|
145
|
+
con.execute('BEGIN IMMEDIATE')
|
|
146
|
+
if con.execute('SELECT value FROM meta WHERE key=?', (key,)).fetchone()[0] != generation:
|
|
147
|
+
return # a newer fetch or membership change superseded this response
|
|
148
|
+
con.execute('DELETE FROM members WHERE conversation_id=?', (chat['id'],))
|
|
149
|
+
con.executemany('INSERT INTO members VALUES (?,?,?,?)',
|
|
150
|
+
[(chat['id'], m.id, (m.aad_object_id or '').lower() or None, m.name)
|
|
151
|
+
for m in members if getattr(m, 'role', None) != 'bot'
|
|
152
|
+
and not m.id.startswith('28:')])
|
|
153
|
+
con.execute('INSERT OR REPLACE INTO meta VALUES (?,?)', ('roster:' + chat['id'], generation))
|
|
154
|
+
con.execute('DELETE FROM meta WHERE key=?', ('roster_error:' + chat['id'],))
|
|
155
|
+
except Exception as error:
|
|
156
|
+
# Retain the member data but leave aliases unavailable after a failed
|
|
157
|
+
# current fetch. Superseded failures must not overwrite newer health.
|
|
158
|
+
log_status = getattr(getattr(error, 'response', None), 'status_code', None)
|
|
159
|
+
with con:
|
|
160
|
+
con.execute('BEGIN IMMEDIATE')
|
|
161
|
+
if con.execute('SELECT value FROM meta WHERE key=?', (key,)).fetchone()[0] != generation:
|
|
162
|
+
return
|
|
163
|
+
con.execute('INSERT OR REPLACE INTO meta VALUES (?,?)',
|
|
164
|
+
('roster_error:' + chat['id'], f'HTTP {log_status}' if log_status else type(error).__name__))
|
|
165
|
+
return False
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""toucan-bot: run the Teams bot and post as Toucan.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 success, 1 operational failure, 2 usage or missing setup,
|
|
4
|
+
4 ambiguous send (may have been delivered; inspect before retrying).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import asyncio
|
|
11
|
+
import dataclasses
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import sqlite3
|
|
15
|
+
import sys
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from email.utils import parsedate_to_datetime
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from . import config, names, store
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _print(rows, as_json: bool, fmt) -> None:
|
|
25
|
+
if as_json:
|
|
26
|
+
print(json.dumps([dict(r) for r in rows], indent=2))
|
|
27
|
+
else:
|
|
28
|
+
for r in rows:
|
|
29
|
+
print(fmt(r))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# The Bot Connector sometimes answers 401 to a fresh token and accepts the same send seconds later.
|
|
33
|
+
# A 401 means nothing was posted, so retrying can't duplicate the message.
|
|
34
|
+
RETRY_401_DELAYS = (3, 10, 30)
|
|
35
|
+
REACTION_RETRIES = 3
|
|
36
|
+
REACTION_ALIASES = {
|
|
37
|
+
"eyes": "1f440_eyes",
|
|
38
|
+
"check": "2705_whiteheavycheckmark",
|
|
39
|
+
"done": "2705_whiteheavycheckmark",
|
|
40
|
+
"pin": "1f4cc_pushpin",
|
|
41
|
+
"thumbsup": "like",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_401(e: Exception) -> bool:
|
|
46
|
+
response = getattr(e, "response", None)
|
|
47
|
+
return getattr(response, "status_code", None) == 401
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def _with_app(creds: config.Credentials, what: str, call):
|
|
51
|
+
from microsoft_teams.apps import App
|
|
52
|
+
|
|
53
|
+
for delay in (*RETRY_401_DELAYS, None):
|
|
54
|
+
app = App(client_id=creds.client_id, client_secret=creds.client_secret, tenant_id=config.app_tenant(creds))
|
|
55
|
+
await app.initialize()
|
|
56
|
+
try:
|
|
57
|
+
return await call(app)
|
|
58
|
+
except Exception as e: # noqa: BLE001 - only a 401 is retried
|
|
59
|
+
if delay is None or not _is_401(e):
|
|
60
|
+
raise
|
|
61
|
+
print(f"toucan-bot: {what} got 401, retrying in {delay}s", file=sys.stderr)
|
|
62
|
+
await asyncio.sleep(delay)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class UncertainSend(Exception):
|
|
66
|
+
"""The connector may have accepted the message; never retry automatically."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def _send(creds: config.Credentials, conversation_id: str, service_url: str, text: str) -> str | None:
|
|
70
|
+
async def call(app):
|
|
71
|
+
try:
|
|
72
|
+
sent = await app.send(conversation_id, text, service_url=service_url)
|
|
73
|
+
except Exception as error:
|
|
74
|
+
# Token acquisition happens inside app.send too. Its failures precede
|
|
75
|
+
# the connector POST and cannot have delivered the chat message.
|
|
76
|
+
request = getattr(error, 'request', None)
|
|
77
|
+
connector = request is None or str(request.url).startswith(service_url.rstrip('/') + '/')
|
|
78
|
+
status = getattr(getattr(error, 'response', None), 'status_code', None)
|
|
79
|
+
before_send = isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout))
|
|
80
|
+
if connector and not before_send and (
|
|
81
|
+
isinstance(error, (httpx.TransportError, TimeoutError, ConnectionError)) or
|
|
82
|
+
status is not None and status >= 500):
|
|
83
|
+
raise UncertainSend('delivery uncertain; inspect the chat before sending again') from error
|
|
84
|
+
raise
|
|
85
|
+
return getattr(sent, "id", None)
|
|
86
|
+
|
|
87
|
+
return await _with_app(creds, "send", call)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def _delete(creds: config.Credentials, conversation_id: str, service_url: str, activity_id: str) -> None:
|
|
91
|
+
async def call(app):
|
|
92
|
+
await app.api.conversations.activities_client.delete(conversation_id, activity_id, service_url=service_url)
|
|
93
|
+
|
|
94
|
+
await _with_app(creds, "delete", call)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _retry_after(response) -> float:
|
|
98
|
+
value = response.headers.get("Retry-After", "1")
|
|
99
|
+
try:
|
|
100
|
+
delay = float(value)
|
|
101
|
+
except ValueError:
|
|
102
|
+
try:
|
|
103
|
+
delay = (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds()
|
|
104
|
+
except (ValueError, TypeError, OverflowError):
|
|
105
|
+
return 1
|
|
106
|
+
return max(0, delay) if math.isfinite(delay) else 1
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def _react(creds: config.Credentials, conversation_id: str, service_url: str,
|
|
110
|
+
activity_id: str, emoji: str, remove: bool = False) -> None:
|
|
111
|
+
retries = 0
|
|
112
|
+
|
|
113
|
+
async def call(app):
|
|
114
|
+
nonlocal retries
|
|
115
|
+
conversations = app.api.from_service_url(service_url).conversations
|
|
116
|
+
react = conversations.delete_reaction if remove else conversations.add_reaction
|
|
117
|
+
while True:
|
|
118
|
+
try:
|
|
119
|
+
return await react(conversation_id, activity_id, emoji)
|
|
120
|
+
except Exception as e: # noqa: BLE001 - only a 429 is retried here
|
|
121
|
+
response = getattr(e, "response", None)
|
|
122
|
+
if getattr(response, "status_code", None) != 429 or retries >= REACTION_RETRIES:
|
|
123
|
+
raise
|
|
124
|
+
retries += 1
|
|
125
|
+
delay = _retry_after(response)
|
|
126
|
+
print(f"toucan-bot: react got 429, retrying in {delay:g}s", file=sys.stderr)
|
|
127
|
+
await asyncio.sleep(delay)
|
|
128
|
+
|
|
129
|
+
await _with_app(creds, "react", call)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def cmd_react(args) -> int:
|
|
133
|
+
creds = config.load_credentials()
|
|
134
|
+
if creds is None:
|
|
135
|
+
print("toucan-bot: not registered yet; finish the setup link first", file=sys.stderr)
|
|
136
|
+
return 2
|
|
137
|
+
if not args.message.strip() or not args.emoji.strip():
|
|
138
|
+
print("toucan-bot: message ID and emoji cannot be empty", file=sys.stderr)
|
|
139
|
+
return 2
|
|
140
|
+
con = store.connect(config.db_path())
|
|
141
|
+
chats = names.load_chats()
|
|
142
|
+
conversation = args.conversation
|
|
143
|
+
if args.to:
|
|
144
|
+
try:
|
|
145
|
+
conversation = names.resolve(args.to, [r["id"] for r in store.conversations(con)], chats)
|
|
146
|
+
except names.NotFound as e:
|
|
147
|
+
print(f"toucan-bot: {e}", file=sys.stderr)
|
|
148
|
+
return 2
|
|
149
|
+
conv = store.get_conversation(con, conversation)
|
|
150
|
+
if conv is None:
|
|
151
|
+
print("toucan-bot: unknown conversation; the bot must be added to it or messaged first", file=sys.stderr)
|
|
152
|
+
return 2
|
|
153
|
+
emoji = REACTION_ALIASES.get(args.emoji, args.emoji)
|
|
154
|
+
to = names.label(chats[conv["id"]]) if conv["id"] in chats else conv["name"] or conv["id"]
|
|
155
|
+
if not args.dry_run:
|
|
156
|
+
try:
|
|
157
|
+
asyncio.run(_react(creds, conv["id"], conv["service_url"], args.message, emoji, args.remove))
|
|
158
|
+
except Exception as e: # noqa: BLE001 - report any reaction failure as operational
|
|
159
|
+
status = getattr(getattr(e, "response", None), "status_code", None)
|
|
160
|
+
reason = ("HTTP 403: bot cannot access this chat or message; check that it is still in the chat" if status == 403
|
|
161
|
+
else "HTTP 404: message or conversation no longer exists, or the bot is no longer in the chat" if status == 404
|
|
162
|
+
else "HTTP 429: reaction rate limit still exceeded after retries" if status == 429
|
|
163
|
+
else f"{type(e).__name__}: {e}")
|
|
164
|
+
print(f"toucan-bot: react failed: {reason}", file=sys.stderr)
|
|
165
|
+
return 1
|
|
166
|
+
result = {"conversation_id": conv["id"], "to": to, "activity_id": args.message,
|
|
167
|
+
"emoji": emoji, "removed": args.remove, "dry_run": args.dry_run}
|
|
168
|
+
action = "remove" if args.remove else "add"
|
|
169
|
+
print(json.dumps(result) if args.json else
|
|
170
|
+
f"{'would ' + action if args.dry_run else 'removed' if args.remove else 'added'} {emoji} "
|
|
171
|
+
f"{'from' if args.remove else 'to'} message {args.message} in {to}: {conv['id']}")
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def cmd_send(args) -> int:
|
|
176
|
+
creds = config.load_credentials()
|
|
177
|
+
if creds is None:
|
|
178
|
+
print("toucan-bot: not registered yet; finish the setup link first", file=sys.stderr)
|
|
179
|
+
return 2
|
|
180
|
+
con = store.connect(config.db_path())
|
|
181
|
+
conversation = args.conversation
|
|
182
|
+
if args.to:
|
|
183
|
+
chats = names.load_chats()
|
|
184
|
+
try:
|
|
185
|
+
conversation = names.resolve(args.to, [r["id"] for r in store.conversations(con)], chats)
|
|
186
|
+
except names.NotFound as e:
|
|
187
|
+
print(f"toucan-bot: {e}", file=sys.stderr)
|
|
188
|
+
return 2
|
|
189
|
+
conv = store.get_conversation(con, conversation)
|
|
190
|
+
if conv is None:
|
|
191
|
+
print("toucan-bot: unknown conversation; the bot must be added to it or messaged first", file=sys.stderr)
|
|
192
|
+
return 2
|
|
193
|
+
if args.dry_run:
|
|
194
|
+
chats = names.load_chats()
|
|
195
|
+
print(f"would send to {names.label(chats[conv['id']]) if conv['id'] in chats else conv['name']}: {conv['id']}")
|
|
196
|
+
return 0
|
|
197
|
+
text = args.text if args.text is not None else sys.stdin.read()
|
|
198
|
+
if not text.strip():
|
|
199
|
+
print("toucan-bot: empty message", file=sys.stderr)
|
|
200
|
+
return 2
|
|
201
|
+
try:
|
|
202
|
+
activity_id = asyncio.run(_send(creds, conv["id"], conv["service_url"], text))
|
|
203
|
+
except UncertainSend as e:
|
|
204
|
+
print(f"toucan-bot: {e}", file=sys.stderr)
|
|
205
|
+
return 4
|
|
206
|
+
except Exception as e: # noqa: BLE001 - failures known to precede delivery
|
|
207
|
+
print(f"toucan-bot: send failed: {type(e).__name__}: {e}", file=sys.stderr)
|
|
208
|
+
return 1
|
|
209
|
+
try:
|
|
210
|
+
store.record_sent(con, conversation_id=conv["id"], activity_id=activity_id, text=text)
|
|
211
|
+
chats = names.load_chats()
|
|
212
|
+
to = names.label(chats[conv["id"]]) if conv["id"] in chats else conv["name"] or conv["id"]
|
|
213
|
+
print(json.dumps({"conversation_id": conv["id"], "to": to, "activity_id": activity_id}) if args.json
|
|
214
|
+
else f"sent to {to}: {activity_id or '(no activity ID)'}")
|
|
215
|
+
except Exception: # the POST succeeded; a local failure must not invite a duplicate
|
|
216
|
+
print("toucan-bot: message accepted but receipt unavailable; delivery uncertain", file=sys.stderr)
|
|
217
|
+
return 4
|
|
218
|
+
return 0
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def cmd_delete(args) -> int:
|
|
222
|
+
creds = config.load_credentials()
|
|
223
|
+
if creds is None:
|
|
224
|
+
print("toucan-bot: not registered yet; finish the setup link first", file=sys.stderr)
|
|
225
|
+
return 2
|
|
226
|
+
con = store.connect(config.db_path())
|
|
227
|
+
conv = store.get_conversation(con, args.conversation)
|
|
228
|
+
if conv is None:
|
|
229
|
+
print("toucan-bot: unknown conversation; the bot must be added to it or messaged first", file=sys.stderr)
|
|
230
|
+
return 2
|
|
231
|
+
try:
|
|
232
|
+
asyncio.run(_delete(creds, conv["id"], conv["service_url"], args.activity))
|
|
233
|
+
except Exception as e: # noqa: BLE001 - report any delete failure as operational
|
|
234
|
+
print(f"toucan-bot: delete failed: {type(e).__name__}: {e}", file=sys.stderr)
|
|
235
|
+
return 1
|
|
236
|
+
print("deleted")
|
|
237
|
+
return 0
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def cmd_conversations(args) -> int:
|
|
241
|
+
con = store.connect(config.db_path())
|
|
242
|
+
chats = names.load_chats()
|
|
243
|
+
rows = [{**dict(r), "name": names.label(chats[r["id"]]) if r["id"] in chats else r["name"]}
|
|
244
|
+
for r in store.conversations(con)]
|
|
245
|
+
if args.json:
|
|
246
|
+
print(json.dumps(rows, indent=2))
|
|
247
|
+
else:
|
|
248
|
+
for r in rows:
|
|
249
|
+
print(f"{r['last_seen']} {r['type'] or '?':9} {r['name'] or '(no name)'} {r['id']}")
|
|
250
|
+
return 0
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def cmd_messages(args) -> int:
|
|
254
|
+
con = store.connect(config.db_path())
|
|
255
|
+
_print(store.recent_messages(con, args.limit), args.json,
|
|
256
|
+
lambda r: f"{r['ts']} {r['sender_name']}: {r['text']} [{r['conversation_id']}]")
|
|
257
|
+
return 0
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def cmd_setup_url(args) -> int:
|
|
261
|
+
print(config.setup_url())
|
|
262
|
+
return 0
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def cmd_status(args) -> int:
|
|
266
|
+
cfg = config.load()
|
|
267
|
+
creds = config.load_credentials()
|
|
268
|
+
def identity(value):
|
|
269
|
+
return value if args.show_ids or not value else "…" + value[-4:]
|
|
270
|
+
warning = config.credential_warning(creds, cfg)
|
|
271
|
+
ready = bool(cfg["tenant_id"] and cfg["public_url"] and creds and not warning)
|
|
272
|
+
out = {"ok": ready, "tenant_id": identity(cfg["tenant_id"]), "public_url": cfg["public_url"],
|
|
273
|
+
"credentials": bool(creds and not warning), "registered": creds is not None, "warning": warning,
|
|
274
|
+
"bot_id": identity(creds.client_id) if creds else None,
|
|
275
|
+
"app_type": creds.app_type if creds else None,
|
|
276
|
+
"endpoint": f"{cfg['public_url']}/api/messages" if cfg["public_url"] else "", "local_port": cfg["port"]}
|
|
277
|
+
try:
|
|
278
|
+
# Status must not create or migrate a store just to inspect it.
|
|
279
|
+
with sqlite3.connect(config.db_path().resolve().as_uri() + '?mode=ro', uri=True) as con:
|
|
280
|
+
con.row_factory = sqlite3.Row
|
|
281
|
+
con.execute('BEGIN') # catch-up state and delivery counts must describe one snapshot
|
|
282
|
+
out.update(store.coverage(con))
|
|
283
|
+
except (OSError, sqlite3.Error, ValueError):
|
|
284
|
+
out.update(catchup={'error': 'bot store missing or outdated; restart the upgraded bot'}, delivery=None)
|
|
285
|
+
print(json.dumps(out, indent=2) if args.json else "\n".join(f"{k}: {v}" for k, v in out.items()))
|
|
286
|
+
return 0 if ready else 1
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def cmd_app_type(args) -> int:
|
|
290
|
+
creds = config.load_credentials()
|
|
291
|
+
if creds is None:
|
|
292
|
+
print("toucan-bot: not registered yet; finish the setup link first", file=sys.stderr)
|
|
293
|
+
return 2
|
|
294
|
+
config.save_credentials(dataclasses.replace(creds, app_type=args.app_type))
|
|
295
|
+
print(f"app type: {args.app_type}; restart the bot: systemctl --user restart toucan-bot")
|
|
296
|
+
return 0
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def cmd_reset(args) -> int:
|
|
300
|
+
if not args.yes:
|
|
301
|
+
print("toucan-bot: this deletes the stored bot ID and secret; rerun with --yes", file=sys.stderr)
|
|
302
|
+
return 2
|
|
303
|
+
print("removed" if config.clear_credentials() else "nothing to remove")
|
|
304
|
+
return 0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def cmd_serve(args) -> int:
|
|
308
|
+
from .server import serve
|
|
309
|
+
|
|
310
|
+
serve()
|
|
311
|
+
return 0
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def main(argv=None) -> int:
|
|
315
|
+
p = argparse.ArgumentParser(prog="toucan-bot", description=__doc__.splitlines()[0],
|
|
316
|
+
epilog=" ".join(__doc__.splitlines()[2:]))
|
|
317
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
318
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
319
|
+
sub.add_parser("serve", help="run the bot server (systemd runs this)").set_defaults(fn=cmd_serve)
|
|
320
|
+
status = sub.add_parser("status", help="configuration, registration and endpoint")
|
|
321
|
+
status.add_argument("--show-ids", action="store_true", help="show full tenant and application IDs")
|
|
322
|
+
status.set_defaults(fn=cmd_status)
|
|
323
|
+
sub.add_parser("setup-url", help="print the private setup link").set_defaults(fn=cmd_setup_url)
|
|
324
|
+
s = sub.add_parser("send", help="post a message as Toucan",
|
|
325
|
+
epilog="Exit 4: ambiguous send; may have been delivered. Inspect before retrying.")
|
|
326
|
+
to = s.add_mutually_exclusive_group(required=True)
|
|
327
|
+
to.add_argument("--to", help="person (their 1:1 with the signed-in user) or chat name, e.g. 'Alice' or 'Project A'")
|
|
328
|
+
to.add_argument("--conversation", help="conversation ID from `toucan-bot conversations`")
|
|
329
|
+
s.add_argument("--text", help="message text (default: read stdin)")
|
|
330
|
+
s.add_argument("--dry-run", action="store_true", help="print which chat it would go to, and send nothing")
|
|
331
|
+
s.set_defaults(fn=cmd_send)
|
|
332
|
+
d = sub.add_parser("delete", help="delete a message Toucan posted")
|
|
333
|
+
d.add_argument("--conversation", required=True, help="conversation ID from `toucan-bot conversations`")
|
|
334
|
+
d.add_argument("--activity", required=True, help="activity ID that `send` printed")
|
|
335
|
+
d.set_defaults(fn=cmd_delete)
|
|
336
|
+
r = sub.add_parser("react", help="add or remove Toucan's reaction to a Teams message")
|
|
337
|
+
to = r.add_mutually_exclusive_group(required=True)
|
|
338
|
+
to.add_argument("--to", help="person (their 1:1 with the signed-in user) or chat name, like `send --to`")
|
|
339
|
+
to.add_argument("--conversation", help="conversation ID from `toucan-bot conversations`")
|
|
340
|
+
r.add_argument("--message", required=True, help="Teams message ID from the bot store")
|
|
341
|
+
r.add_argument("--emoji", required=True, help="Teams reaction ID or eyes, check, done, pin, thumbsup")
|
|
342
|
+
r.add_argument("--remove", action="store_true", help="remove the bot's own reaction")
|
|
343
|
+
r.add_argument("--dry-run", action="store_true", help="print the chat, message and reaction without changing it")
|
|
344
|
+
r.set_defaults(fn=cmd_react)
|
|
345
|
+
sub.add_parser("conversations", help="chats the bot knows about").set_defaults(fn=cmd_conversations)
|
|
346
|
+
m = sub.add_parser("messages", help="recent messages the bot received")
|
|
347
|
+
m.add_argument("--limit", type=int, default=20)
|
|
348
|
+
m.set_defaults(fn=cmd_messages)
|
|
349
|
+
a = sub.add_parser("app-type", help="set how the bot is registered with the Bot Framework")
|
|
350
|
+
a.add_argument("app_type", choices=config.APP_TYPES)
|
|
351
|
+
a.set_defaults(fn=cmd_app_type)
|
|
352
|
+
r = sub.add_parser("reset", help="delete the stored bot ID and secret")
|
|
353
|
+
r.add_argument("--yes", action="store_true")
|
|
354
|
+
r.set_defaults(fn=cmd_reset)
|
|
355
|
+
for command in sub.choices.values():
|
|
356
|
+
command.add_argument('--json', action='store_true', default=argparse.SUPPRESS,
|
|
357
|
+
help='machine-readable output')
|
|
358
|
+
args = p.parse_args(argv)
|
|
359
|
+
try:
|
|
360
|
+
return args.fn(args)
|
|
361
|
+
except (OSError, ValueError, KeyError) as error:
|
|
362
|
+
reason = str(error) if isinstance(error, ValueError) and not isinstance(error, json.JSONDecodeError) else "cannot read bot configuration or credentials"
|
|
363
|
+
print(f"toucan-bot: {reason}", file=sys.stderr)
|
|
364
|
+
return 1
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
if __name__ == "__main__":
|
|
368
|
+
sys.exit(main())
|