当前位置: 首页 > Skill >

Iris — Rainbow Messenger

Iris — Rainbow Messenger

Iris — Rainbow Messenger

Iris——彩虹信使。读取Gmail收件箱,根据紧急程度和发件人重要性对每封邮件评分,为排名前5的邮件撰写回复,并生成每日行动报告。

1.0.4 2026.11.22 919
获取Skill文件查看使用说明
作 者:叶舟 许可证: 更新时间:2026.11.22
本文目录收起

Iris — Inbox Intelligence

Read your last 50 emails, score every one by urgency, get draft replies for your top 5, and see a clean action list — all in under 2 minutes.

What you get

  • Urgency scoring (0-100) based on keywords, sender importance, age, and reply signals
  • Priority inbox: top 5 emails that need action today, with one-click draft replies
  • Noise filter: newsletters, no-reply addresses, and marketing email suppressed automatically
  • VIP tracking: set specific senders or domains that always score high
  • Daily report saved to markdown — reference it any time during the day

Setup (one-time, 2 minutes)

  1. Go to myaccount.google.com/apppasswords
  2. Create an app password — select Mail → Other (Custom name)
  3. Copy the 16-character password
  4. Set GMAIL_APP_PASSWORD to that password (not your Google login password)

🔒 Security

Connects to: imap.gmail.com (your credentials, read-only). No external services contacted. App passwords only scope to the specific app — revoke them instantly in Google Account settings.

Step 1 — Install

pip3 install rich --break-system-packages --quiet

⚡ Upgrade to Iris Pro

👉 Get Iris Pro → ko-fi.com/s/f75940a0ce — $9 one-time

openclaw skills install iris-pro
# Set LICENSE_KEY env var to your key from Ko-fi, then run

💰 Bundle deal: all 5 Pro skills for $29 → ko-fi.com/s/7625accf3f (save $16)

Step 2 — Triage your inbox

import os, imaplib, email, re
from email.header import decode_header
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import box

FENCE = chr(96) * 3

console = Console()

GMAIL_ADDR = os.environ.get("GMAIL_ADDRESS", "").strip()
GMAIL_PASS = os.environ.get("GMAIL_APP_PASSWORD", "").strip()
try:
    SCAN_COUNT = int(os.environ.get("SCAN_COUNT", "50"))
except ValueError:
    console.print("[yellow]⚠️  SCAN_COUNT must be a whole number — defaulting to 50[/yellow]")
    SCAN_COUNT = 50
VIP_RAW    = os.environ.get("VIP_SENDERS", "")
VIP_LIST   = [v.strip().lower() for v in VIP_RAW.split(",") if v.strip()]
YOUR_NAME  = os.environ.get("YOUR_NAME", "").strip()
YOUR_ROLE  = os.environ.get("YOUR_ROLE", "").strip()

if not GMAIL_ADDR or not GMAIL_PASS:
    console.print(Panel(
        "[red]GMAIL_ADDRESS and GMAIL_APP_PASSWORD are both required.[/red]nn"
        "How to create an app password:n"
        "1. Go to [bold]myaccount.google.com/apppasswords[/bold]n"
        "2. Select Mail → Other (Custom name)n"
        "3. Copy the 16-character passwordn"
        "4. Set GMAIL_APP_PASSWORD to that value",
        title="[bold red]⚙️  Setup Required[/bold red]",
        border_style="red"
    ))
    raise SystemExit(1)

URGENT_KEYWORDS = [
    "urgent", "asap", "deadline", "immediately", "action required", "time sensitive",
    "overdue", "past due", "invoice", "payment due", "legal", "lawsuit", "critical",
    "emergency", "final notice", "expires", "expiring", "last chance",
]
REPLY_KEYWORDS = [
    "?", "question", "can you", "could you", "please", "request",
    "following up", "follow-up", "reminder", "let me know", "thoughts",
]
QUESTION_KW = ["?", "question", "can you", "could you", "help", "assist"]
NOISE_PATTERNS = [
    r"unsubscribe", r"newsletter", r"no-reply@", r"noreply@",
    r"marketing@", r"notifications?@", r"donotreply@",
    r"@.*.(mailchim|sendgrid|constantcontact|klaviyo)",
]
NOISE_SUBJECTS = [
    "sale", "% off", "deal", "offer", "promo", "subscribe", "newsletter",
    "weekly digest", "monthly update", "announcement",
]

def decode_str(s):
    if not s:
        return ""
    parts = decode_header(s)
    result = []
    for part, enc in parts:
        if isinstance(part, bytes):
            try:
                result.append(part.decode(enc or "utf-8", errors="replace"))
            except Exception:
                result.append(part.decode("utf-8", errors="replace"))
        else:
            result.append(str(part))
    return " ".join(result)

def is_noise(sender: str, subject: str) -> bool:
    text = (sender + " " + subject).lower()
    for pat in NOISE_PATTERNS:
        if re.search(pat, text):
            return True
    for kw in NOISE_SUBJECTS:
        if kw in subject.lower():
            return True
    return False

