* feat(wisdom): add trusted publish and install foundation
* feat(wisdom): add private contribution loop
* feat(wisdom): add managed consumption workflows
* fix(wisdom): close cross-repository safety gaps
* fix(wisdom): align local package and lifecycle policy
* fix(wisdom): require explicit profile setup
* docs(wisdom): repin reconciled gateway head
* fix(wisdom): fence content downloads and approval receipts
* docs(wisdom): record generation-fenced downloads
* docs(wisdom): record unified delivery PR
* fix(ci): stop passing invalid classifier inputs
* docs(wisdom): remove internal requirements ledger
* feat(wisdom): localize dashboard and desktop copy
* feat(wisdom): complete local contribution and consumption UX
* style(wisdom): satisfy desktop lint
* chore(wisdom): refresh requirements pin
* test(dashboard): allow formatted profile copy
* test(wisdom): stabilize desktop interaction coverage
* fix(wisdom): surface dashboard action failures
* fix(wisdom): add repeatable Portal demo login
* feat(wisdom): add actionable skill notifications
* feat(wisdom): add notification install and update actions
* fix(wisdom): make Telegram skill alerts actionable
* fix(wisdom): always refresh demo Agent login
* feat(wisdom): embed Telegram notification actions
* fix(wisdom): preserve Telegram notifications after actions
* fix(wisdom): keep Telegram notification cards readable
* feat(wisdom): add Telegram candidate approval flow
* feat(wisdom): explain Telegram qualification reasons
* fix(wisdom): reconcile cross-surface candidate actions
* feat(telegram): add Collective Wisdom management command
* chore(wisdom): refresh Gateway contract pin
* chore(wisdom): advance Gateway contract pin
* feat(wisdom): align command UX across clients
* feat(slack): add Collective Wisdom management parity
* feat(wisdom): add security and professionalism reviews
* feat(wisdom): add first-time qualification guidance
* feat(wisdom): simplify qualification sharing choices
* feat(skills): add optional editorial metadata
* feat(wisdom): enrich legacy skill presentation
* fix(wisdom): harden review and update boundaries
* fix(wisdom): emit canonical review timestamps
* fix(wisdom): align with merged gateway and main
* wisdom: add agent-led sharing core (policy, evidence, schemas, templates, delivery, weekly job, share/install flows)
- hermes_wisdom/agent_led/: policy resolution (server > local > defaults),
7-day evidence builder that excludes bundled/hub/managed skills and
dismissed/handled/recently-suggested content hashes, strict pydantic
schemas for agent output with repair-or-reject, fixed copy templates
(Share / Teammate / Published / Update / Mute), idempotent retried
delivery ledger with stale-action resolution, weekly review job,
resumable Share and Install flows.
- prompts/: candidate review, recipient recommendation, share packaging.
- tests/wisdom/test_agent_led.py: 30 tests.
* wisdom: agent-led renderers and button action dispatcher
- render.py: Telegram HTML, Slack blocks, Desktop payload; editorial name
is the emphasized line, product label stays separate.
- actions.py: resolve opaque wa:<action>:<dedup> targets via the delivery
ledger; Not now -> dismissal, Mute -> fixed options, Share -> resumable
packaging flow, Install/Update -> plan command. Never publishes/installs.
* wisdom: CLI verbs, agent_led config default, conversational catalog skill
- hermes wisdom browse/review-week/act/share/dismiss/mute (all --json).
- wisdom.agent_led config block, default enabled.
- SKILL.md rewritten so natural-language catalog questions map to the CLI
verbs, share/install flows and fixed notification templates.
* wisdom: wire agent-led weekly review into gateway tick and Telegram buttons
- gateway housekeeping tick calls maybe_run_weekly_review with a home
channel sender when a Telegram adapter is available.
- Telegram: wa: callbacks resolved through the ledger (stale-safe), mute
duration keyboard, send_wisdom_agent_recommendation rich card + fallback.
* fix(wisdom): integrate local mediation and harden model and setup boundaries
* fix(wisdom): honor authoritative recommendation policy and defer on failure
* fix(wisdom): synchronize opaque suppression and recheck delivery preferences
* feat(wisdom): route weekly selection through the session-owned assessment queue
* fix(wisdom): prepare and submit the reviewed generated share package
* feat(wisdom): separate native Share preparation from publication consent
* feat(wisdom): sync native mute choices through a leased preference outbox
* feat(wisdom): bind native mute controls to durable preference choices
* feat(wisdom): add scoped desktop and dashboard notification settings
* fix(wisdom): revalidate feed recommendations before assessment and delivery
* fix(wisdom): persist validated delivery receipts before completing notices
* feat(wisdom): add private notification claim and receipt client
* Persist Wisdom send reservations and recover delivery acknowledgements
* Route legacy Wisdom controls through current native review
* Add typed private Wisdom operation outcome client
* fix(wisdom): make agent-led advice usable in the local demo
* fix(wisdom): keep requested consent outside proactive limits
* fix(wisdom): distinguish unavailable assessments and preserve digest text
* fix(wisdom): assess ongoing usefulness beyond the current task
* fix(wisdom): restore immediate qualification sharing controls
* fix(wisdom): separate qualification review from installation advice
* fix(wisdom): collapse review checklists and simplify sharing copy
* fix(wisdom): show compact sharing progress and publication receipts
* fix(wisdom): require credential prefixes rather than matching skill names
* fix(wisdom): finish package checks before presenting sharing consent
* fix(wisdom): scan local skills before qualification cards
* fix(wisdom): update moderation results on existing sharing cards
* fix(wisdom): keep sharing review accessible from receipt cards
* fix(wisdom): align mediated review cards and collapsible checks
* fix(wisdom): clarify clean security summary wording
* fix(wisdom): normalize consent plans and add explicit recheck
* fix(wisdom): keep install and update receipts concise
* fix(wisdom): collapse assessments and deduplicate operation cards
* fix(wisdom): restore private Portal review from native cards
* fix(wisdom): sync Portal publication to original consent card
* fix(wisdom): show local skill version on sharing cards
* fix(wisdom): skip agent recommendations for self-published versions
* fix(wisdom): simplify candidate notices and local-edit recovery copy
* feat(wisdom): submit locally reviewed packages with one confirmation
* feat(wisdom): expose safe receipt and outcome sync recovery
* wisdom: onboarding notice says detect and share, names the user's own skill
Copy review from the product owner on the first and returning
qualification notices (fixed delivery mode):
- the feature blurb now says the org enabled detection *and sharing*
- both notices say the detected skill is one the user created
- both close with an exclamation mark
Applied identically to hermes_wisdom.notice, the desktop and web i18n
strings, and the tests that assert the sentences.
* wisdom: one opener, no approval line, ask to share after the skill is shown
Product owner review of the candidate card.
- The Hermes written card now opens with the same sentence as the fixed card
("Your organisation has enabled Collective Wisdom, a feature designed to
automatically detect and share useful skills across all team members.")
instead of its own blurb, so there is one first time message.
- "Nothing is shared without your approval." removed from Telegram, Slack
and Desktop. The buttons already make the permission explicit.
- "Would you like to share?" no longer appears before the skill is named.
It is now the last line, after the skill name, description, why suggested
and the checks, and reads "Would you like to share it?" (matching the
agent led template wording).
Tests updated for the new order; proposalNotice removed from all desktop locales.
* wisdom: American spelling, organization
Product owner decision: user facing copy uses American spelling.
Changes "Your organisation" to "Your organization" in the chat notice,
the Hermes written card opener, the desktop and web strings, and the
tests that assert them. Identifiers such as nas_organisation:* and the
German and French locales are untouched.
* wisdom: candidate card copy round 4 (owner review)
Apply the product owner's round 4 copy decisions to the Hermes Collective
Wisdom candidate card on Telegram, Slack, Desktop and the shared views:
1. Hermes-written cards are titled "Hermes Collective Wisdom" instead of
the bare "Collective Wisdom".
2. The "Reusable skill ready to review" line is gone from the candidate
card (Telegram rich card and plain fallback, legacy agent-led share
template).
3. The skill name and description are labelled: "Skill name: <name>" and
"What it does: <description>" (Telegram, Slack, Desktop).
4. "Why suggested:" is now "Why others might benefit:".
5. A passing professionalism review reads "Safe to share at work ✓ (no
inappropriate content found)" with no per-check bullets and no "Pass";
a failed review reads "Needs a look before sharing at work (possible
inappropriate content)" and lists only the checks that flagged
something. Pending/unavailable wording is unchanged.
6. Telegram button toasts: "Will ask later...", "Preparing more
details...", "Sharing...".
7. Qualification reasons: "You used this skill consistently across many
days." and "You've really refined this skill."
8. prompts/wisdom_candidate_review.md asks for a compelling
editorial_name, a simple one_line_description and a compelling
why_coworkers_benefit under 300 characters; "Be concise and
convincing." becomes "Be concise and compelling: the goal is that the
user wants to share it."
Tests updated for the new strings; review_text() gains direct coverage.
* wisdom: re-apply owner copy after rebase
- Native share cards (advice_view/interaction_view): drop the approval line, ask "Would you like to share it?" as the last line after the checks
- Hermes-written completion card titled "Hermes Collective Wisdom"
- Qualification reasons use the owner wording (consistently across many days / really refined)
- American spelling (organization) in remaining English copy
- Desktop test asserts the current Share button; web test matches the returning notice
* fix(wisdom): pin reconciled Gateway and verify Unicode hash vectors
Pin Gateway 60cd2d6b613ae3cd4a6e65155d1142006d907e78 and byte-identical producer artifacts. Verify every content-order case and package-manifest binding. Validation: 186 focused Python tests, Ruff and contract verifier.
* fix(wisdom): reconcile optional SDK tests and frontend lint
* fix(wisdom): default to agent-written notification summaries
* fix(wisdom): restore deferred install review and browse controls
* feat(wisdom): inspect installed setup with exact package provenance
* feat(wisdom): run native-approved installed setup steps with durable evidence
* fix(wisdom): recover interrupted setup with explicit native consent
* feat(wisdom): hand native installs into guided setup review
* fix(wisdom): continue requested setup with fixed notification copy
* fix(wisdom): preserve setup while waiting for a session model
* fix(wisdom): expose canonical setup review controls on desktop
* fix(wisdom): resume setup after recorded automatic updates
* fix(wisdom): make missing setup prerequisites recheckable
* chore(wisdom): align Agent with verified Gateway contract
* fix(wisdom): stop guessing team slugs in portal links
* fix(wisdom): retire pending advice on account sign-out
* fix(wisdom): cancel advice after terminal account revocation
* fix(wisdom): fence feed responses across account sign-out
* fix(wisdom): checkpoint signed-out feed before reactivation
* fix(wisdom): link proactive advice to scoped notification settings
* fix(wisdom): coalesce queued publication recommendations by version
* fix(wisdom): keep package review navigation local and deferable
* fix(wisdom): reflect installed state in discovery controls
* fix(wisdom): show exact checks before command confirmation
* chore(wisdom): pin bounded analytics privacy contract
* chore(wisdom): pin retired legacy notification contract
* feat(wisdom): review publisher usage with exact sharing copy
* fix(wisdom): align discovery and review check summaries
* fix(wisdom): show expired consent before confirmation
* fix(wisdom): require fresh review for legacy install controls
* fix(wisdom): preserve review expiry across check toggles
* fix(wisdom): retain update policy in native install reviews
* fix(wisdom): surface failed native card edits
* fix(wisdom): persist local command approval reviews
* fix(wisdom): use saved approvals for messaging commands
* test(wisdom): provide scan result in setup handoff fixture
* test(wisdom): exercise Telegram approvals with saved review state
* fix(wisdom): retain suppression policy for offline deferral
* fix(wisdom): reconsider candidates after deferred suppression expires
* fix(wisdom): bind review checks and report verified readiness separately
* fix(wisdom): persist accepted publication intent and recover exact outcomes
* fix(sync): pin UTF-8 tree ordering across writers
* chore(wisdom): pin organisation-scoped Gateway authorization
* fix(wisdom): restrict consent delivery to user-facing sessions
* chore(wisdom): refresh reviewed Gateway contract pin
* fix(wisdom): preserve kept tools in Blank Slate exclusions
* test(auth): reset anonymous fixture with a profile-scoped cache
* fix(wisdom): gate local surfaces and work on current profile entitlement
* fix(wisdom): invalidate quiet tool cache on entitlement changes
* test(wisdom): authorize local consent gateway fixtures
* fix(wisdom): keep entitlement decoding free of native crypto imports
* test(wisdom): provide local entitlement to demo CLI subprocess
* ci: leave upstream workflow unchanged in Wisdom PR
* fix(wisdom): ship package and contracts in Nix wheels
---------
Co-authored-by: hbizi <36184542+hbizi@users.noreply.github.com>
349 lines
15 KiB
Python
349 lines
15 KiB
Python
"""Trusted product notifications; not part of the model-facing message schema."""
|
|
|
|
import html
|
|
import inspect
|
|
import logging
|
|
import re
|
|
|
|
from agent.secret_scope import get_secret
|
|
from tools.send_message_senders import _error, _sanitize_error_text, _send_telegram
|
|
|
|
logger = logging.getLogger("tools.send_message_tool")
|
|
|
|
|
|
def telegram_notification_markup(*, action_button_rows=None, action_buttons=None, url_buttons=None):
|
|
"""Build an inline keyboard from already validated internal controls."""
|
|
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
|
|
|
rows = action_button_rows or [[button] for button in (action_buttons or url_buttons or [])]
|
|
if not rows:
|
|
return None
|
|
return InlineKeyboardMarkup([
|
|
[InlineKeyboardButton(
|
|
str(button["label"]),
|
|
**({"url": str(button["url"])} if button.get("url") else {"callback_data": str(button["callback_data"])}),
|
|
) for button in row]
|
|
for row in rows if row
|
|
])
|
|
|
|
|
|
async def try_telegram_rich_notification(bot, chat_id, rich_html, thread_kwargs, *, disable_link_previews=False):
|
|
"""Return a receipt or error; None permits fallback only after definite rejection."""
|
|
raw_request = getattr(bot, "do_api_request", None)
|
|
if not inspect.iscoroutinefunction(raw_request):
|
|
return None
|
|
payload = {"chat_id": chat_id, "rich_message": {"html": rich_html}, **thread_kwargs}
|
|
if disable_link_previews:
|
|
payload["link_preview_options"] = {"is_disabled": True}
|
|
try:
|
|
result = await raw_request("sendRichMessage", api_kwargs=payload)
|
|
except Exception as exc:
|
|
error_text = str(exc).lower()
|
|
permanent_rejection = (
|
|
exc.__class__.__name__.lower() in {"badrequest", "endpointnotfound"}
|
|
or getattr(exc, "error_code", None) in {400, 404}
|
|
or isinstance(exc, (AttributeError, TypeError, NotImplementedError))
|
|
or (("method" in error_text or "endpoint" in error_text)
|
|
and ("not found" in error_text or "does not exist" in error_text))
|
|
or "unsupported" in error_text
|
|
or "not implemented" in error_text
|
|
)
|
|
if not permanent_rejection:
|
|
logger.warning("Telegram rich notification failed; not resending to avoid a duplicate: %s",
|
|
_sanitize_error_text(exc))
|
|
return _error(f"Telegram rich notification failed: {_sanitize_error_text(exc)}")
|
|
logger.debug("Telegram rejected rich notification; falling back to inline keyboard: %s",
|
|
_sanitize_error_text(exc))
|
|
return None
|
|
if isinstance(result, dict):
|
|
message_id = result.get("message_id")
|
|
if message_id is None:
|
|
message_id = (result.get("result") or {}).get("message_id")
|
|
else:
|
|
message_id = getattr(result, "message_id", None)
|
|
return {"success": True, "message_id": str(message_id) if message_id is not None else None}
|
|
|
|
|
|
def send_telegram_notification_pane(
|
|
*,
|
|
message: str,
|
|
button_rows: list[list[dict[str, str]]],
|
|
items: list[dict[str, object]] | None = None,
|
|
) -> dict:
|
|
"""Send an internal notification to the Telegram home chat with trusted actions.
|
|
|
|
This is intentionally not part of the model-facing ``send_message`` schema.
|
|
Product notifications can offer trusted managed actions and Portal deep
|
|
links without giving an arbitrary tool caller a second, Telegram-specific
|
|
message surface. Rows are explicit so each skill keeps its action and link
|
|
together. Bot API 10.3 clients render the trusted controls directly inside
|
|
each rich-message item; the compact inline keyboard is retained as a safe
|
|
fallback for older Bot API servers and clients.
|
|
"""
|
|
from tools.send_message_tool import prepare_send_message_platforms
|
|
|
|
prepare_send_message_platforms()
|
|
try:
|
|
from gateway.config import Platform, load_gateway_config
|
|
|
|
config = load_gateway_config()
|
|
platform = Platform.TELEGRAM
|
|
pconfig = config.platforms.get(platform)
|
|
if not pconfig or not pconfig.enabled:
|
|
return _error("Telegram is not configured")
|
|
home = config.get_home_channel(platform)
|
|
if not home:
|
|
return _error("Telegram has no configured home channel")
|
|
|
|
safe_rows: list[list[dict[str, str]]] = []
|
|
safe_rows_by_item: list[list[dict[str, str]]] = []
|
|
button_count = 0
|
|
for row in button_rows[:8]:
|
|
safe_row: list[dict[str, str]] = []
|
|
for button in row[:2]:
|
|
if button_count >= 16:
|
|
break
|
|
label = str(button.get("label") or "").strip()[:32]
|
|
url = str(button.get("url") or "").strip()
|
|
if label and re.fullmatch(r"https?://[^\s]+", url):
|
|
safe_row.append({"label": label, "url": url})
|
|
button_count += 1
|
|
continue
|
|
callback_data = str(button.get("callback_data") or "").strip()
|
|
if (
|
|
label
|
|
and len(callback_data.encode("utf-8")) <= 64
|
|
and re.fullmatch(
|
|
r"wi:(?:plan:(?:install|update):[A-Za-z0-9_-]+|"
|
|
r"confirm:(?:install|update):w(?:ip|up)_[a-f0-9]+|cancel)",
|
|
callback_data,
|
|
)
|
|
):
|
|
safe_row.append({
|
|
"label": label,
|
|
"callback_data": callback_data,
|
|
})
|
|
button_count += 1
|
|
safe_rows_by_item.append(safe_row)
|
|
if safe_row:
|
|
safe_rows.append(safe_row)
|
|
|
|
rich_message_html = None
|
|
if items:
|
|
rich_item_parts: list[str] = []
|
|
for item, item_buttons in zip(items[:8], safe_rows_by_item):
|
|
heading = html.escape(str(item.get("heading") or "").strip())
|
|
detail = html.escape(str(item.get("detail") or "").strip())
|
|
detail = detail.replace("\r\n", "\n").replace("\r", "\n")
|
|
detail = detail.replace("\n", "<br/>")
|
|
if not heading or not detail:
|
|
continue
|
|
controls: list[str] = []
|
|
for button in item_buttons:
|
|
label = html.escape(button["label"])
|
|
if button.get("url"):
|
|
controls.append(
|
|
'<tg-button type="url" url="'
|
|
f'{html.escape(button["url"], quote=True)}">'
|
|
f"{label}</tg-button>"
|
|
)
|
|
else:
|
|
controls.append(
|
|
'<tg-button type="callback_data" style="primary" data="'
|
|
f'{html.escape(button["callback_data"], quote=True)}">'
|
|
f"{label}</tg-button>"
|
|
)
|
|
control_html = (
|
|
f'<tg-button-row align="left">'
|
|
f"{' '.join(controls)}"
|
|
"</tg-button-row>"
|
|
if controls
|
|
else ""
|
|
)
|
|
rich_item_parts.append(
|
|
f"<p><b>{heading}</b><br/>{detail}</p>{control_html}"
|
|
)
|
|
if rich_item_parts:
|
|
item_count = len(rich_item_parts)
|
|
rich_parts = [
|
|
# Telegram owns rich-message bubble sizing and exposes no
|
|
# width/min-width control. Keep a stable, naturally wider
|
|
# product heading so short skill names and one-word actions
|
|
# do not collapse these notifications into narrow cards.
|
|
"<h3>Hermes Collective Wisdom</h3>",
|
|
(
|
|
f"<p>{item_count} new "
|
|
f"{'notification' if item_count == 1 else 'notifications'}</p>"
|
|
),
|
|
*rich_item_parts,
|
|
]
|
|
rich_message_html = "".join(rich_parts)
|
|
|
|
from model_tools import _run_async
|
|
|
|
result = _run_async(
|
|
_send_telegram(
|
|
pconfig.token,
|
|
home.chat_id,
|
|
message,
|
|
disable_link_previews=True,
|
|
action_button_rows=safe_rows,
|
|
rich_message_html=rich_message_html,
|
|
)
|
|
)
|
|
return result if isinstance(result, dict) else {"success": bool(result)}
|
|
except Exception as exc:
|
|
return _error(f"Telegram notification failed: {exc}")
|
|
|
|
|
|
def send_slack_wisdom_notification_pane(
|
|
*,
|
|
message: str,
|
|
button_rows: list[list[dict[str, str]]],
|
|
items: list[dict[str, object]],
|
|
) -> dict:
|
|
"""Send a trusted Collective Wisdom Block Kit pane to Slack's home chat.
|
|
|
|
This internal surface deliberately accepts only Wisdom's compact managed
|
|
callback grammar and HTTPS Portal links. It is not exposed through the
|
|
model-facing ``send_message`` tool.
|
|
"""
|
|
from tools.send_message_tool import prepare_send_message_platforms
|
|
|
|
prepare_send_message_platforms()
|
|
try:
|
|
from gateway.config import Platform, load_gateway_config
|
|
from model_tools import _run_async
|
|
|
|
config = load_gateway_config()
|
|
pconfig = config.platforms.get(Platform.SLACK)
|
|
if not pconfig or not pconfig.enabled:
|
|
return _error("Slack is not configured")
|
|
home = config.get_home_channel(Platform.SLACK)
|
|
if not home:
|
|
return _error("Slack has no configured home channel")
|
|
|
|
blocks: list[dict[str, object]] = [
|
|
{
|
|
"type": "header",
|
|
"text": {
|
|
"type": "plain_text",
|
|
"text": "Hermes Collective Wisdom",
|
|
"emoji": True,
|
|
},
|
|
},
|
|
{
|
|
"type": "section",
|
|
"text": {
|
|
"type": "mrkdwn",
|
|
"text": (
|
|
f"{len(items[:8])} new "
|
|
f"{'update' if len(items[:8]) == 1 else 'updates'}"
|
|
),
|
|
},
|
|
},
|
|
]
|
|
for item_index, (item, row) in enumerate(
|
|
zip(items[:8], button_rows[:8])
|
|
):
|
|
heading = str(item.get("heading") or "").strip()[:150]
|
|
detail = str(item.get("detail") or "").strip()[:2600]
|
|
if not heading or not detail:
|
|
continue
|
|
safe_heading = heading.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
safe_detail = detail.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
blocks.append(
|
|
{
|
|
"type": "section",
|
|
"text": {
|
|
"type": "mrkdwn",
|
|
"text": f"*{safe_heading}*\n{safe_detail}",
|
|
},
|
|
}
|
|
)
|
|
buttons: list[dict[str, object]] = []
|
|
for button_index, button in enumerate(row[:2]):
|
|
label = str(button.get("label") or "").strip()[:75]
|
|
if not label:
|
|
continue
|
|
element: dict[str, object] = {
|
|
"type": "button",
|
|
"text": {"type": "plain_text", "text": label, "emoji": True},
|
|
"action_id": (
|
|
f"hermes_wisdom_feed_{item_index}_{button_index}"
|
|
),
|
|
}
|
|
url = str(button.get("url") or "").strip()
|
|
# These are trusted product links assembled by Wisdom, not
|
|
# model-authored buttons. Permit HTTP as well so the local
|
|
# demo Portal retains the same View action as production.
|
|
if re.fullmatch(r"https?://[^\s]+", url):
|
|
element["url"] = url
|
|
element["value"] = "wisdom:portal"
|
|
else:
|
|
callback_data = str(button.get("callback_data") or "").strip()
|
|
if not re.fullmatch(
|
|
r"wi:plan:(?:install|update):[A-Za-z0-9_-]+",
|
|
callback_data,
|
|
):
|
|
continue
|
|
element["value"] = callback_data
|
|
element["style"] = "primary"
|
|
buttons.append(element)
|
|
if buttons:
|
|
blocks.append({"type": "actions", "elements": buttons})
|
|
|
|
async def send() -> dict:
|
|
try:
|
|
from slack_sdk.web.async_client import AsyncWebClient
|
|
except ImportError:
|
|
return _error("slack_sdk is not installed")
|
|
raw_token = getattr(pconfig, "token", None) or get_secret(
|
|
"SLACK_BOT_TOKEN", ""
|
|
)
|
|
tokens = [
|
|
token.strip()
|
|
for token in str(raw_token or "").split(",")
|
|
if token.strip()
|
|
]
|
|
if not tokens:
|
|
return _error("Slack bot token is not configured")
|
|
last_error = "unknown"
|
|
for token in tokens:
|
|
try:
|
|
client = AsyncWebClient(token=token)
|
|
if home.thread_id:
|
|
response = await client.chat_postMessage(
|
|
channel=home.chat_id,
|
|
text=message[:39000],
|
|
blocks=blocks[:50],
|
|
unfurl_links=False,
|
|
unfurl_media=False,
|
|
thread_ts=str(home.thread_id),
|
|
)
|
|
else:
|
|
response = await client.chat_postMessage(
|
|
channel=home.chat_id,
|
|
text=message[:39000],
|
|
blocks=blocks[:50],
|
|
unfurl_links=False,
|
|
unfurl_media=False,
|
|
)
|
|
payload = getattr(response, "data", response)
|
|
if isinstance(payload, dict) and payload.get("ok", True):
|
|
return {
|
|
"success": True,
|
|
"message_id": payload.get("ts"),
|
|
"private": str(home.chat_id).startswith("D"),
|
|
}
|
|
if isinstance(payload, dict):
|
|
last_error = str(payload.get("error") or last_error)
|
|
except Exception as exc:
|
|
last_error = str(exc)
|
|
return _error(f"Slack notification failed: {last_error}")
|
|
|
|
result = _run_async(send())
|
|
return result if isinstance(result, dict) else {"success": bool(result)}
|
|
except Exception as exc:
|
|
return _error(f"Slack notification failed: {exc}")
|