苹果IM群发短信自动化的实现与应用!

84 阅读3分钟

苹果IM群发短信并没有官方公开的群发 API,最稳妥的落地路径是macOS Messages+AppleScript/Shortcuts,再用Python管理队列、去重、限速、审计和重试。

它适合已获得同意的客服通知、内部告警、预约确认,不适合冷名单营销;iMessage与SMS也不一样,非Apple设备通常要靠iPhone短信转发,稳定性会下降,下面按可运行链路拆开讲。

1、苹果IM群发的原理与边界

自动化只能“控制本机Messages发单条”,批量是外层循环,不是Apple官方群发接口,Apple没有开放iMessage群发API,可行方式是macOS登录Messages,授予终端或脚本“自动化”权限,用AppleScript发送,不要用私有API或模拟点击绕限制,频率高会触发风控,账号可能被限制。

-- send_one.applescript
on run argv
  set targetHandle to item 1 of argv
  set msgText to item 2 of argv
  tell application "Messages"
    set targetService to first service whose service type = iMessage
    set targetBuddy to buddy targetHandle of targetService
    send msgText to targetBuddy
  end tell
end run

调用方式:

osascript send_one.applescript "+86138xxxxxxxx" "您好,预约已确认。"

2、最小发送单元:AppleScript驱动Messages

把发送封装成单条函数,外层才能做队列、日志和重试,在Python里用subprocess调osascript,把号码和文本作为参数传入,避免拼接脚本导致转义错误,每次发送后等待8-20秒随机间隔。

import csv, subprocess, time, random, sqlite3, hashlib, datetime

DB = "im_sent.sqlite3"
SCRIPT = r'''
on run argv
  set targetHandle to item 1 of argv
  set msgText to item 2 of argv
  tell application "Messages"
    set targetService to first service whose service type = iMessage
    set targetBuddy to buddy targetHandle of targetService
    send msgText to targetBuddy
  end tell
end run
'''

def send_imessage(handle, text):
    r = subprocess.run(
        ["osascript", "-e", SCRIPT, "--", handle, text],
        capture_output=True, text=True, check=False
    )
    return r.returncode == 0, r.stderr.strip()

3、批量队列:Python 做去重、限速和重试

批量能力来自外层队列,关键是同一人同一内容只发一次,失败退避,成功留痕,用SQLite主键去重,发送前查同意表和黑名单,失败重试2次并指数退避,不要并发轰炸Messages,单进程串行更稳!

def init_db():
    con = sqlite3.connect(DB)
    con.execute("""
    create table if not exists sent(
      handle text, text_hash text, ts text, status text,
      primary key(handle, text_hash)
    )""")
    con.commit(); con.close()

def already_sent(handle, h):
    con = sqlite3.connect(DB)
    row = con.execute("select 1 from sent where handle=? and text_hash=?",
                      (handle, h)).fetchone()
    con.close()
    return row is not None

def mark(handle, h, ok, err=""):
    con = sqlite3.connect(DB)
    con.execute("insert or replace into sent values(?,?,?,?)",
        (handle, h, datetime.datetime.now().isoformat(),
         "ok" if ok else "fail:" + err[:120]))
    con.commit(); con.close()

def send_with_retry(handle, text, retries=2):
    for i in range(retries + 1):
        ok, err = send_imessage(handle, text)
        if ok:
            return True, ""
        time.sleep((2 ** i) + random.random())
    return False, err

def run_queue(csv_path, consents, blacklist):
    init_db()
    with open(csv_path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            handle = row["handle"].strip()
            text = row["text"].strip()
            if not handle or not text: continue
            if handle in blacklist or handle not in consents: continue
            h = hashlib.sha256((handle + text).encode()).hexdigest()
            if already_sent(handle, h): continue
            ok, err = send_with_retry(handle, text)
            mark(handle, h, ok, err)
            time.sleep(random.uniform(8, 20))

4、审计与隐私:只读查询chat.db

审计用只读查询,不要抓取聊天内容做二次营销,Messages的chat.db需要“完全磁盘访问权限”,只查发送时间、句柄、状态,且本地保存,生产环境建议只记录自己的发送日志,不碰对方回复正文。

sqlite3 ~/Library/Messages/chat.db <<'SQL'
.headers on
.mode column
select
  handle.id as buddy,
  datetime(message.date/1000000000 + 978307200, 'unixepoch', 'localtime') as sent_at,
  substr(message.text,1,40) as preview
from message
left join handle on message.handle_id = handle.ROWID
where message.is_from_me = 1
order by message.date desc
limit 20;
SQL

5、定时运行:launchd托管任务

macOS上用launchd,不要依赖cron的图形会话权限,把队列脚本做成plist,每5分钟跑一次,注意脚本要使用绝对路径,Python依赖要装在系统可访问环境,Messages必须已登录。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.example.im-sender</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/python3</string>
    <string>/Users/me/im_sender.py</string>
    <string>/Users/me/queue.csv</string>
  </array>
  <key>StartInterval</key><integer>300</integer>
  <key>RunAtLoad</key><true/>
</dict>
</plist>

6、合规落地:同意、退订、频控和日志

没有同意记录就不发,退订要落库,频控和日志决定这套系统能否长期用,发送前检查consent、blacklist、last_sent;每7天最多一次,内容带退订说明,遵守Apple条款、反垃圾邮件法规和个保法,技术只是执行层,合规才是边界。

def can_send(handle, consents, blacklist, last_sent, now):
    if handle in blacklist:
        return False, "blacklist"
    if handle not in consents:
        return False, "no_consent"
    if now - last_sent.get(handle, 0) < 7 * 86400:
        return False, "frequency"
    return True, ""

如果只是内部告警,优先用企业微信、飞书或Slack;苹果IM群发短信只在确实需要iMessage触达时用,把发送量压到最小,把同意、退订和日志做扎实,比追求“自动化群发”更重要!