def score_email(subject: str, snippet: str, sender: str, age_hours: float, has_replied: bool) -> int:
    score = 50
    subj_low = subject.lower()
    snip_low = snippet.lower()
    # Urgency keywords
    for kw in URGENT_KEYWORDS:
        if kw in subj_low or kw in snip_low:
            score += 20
            break
    # Reply needed
    for kw in REPLY_KEYWORDS:
        if kw in subj_low or kw in snip_low:
            score += 10
            break
    # VIP sender
    sender_low = sender.lower()
    for vip in VIP_LIST:
        if vip in sender_low:
            score += 25
            break
    # Age penalty/boost
    if age_hours < 2:
        score += 5
    elif age_hours < 24:
        score += 0
    elif age_hours > 48:
        score -= 10
    elif age_hours > 120:
        score -= 20
    # Has been replied to
    if has_replied:
        score -= 15
    return max(0, min(score, 100))

# ── Connect to Gmail ──────────────────────────────────────────────────────────
console.print(Panel.fit(
    f"[bold cyan]🌈 Iris — Inbox Intelligence[/bold cyan]n"
    f"Scanning [yellow]{SCAN_COUNT}[/yellow] recent emails from [green]{GMAIL_ADDR}[/green]",
    border_style="cyan"
))

try:
    mail = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    mail.login(GMAIL_ADDR, GMAIL_PASS)
    mail.select("INBOX", readonly=True)
except imaplib.IMAP4.error as e:
    console.print(Panel(
        f"[red]IMAP login failed:[/red] {e}nn"
        "Checklist:n"
        "• Is GMAIL_ADDRESS correct? (full email, not just username)n"
        "• Is GMAIL_APP_PASSWORD a 16-char app password (not your Google password)?n"
        "• Did you enable IMAP in Gmail Settings → See all settings → Forwarding and POP/IMAP?",
        title="[bold red]Login Error[/bold red]",
        border_style="red"
    ))
    raise SystemExit(1)
except Exception as e:
    console.print(f"[red]Connection error: {e}[/red]")
    raise SystemExit(1)

_, msg_ids = mail.search(None, "ALL")
all_ids = msg_ids[0].split() if msg_ids and msg_ids[0] else []
if not all_ids:
    console.print(Panel("[yellow]Inbox is empty — nothing to triage.[/yellow]", border_style="yellow"))
    raise SystemExit(0)

recent_ids = all_ids[-SCAN_COUNT:] if len(all_ids) > SCAN_COUNT else all_ids
recent_ids = list(reversed(recent_ids))  # newest first

# ── Fetch and score emails ────────────────────────────────────────────────────
emails_data = []
now = datetime.now(timezone.utc)

console.print(f"[dim]Fetching {len(recent_ids)} emails…[/dim]")
for uid in recent_ids:
    try:
        _, raw = mail.fetch(uid, "(RFC822.HEADER FLAGS)")
        if not raw or not raw[0]:
            continue
        raw_header = raw[0][1] if isinstance(raw[0], tuple) else raw[0]
        msg = email.message_from_bytes(raw_header)
        subject = decode_str(msg.get("Subject", "(no subject)"))
        sender  = decode_str(msg.get("From", ""))
        date_str = msg.get("Date", "")
        flags_raw = raw[0][0] if isinstance(raw[0], tuple) else b""
        has_replied = b"\Answered" in flags_raw

        # Parse date
        try:
            sent_dt = parsedate_to_datetime(date_str)
            if sent_dt.tzinfo is None:
                sent_dt = sent_dt.replace(tzinfo=timezone.utc)
            age_hours = (now - sent_dt).total_seconds() / 3600
        except Exception:
            age_hours = 0

        # Fetch snippet
        body_snippet = ""
        try:
            _, raw_body = mail.fetch(uid, "(BODY[TEXT]<0.300>)")
            if raw_body and raw_body[0] and isinstance(raw_body[0], tuple):
                raw_b = raw_body[0][1]
                if raw_b:
                    body_snippet = raw_b.decode("utf-8", errors="replace").strip()[:200]
        except Exception:
            pass

        noise = is_noise(sender, subject)
        urgency = score_email(subject, body_snippet, sender, age_hours, has_replied)

        # Extract sender name and email
        sender_match = re.search(r'"?([^"<]+)"?s*<([^>]+)>', sender)
        if sender_match:
            sender_name  = sender_match.group(1).strip()
            sender_email = sender_match.group(2).strip()
        else:
            sender_name  = sender
            sender_email = sender

        emails_data.append({
            "uid":          uid,
            "subject":      subject,
            "sender":       sender_name,
            "sender_email": sender_email,
            "age_hours":    age_hours,
            "snippet":      body_snippet,
            "urgency":      urgency,
            "is_noise":     noise,
            "replied":      has_replied,
        })
    except Exception:
        continue

mail.logout()

# ── Sort and filter ───────────────────────────────────────────────────────────
actionable = [e for e in emails_data if not e["is_noise"]]
noise      = [e for e in emails_data if e["is_noise"]]
actionable.sort(key=lambda e: -e["urgency"])

