-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmc.py
More file actions
executable file
路634 lines (557 loc) 路 26.9 KB
/
Copy pathmc.py
File metadata and controls
executable file
路634 lines (557 loc) 路 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = ["typer>=0.12", "msal>=1.28"]
# ///
"""Message Center CLI: read M365 Message Center posts and push them to Microsoft Planner.
Always your own identity, never an app secret, via one of two modes (--auth, or MC_AUTH in the
environment): az reuses the Azure CLI login through `az rest`, and device signs you in with a
device code through the Microsoft Graph Command Line Tools public client. Use device when az mode
403s: Microsoft does not let the Azure CLI app request these Graph scopes (AADSTS65002). Reading
messages needs a Message Center capable role (Message Center Reader is enough); writing to Planner
needs nothing beyond membership of the group that owns the plan.
Commands:
messages List Message Center posts, filtered by service, category, severity, and time.
summarise Produce a markdown summary of the filtered posts.
post Create Planner tasks from the filtered posts (one per post, or one rollup task).
plans Discover plan ids and buckets for a group, to feed into post.
Run `mc.py <command> --help` for the filters each command takes.
"""
import csv
import datetime as dt
import html
import json
import re
import subprocess
import urllib.error
import urllib.request
from pathlib import Path
from collections import Counter
from typing import List, Optional
import typer
GRAPH = "https://graph.microsoft.com/v1.0"
ADMIN_LINK = "https://admin.microsoft.com/#/MessageCenter/:/messages/{id}"
# The Microsoft Graph Command Line Tools public client (the app Connect-MgGraph uses). Unlike the
# Azure CLI's first-party app, it is allowed to request these delegated Graph scopes dynamically,
# so device auth works where az scoped logins die with AADSTS65002 (Microsoft first-party apps can
# only request scopes Microsoft preauthorized for them, and these are not among the Azure CLI's).
GRAPH_CLI_APP = "14d82eec-204b-4c2f-b7e8-296a70dab67e"
# Lean by design: Group.Read.All is deliberately NOT requested (admin-consent-gated in most
# corporate tenants, and only the group-name lookup needs it; plans with no arguments and everything
# else run on Tasks.ReadWrite). Consent is all-or-nothing per sign-in.
DEVICE_SCOPES = ["ServiceMessage.Read.All", "Tasks.ReadWrite"]
TOKEN_CACHE = Path.home() / ".config" / "m365-mc-planner" / "token-cache.json"
class Auth:
"""Process-wide auth selection, set by the root callback before any command runs."""
mode = "az"
tenant = "organizations"
client_id = GRAPH_CLI_APP
_token: Optional[str] = None
# Short names for the services people actually say, mapped to substrings matched (case-insensitive)
# against the message's services list. Anything not in this table is used as a raw substring, so
# `--service "power platform"` works without an alias.
SERVICE_ALIASES = {
"xdr": ["defender xdr", "365 defender"],
"defender": ["defender"],
"mde": ["defender for endpoint"],
"mdo": ["defender for office"],
"purview": ["purview"],
"azure": ["azure"],
"entra": ["entra", "azure ad", "identity"],
"intune": ["intune"],
"teams": ["teams"],
"exchange": ["exchange"],
"sharepoint": ["sharepoint"],
"onedrive": ["onedrive"],
"copilot": ["copilot"],
"sentinel": ["sentinel"],
"planner": ["planner"],
"power": ["power apps", "power automate", "power bi", "power platform"],
}
CATEGORY_ALIASES = {
"plan": "planForChange",
"planforchange": "planForChange",
"stay": "stayInformed",
"stayinformed": "stayInformed",
"prevent": "preventOrFixIssue",
"preventorfixissue": "preventOrFixIssue",
}
app = typer.Typer(
add_completion=False,
no_args_is_help=True,
help=__doc__,
context_settings={"help_option_names": ["-h", "--help"]},
)
@app.callback()
def _root(
auth: str = typer.Option(
"az",
"--auth",
envvar="MC_AUTH",
help="az (reuse the Azure CLI identity), device (device-code sign-in via the Microsoft Graph Command Line Tools public client; use when az mode 403s with AADSTS65002), or interactive (browser sign-in with the same client; use when Conditional Access blocks device code).",
),
tenant: str = typer.Option(
"organizations",
"--tenant",
envvar="MC_TENANT",
help="Tenant id or domain for device auth (device mode only).",
),
client_id: str = typer.Option(
GRAPH_CLI_APP,
"--client-id",
envvar="MC_CLIENT_ID",
help="Public client app id for device/interactive sign-in. Override when a tenant blocks the Microsoft Graph Command Line Tools app with AADSTS50105 (assignment required) and permits another public client with the same delegated scopes.",
),
):
if auth not in ("az", "device", "interactive"):
typer.secho("--auth must be az, device, or interactive.", fg="red", err=True)
raise typer.Exit(2)
Auth.mode = auth
Auth.tenant = tenant
Auth.client_id = client_id
# ---------------------------------------------------------------------------- az plumbing
def _az_rest(method: str, url: str, body: Optional[dict] = None, headers: Optional[dict] = None) -> Optional[dict]:
"""Call Microsoft Graph through `az rest` and return the parsed JSON (None for empty replies)."""
cmd = ["az", "rest", "--method", method, "--url", url, "--output", "json"]
if body is not None:
cmd += ["--body", json.dumps(body)]
for k, v in (headers or {}).items():
cmd += ["--headers", f"{k}={v}"]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
typer.secho("The Azure CLI (az) is not on PATH. Install it and run az login first.", fg="red", err=True)
raise typer.Exit(2)
if proc.returncode != 0:
err = proc.stderr.strip()
typer.secho(f"Graph call failed: {method.upper()} {url}", fg="red", err=True)
typer.secho(err[:2000], err=True)
if "403" in err or "Forbidden" in err or "Insufficient privileges" in err or "UnknownError" in err:
_permission_hint()
raise typer.Exit(1)
out = proc.stdout.strip()
return json.loads(out) if out else None
def _user_token() -> str:
"""Delegated token via device-code or interactive browser sign-in, cached (with refresh) on disk."""
if Auth._token:
return Auth._token
import msal
TOKEN_CACHE.parent.mkdir(parents=True, exist_ok=True)
cache = msal.SerializableTokenCache()
if TOKEN_CACHE.exists():
cache.deserialize(TOKEN_CACHE.read_text())
pca = msal.PublicClientApplication(
Auth.client_id, authority=f"https://login.microsoftonline.com/{Auth.tenant}", token_cache=cache
)
result = None
accounts = pca.get_accounts()
if accounts:
result = pca.acquire_token_silent(DEVICE_SCOPES, account=accounts[0])
if not result and Auth.mode == "interactive":
result = pca.acquire_token_interactive(DEVICE_SCOPES, prompt="select_account")
elif not result:
flow = pca.initiate_device_flow(scopes=DEVICE_SCOPES)
if "user_code" not in flow:
typer.secho(f"Could not start the device flow: {flow.get('error_description', flow)}", fg="red", err=True)
raise typer.Exit(1)
typer.secho(flow["message"], fg="cyan", err=True)
result = pca.acquire_token_by_device_flow(flow)
if "access_token" not in result:
typer.secho(f"Sign-in failed: {result.get('error_description', result.get('error'))}", fg="red", err=True)
if Auth.mode == "device":
typer.secho("If Conditional Access blocks device code sign-in, try: --auth interactive (or MC_AUTH=interactive).", fg="yellow", err=True)
raise typer.Exit(1)
if cache.has_state_changed:
TOKEN_CACHE.write_text(cache.serialize())
TOKEN_CACHE.chmod(0o600)
Auth._token = result["access_token"]
return Auth._token
def _permission_hint() -> None:
typer.secho(
"\nThis is a permissions problem, not a script problem. Check that:\n"
" 1. You are signed in to the right tenant (az account show, or --tenant for device auth).\n"
" 2. Reading messages: your account holds a Message Center capable admin role\n"
" (Message Center Reader is enough).\n"
" 3. Posting to Planner: you are a member of the group that owns the plan.\n"
" 4. In az mode a 403 usually means the Azure CLI token lacks the Graph scopes, and\n"
" Microsoft does not let the az app request them (AADSTS65002). Switch to device auth,\n"
" which signs in as you through the Microsoft Graph Command Line Tools client:\n"
" mc.py --auth device <command> ... (or export MC_AUTH=device)",
fg="yellow",
err=True,
)
def graph_call(method: str, url: str, body: Optional[dict] = None, headers: Optional[dict] = None) -> Optional[dict]:
"""Call Graph with whichever identity source --auth selected."""
if Auth.mode == "az":
return _az_rest(method, url, body=body, headers=headers)
token = _user_token()
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, method=method.upper(), data=data)
req.add_header("Authorization", f"Bearer {token}")
req.add_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
req.add_header(k, v)
try:
with urllib.request.urlopen(req) as resp:
text = resp.read().decode()
except urllib.error.HTTPError as e:
detail = e.read().decode(errors="replace")
typer.secho(f"Graph call failed ({e.code}): {method.upper()} {url}", fg="red", err=True)
typer.secho(detail[:2000], err=True)
if e.code == 403:
_permission_hint()
raise typer.Exit(1)
return json.loads(text) if text else None
def graph_get_all(url: str) -> List[dict]:
"""GET a Graph collection, following @odata.nextLink until exhausted."""
items: List[dict] = []
while url:
page = graph_call("get", url) or {}
items.extend(page.get("value", []))
url = page.get("@odata.nextLink")
return items
# ---------------------------------------------------------------------------- filtering
def parse_period(
day: Optional[str], week: Optional[str], month: Optional[str], year: Optional[str]
) -> Optional[tuple]:
"""Turn exactly one of day/week/month/year into a (start, end, label) UTC window."""
supplied = [p for p in (day, week, month, year) if p is not None]
if not supplied:
return None
if len(supplied) > 1:
typer.secho("Use only one of --day, --week, --month, --year.", fg="red", err=True)
raise typer.Exit(2)
today = dt.datetime.now(dt.timezone.utc).date()
if day is not None:
if day == "today":
d = today
elif day == "yesterday":
d = today - dt.timedelta(days=1)
else:
d = dt.date.fromisoformat(day)
start = dt.datetime.combine(d, dt.time.min, dt.timezone.utc)
return start, start + dt.timedelta(days=1), f"day {d.isoformat()}"
if week is not None:
if week in ("this", "last"):
anchor = today if week == "this" else today - dt.timedelta(days=7)
iso = anchor.isocalendar()
y, w = iso[0], iso[1]
else:
m = re.fullmatch(r"(\d{4})-W(\d{1,2})", week)
if not m:
typer.secho("Week must be this, last, or ISO form like 2026-W29.", fg="red", err=True)
raise typer.Exit(2)
y, w = int(m.group(1)), int(m.group(2))
monday = dt.date.fromisocalendar(y, w, 1)
start = dt.datetime.combine(monday, dt.time.min, dt.timezone.utc)
return start, start + dt.timedelta(days=7), f"week {y}-W{w:02d}"
if month is not None:
if month in ("this", "last"):
anchor = today.replace(day=1)
if month == "last":
anchor = (anchor - dt.timedelta(days=1)).replace(day=1)
y, mo = anchor.year, anchor.month
else:
m = re.fullmatch(r"(\d{4})-(\d{1,2})", month)
if not m:
typer.secho("Month must be this, last, or ISO form like 2026-07.", fg="red", err=True)
raise typer.Exit(2)
y, mo = int(m.group(1)), int(m.group(2))
start = dt.datetime(y, mo, 1, tzinfo=dt.timezone.utc)
end = dt.datetime(y + 1, 1, 1, tzinfo=dt.timezone.utc) if mo == 12 else dt.datetime(y, mo + 1, 1, tzinfo=dt.timezone.utc)
return start, end, f"month {y}-{mo:02d}"
y = int(year)
start = dt.datetime(y, 1, 1, tzinfo=dt.timezone.utc)
return start, dt.datetime(y + 1, 1, 1, tzinfo=dt.timezone.utc), f"year {y}"
def msg_datetime(msg: dict, date_field: str) -> Optional[dt.datetime]:
raw = msg.get(date_field)
if not raw:
return None
return dt.datetime.fromisoformat(raw.replace("Z", "+00:00"))
def wanted_service(msg: dict, service_terms: List[str]) -> bool:
if not service_terms:
return True
services = " | ".join(msg.get("services") or []).lower()
for term in service_terms:
for needle in SERVICE_ALIASES.get(term.lower(), [term.lower()]):
if needle in services:
return True
return False
def filter_messages(
messages: List[dict],
services: List[str],
category: Optional[str],
severity: Optional[str],
major_only: bool,
period: Optional[tuple],
date_field: str,
) -> List[dict]:
out = []
want_category = CATEGORY_ALIASES.get(category.lower()) if category else None
if category and not want_category:
typer.secho("Category must be one of: planForChange, stayInformed, preventOrFixIssue.", fg="red", err=True)
raise typer.Exit(2)
for m in messages:
if not wanted_service(m, services):
continue
if want_category and m.get("category") != want_category:
continue
if severity and (m.get("severity") or "").lower() != severity.lower():
continue
if major_only and not m.get("isMajorChange"):
continue
if period:
when = msg_datetime(m, date_field)
if when is None or not (period[0] <= when < period[1]):
continue
out.append(m)
out.sort(key=lambda m: m.get(date_field) or "", reverse=True)
return out
def fetch_filtered(services, category, severity, major_only, day, week, month, year, date_field):
period = parse_period(day, week, month, year)
messages = graph_get_all(f"{GRAPH}/admin/serviceAnnouncement/messages?$top=100")
return filter_messages(messages, services, category, severity, major_only, period, date_field), period
def strip_html(text: str, cap: int = 2000) -> str:
text = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
text = re.sub(r"<br\s*/?>|</p>|</li>", "\n", text, flags=re.I)
text = re.sub(r"<[^>]+>", " ", text)
text = html.unescape(text)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n\s*\n\s*", "\n\n", text).strip()
return text[:cap] + (" ..." if len(text) > cap else "")
CSV_FIELDS = [
"id", "title", "category", "severity", "isMajorChange", "services", "tags",
"lastModifiedDateTime", "startDateTime", "endDateTime", "actionRequiredByDateTime",
"adminCenterLink", "bodyText",
]
def write_csv(messages: List[dict], path: str) -> None:
"""Write the filtered messages as CSV. utf-8-sig so Excel picks up the encoding on open."""
with open(path, "w", newline="", encoding="utf-8-sig") as fh:
writer = csv.writer(fh)
writer.writerow(CSV_FIELDS)
for m in messages:
writer.writerow([
m.get("id", ""),
m.get("title", ""),
m.get("category", ""),
m.get("severity", ""),
bool(m.get("isMajorChange")),
"; ".join(m.get("services") or []),
"; ".join(m.get("tags") or []),
m.get("lastModifiedDateTime", ""),
m.get("startDateTime", ""),
m.get("endDateTime", ""),
m.get("actionRequiredByDateTime", ""),
ADMIN_LINK.format(id=m.get("id", "")),
strip_html((m.get("body") or {}).get("content") or "", cap=1000),
])
def build_summary(messages: List[dict], period, services, category, severity, date_field) -> str:
label_bits = []
if period:
label_bits.append(period[2])
if services:
label_bits.append("services: " + ", ".join(services))
if category:
label_bits.append(f"category: {category}")
if severity:
label_bits.append(f"severity: {severity}")
label = "; ".join(label_bits) if label_bits else "all messages"
sev = Counter((m.get("severity") or "normal") for m in messages)
lines = [
f"# Message Center summary ({label})",
"",
f"Total: {len(messages)} messages "
f"({sev.get('critical', 0)} critical, {sev.get('high', 0)} high, {sev.get('normal', 0)} normal)",
"",
"## By service",
]
by_service = Counter(s for m in messages for s in (m.get("services") or ["(none)"]))
for name, count in by_service.most_common():
lines.append(f"- {name}: {count}")
lines += ["", "## By category"]
for name, count in Counter(m.get("category") or "(none)" for m in messages).most_common():
lines.append(f"- {name}: {count}")
action = [m for m in messages if m.get("actionRequiredByDateTime")]
if action:
lines += ["", "## Action required"]
for m in sorted(action, key=lambda m: m["actionRequiredByDateTime"]):
due = m["actionRequiredByDateTime"][:10]
lines.append(f"- {m['id']} due {due}: {m.get('title', '')}")
lines += ["", "## Messages"]
for m in messages:
when = (m.get(date_field) or "")[:10]
svc = ", ".join(m.get("services") or [])
lines.append(f"- {m['id']} {when} [{svc}] {m.get('title', '')}")
return "\n".join(lines)
# Shared filter options, spelled once.
OPT_SERVICE = typer.Option(None, "--service", "-s", help="Service filter, repeatable. Short names (xdr, purview, azure, entra, intune, teams ...) or any substring of the service name.")
OPT_CATEGORY = typer.Option(None, "--category", "-c", help="planForChange, stayInformed, or preventOrFixIssue (plan/stay/prevent also accepted).")
OPT_SEVERITY = typer.Option(None, "--severity", help="normal, high, or critical.")
OPT_MAJOR = typer.Option(False, "--major", help="Only major-change messages.")
OPT_DAY = typer.Option(None, "--day", help="A date (2026-07-20), today, or yesterday.")
OPT_WEEK = typer.Option(None, "--week", help="An ISO week (2026-W29), this, or last.")
OPT_MONTH = typer.Option(None, "--month", help="A month (2026-07), this, or last.")
OPT_YEAR = typer.Option(None, "--year", help="A year (2026).")
OPT_DATE_FIELD = typer.Option("lastModifiedDateTime", "--date-field", help="Which timestamp the time filters compare against: lastModifiedDateTime or startDateTime.")
# ---------------------------------------------------------------------------- commands
@app.command()
def messages(
service: List[str] = OPT_SERVICE,
category: Optional[str] = OPT_CATEGORY,
severity: Optional[str] = OPT_SEVERITY,
major: bool = OPT_MAJOR,
day: Optional[str] = OPT_DAY,
week: Optional[str] = OPT_WEEK,
month: Optional[str] = OPT_MONTH,
year: Optional[str] = OPT_YEAR,
date_field: str = OPT_DATE_FIELD,
output: str = typer.Option("table", "--output", "-o", help="table, json, or ids."),
limit: int = typer.Option(0, "--limit", help="Show at most this many rows (0 = all)."),
out_csv: Optional[str] = typer.Option(None, "--out-csv", help="Write the filtered messages to this CSV file instead of printing them."),
):
"""List Message Center posts with the chosen filters."""
msgs, _ = fetch_filtered(service, category, severity, major, day, week, month, year, date_field)
if limit:
msgs = msgs[:limit]
if out_csv:
write_csv(msgs, out_csv)
typer.secho(f"Wrote {out_csv} ({len(msgs)} messages).", fg="green")
return
if output == "json":
typer.echo(json.dumps(msgs, indent=2))
return
if output == "ids":
for m in msgs:
typer.echo(m["id"])
return
if not msgs:
typer.secho("No messages matched.", fg="yellow")
return
typer.echo(f"{'ID':<10} {'SEV':<9} {'MODIFIED':<11} {'SERVICES':<32} TITLE")
for m in msgs:
svc = ", ".join(m.get("services") or [])
typer.echo(
f"{m['id']:<10} {(m.get('severity') or ''):<9} {(m.get(date_field) or '')[:10]:<11} "
f"{svc[:31]:<32} {(m.get('title') or '')[:70]}"
)
typer.secho(f"\n{len(msgs)} message(s).", fg="green")
@app.command()
def summarise(
service: List[str] = OPT_SERVICE,
category: Optional[str] = OPT_CATEGORY,
severity: Optional[str] = OPT_SEVERITY,
major: bool = OPT_MAJOR,
day: Optional[str] = OPT_DAY,
week: Optional[str] = OPT_WEEK,
month: Optional[str] = OPT_MONTH,
year: Optional[str] = OPT_YEAR,
date_field: str = OPT_DATE_FIELD,
out: Optional[str] = typer.Option(None, "--out", help="Write the markdown to this file instead of stdout."),
):
"""Summarise the filtered posts as markdown (counts by service, category, action-required list)."""
msgs, period = fetch_filtered(service, category, severity, major, day, week, month, year, date_field)
text = build_summary(msgs, period, service, category, severity, date_field)
if out:
with open(out, "w") as fh:
fh.write(text + "\n")
typer.secho(f"Wrote {out} ({len(msgs)} messages).", fg="green")
else:
typer.echo(text)
@app.command()
def plans(
group_name: Optional[str] = typer.Option(None, "--group-name", "-g", help="Display name of the M365 group that owns the plan. Omit to list YOUR plans instead, which is the only way to find roster plans (new Planner personal boards, no group behind them)."),
buckets: bool = typer.Option(False, "--buckets", help="Also list each plan's buckets."),
):
"""Find plan ids (and optionally bucket ids), from a group or from your own memberships."""
if group_name is None:
for p in graph_get_all(f"{GRAPH}/me/planner/plans"):
typer.echo(f"plan: {p['title']} id: {p['id']}")
if buckets:
for b in graph_get_all(f"{GRAPH}/planner/plans/{p['id']}/buckets"):
typer.echo(f" bucket: {b['name']} id: {b['id']}")
return
safe = group_name.replace("'", "''")
groups = graph_get_all(f"{GRAPH}/groups?$filter=displayName eq '{safe}'&$select=id,displayName")
if not groups:
typer.secho(f"No group named '{group_name}' found (or no read access to it).", fg="red", err=True)
raise typer.Exit(1)
for g in groups:
typer.secho(f"Group: {g['displayName']} ({g['id']})", fg="cyan")
for p in graph_get_all(f"{GRAPH}/groups/{g['id']}/planner/plans"):
typer.echo(f" plan: {p['title']} id: {p['id']}")
if buckets:
for b in graph_get_all(f"{GRAPH}/planner/plans/{p['id']}/buckets"):
typer.echo(f" bucket: {b['name']} id: {b['id']}")
@app.command()
def post(
plan_id: str = typer.Option(..., "--plan-id", help="Planner plan id (find it with the plans command)."),
bucket_name: str = typer.Option("To be discussed", "--bucket-name", help="Bucket (board column) to post into; created if missing."),
rollup: bool = typer.Option(False, "--rollup", help="Create ONE task holding the whole summary instead of one task per message."),
dry_run: bool = typer.Option(False, "--dry-run", help="Show what would be created without writing anything."),
service: List[str] = OPT_SERVICE,
category: Optional[str] = OPT_CATEGORY,
severity: Optional[str] = OPT_SEVERITY,
major: bool = OPT_MAJOR,
day: Optional[str] = OPT_DAY,
week: Optional[str] = OPT_WEEK,
month: Optional[str] = OPT_MONTH,
year: Optional[str] = OPT_YEAR,
date_field: str = OPT_DATE_FIELD,
):
"""Create Planner tasks from the filtered posts. Re-runs are safe: existing tasks are skipped."""
msgs, period = fetch_filtered(service, category, severity, major, day, week, month, year, date_field)
if not msgs:
typer.secho("No messages matched; nothing to post.", fg="yellow")
return
existing_titles = [t.get("title") or "" for t in graph_get_all(f"{GRAPH}/planner/plans/{plan_id}/tasks")]
all_buckets = graph_get_all(f"{GRAPH}/planner/plans/{plan_id}/buckets")
bucket = next((b for b in all_buckets if b["name"].lower() == bucket_name.lower()), None)
if bucket is None:
if dry_run:
typer.echo(f"[dry-run] would create bucket '{bucket_name}'")
bucket = {"id": "(new)"}
else:
bucket = graph_call("post", f"{GRAPH}/planner/buckets", body={"name": bucket_name, "planId": plan_id, "orderHint": " !"})
typer.secho(f"Created bucket '{bucket_name}'.", fg="green")
def create_task(title: str, description: str, due: Optional[str]):
if dry_run:
typer.echo(f"[dry-run] would create task: {title}" + (f" (due {due[:10]})" if due else ""))
return
body = {"planId": plan_id, "bucketId": bucket["id"], "title": title}
if due:
body["dueDateTime"] = due
task = graph_call("post", f"{GRAPH}/planner/tasks", body=body)
details = graph_call("get", f"{GRAPH}/planner/tasks/{task['id']}/details")
graph_call(
"patch",
f"{GRAPH}/planner/tasks/{task['id']}/details",
body={"description": description, "previewType": "description"},
headers={"If-Match": details["@odata.etag"]},
)
typer.secho(f"Created: {title}", fg="green")
if rollup:
label = period[2] if period else dt.date.today().isoformat()
title = f"Message Center rollup: {label} ({len(msgs)} messages)"
if any(title == t for t in existing_titles):
typer.secho(f"Rollup task already exists, skipping: {title}", fg="yellow")
return
create_task(title, build_summary(msgs, period, service, category, severity, date_field)[:20000], None)
return
created = skipped = 0
for m in msgs:
title = f"{m['id']}: {(m.get('title') or '').strip()}"[:255]
if any(t.startswith(m["id"]) for t in existing_titles):
skipped += 1
continue
body_text = strip_html((m.get("body") or {}).get("content") or "")
description = (
f"Services: {', '.join(m.get('services') or [])}\n"
f"Category: {m.get('category')} Severity: {m.get('severity')} Major change: {bool(m.get('isMajorChange'))}\n"
f"Last modified: {(m.get('lastModifiedDateTime') or '')[:10]}\n"
f"Admin center: {ADMIN_LINK.format(id=m['id'])}\n\n{body_text}"
)
create_task(title, description, m.get("actionRequiredByDateTime"))
created += 1
typer.secho(f"Done: {created} created, {skipped} already present.", fg="green")
if __name__ == "__main__":
app()