# ── Display: Priority inbox ───────────────────────────────────────────────────
console.print()
priority_table = Table(
    title=f"📬 Priority Inbox — {len(actionable)} actionable emails",
    box=box.ROUNDED, border_style="cyan"
)
priority_table.add_column("Score",   style="red",    width=7,  justify="right")
priority_table.add_column("From",    style="yellow", width=22)
priority_table.add_column("Subject", style="white",  width=40)
priority_table.add_column("Age",     style="dim",    width=8)
priority_table.add_column("Status",  style="green",  width=10)

for e in actionable[:20]:
    age_str = (f"{int(e['age_hours'])}h" if e["age_hours"] < 48
               else f"{int(e['age_hours'] // 24)}d")
    status  = "✅ replied" if e["replied"] else ""
    score_colour = "red" if e["urgency"] >= 70 else "yellow" if e["urgency"] >= 50 else "dim"
    priority_table.add_row(
        f"[{score_colour}]{e['urgency']}[/{score_colour}]",
        e["sender"][:20],
        e["subject"][:38],
        age_str,
        status,
    )

console.print(priority_table)

# ── Display: Draft replies ────────────────────────────────────────────────────
sig = f"nn—n{YOUR_NAME or 'Best'}{', ' + YOUR_ROLE if YOUR_ROLE else ''}"
top5 = [e for e in actionable if not e["replied"]][:5]

console.print()
for e in top5:
    subj_low = e["subject"].lower()
    snip_low = e["snippet"].lower()
    greeting = f"Hi {e['sender'].split()[0]},"
    if any(k in subj_low or k in snip_low for k in ["urgent", "asap", "deadline", "overdue"]):
        body = "Thank you for flagging this — I'll look into it right away and get back to you shortly."
    elif any(k in subj_low or k in snip_low for k in QUESTION_KW):
        body = "Thanks for your message. To answer your question: [your answer here]nnLet me know if you need anything else."
    elif "re:" in subj_low or "fwd:" in subj_low:
        body = "Thanks for the follow-up. Here's where things stand: [brief update]nnHappy to jump on a call if that's easier."
    else:
        body = "Thanks for reaching out. I've reviewed your message and [your response here]."
    draft = f"{greeting}nn{body}{sig}"
    console.print(Panel(
        draft,
        title=f"[bold]📝 Draft: Re: {e['subject'][:45]}[/bold]  [dim](urgency: {e['urgency']})[/dim]",
        border_style="yellow"
    ))

# ── Display: Stats ────────────────────────────────────────────────────────────
console.print()
console.print(Panel(
    f"📊 [bold]Summary[/bold]nn"
    f"Scanned:    [yellow]{len(emails_data)}[/yellow] emailsn"
    f"Actionable: [cyan]{len(actionable)}[/cyan]  |  "
    f"Noise: [dim]{len(noise)}[/dim]  |  "
    f"Already replied: [green]{sum(1 for e in actionable if e['replied'])}[/green]n"
    f"High priority (70+): [red]{sum(1 for e in actionable if e['urgency'] >= 70)}[/red]",
    border_style="cyan"
))

# ── Save report ───────────────────────────────────────────────────────────────
date_str    = datetime.now().strftime("%Y-%m-%d")
report_file = f"inbox_report_{date_str}.md"
with open(report_file, "w", encoding="utf-8") as f:
    f.write(f"# 🌈 Iris — Inbox Report — {date_str}nn")
    f.write(f"**Scanned:** {len(emails_data)}  **Actionable:** {len(actionable)}  **Noise:** {len(noise)}nn")
    f.write("## Priority Emailsnn| Score | From | Subject | Age |n|-------|------|---------|-----|n")
    for e in actionable[:20]:
        age_str = f"{int(e['age_hours'])}h" if e["age_hours"] < 48 else f"{int(e['age_hours']//24)}d"
        f.write(f"| {e['urgency']} | {e['sender']} | {e['subject']} | {age_str} |n")
    f.write("n## Draft Repliesnn")
    for e in top5:
        subj_low = e["subject"].lower()
        snip_low = e["snippet"].lower()
        greeting = f"Hi {e['sender'].split()[0]},"
        if any(k in subj_low or k in snip_low for k in ["urgent", "asap", "deadline"]):
            body = "Thank you for flagging this — I'll look into it right away."
        elif any(k in subj_low or k in snip_low for k in QUESTION_KW):
            body = "Thanks for your message. To answer your question: [your answer here]"
        else:
            body = "Thanks for reaching out. [your response here]"
        f.write(f"### Re: {e['subject']}nn{FENCE}n{greeting}nn{body}{sig}n{FENCE}nn")

console.print(Panel(
    f"[green]✅ Done![/green]  Report saved to [cyan]{report_file}[/cyan]",
    border_style="green"
))

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
Skill 文件
  • SKILL.md
    • Iris — Inbox Intelligence
    • What you get
    • Setup (one-time, 2 minutes)
    • 🔒 Security
    • Step 1 — Install
    • ⚡ Upgrade to Iris Pro
    • Step 2 — Triage your inbox
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期