在 Python 中使用 PyObjC 和 ScriptingBridge 在 Messages 中发送消息

Sending a message in Messages with PyObjC and ScriptingBridge in Python

这可能是一个简单的问题,但我有点困惑,因为我没有在网上找到很多例子。

我已经能够使用 Javascript (Using this tutorial) 通过 Mac OS 中的消息发送消息,但我不知道该怎么做使用 Python 和 PyObjC。

使用 Javascript 我会做这样的事情:

var messages = Application('Messages');
var buddy = messages.services["E:%REPLACE_WITH_YOUR_IMESSAGE_EMAIL%"].buddies["%REPLACE_WITH_BUDDYS_EMAIL%"];
messages.send("JavaScript sent this message!", {to: buddy});

我不知道如何使用 Python 将 buddy 变量设置为相关对象。以下内容可以正常访问 Messages

from Foundation import *
from ScriptingBridge import *
Messages = SBApplication.applicationWithBundleIdentifier_("com.apple.iChat")

然后在 Python 我可以做这样的事情。

In [182]: s = Messages.services()
In [183]: [x.name() for x in s]
Out[183]: ['E:foo@icloud.com', 'Bonjour', 'SMS']

但我不确定如何在创建 Messages 对象后从这里跳转到实际让它使用 Messages.send_to_ 发送消息。

非常感谢您的帮助,非常感谢!

你可以这样做:

from ScriptingBridge import SBApplication

Messages = SBApplication.applicationWithBundleIdentifier_("com.apple.iChat")

# get the first budddy who's name is Chris Cummings
buddy_to_message = [b for b in Messages.buddies() if b.fullName() == "Chris Cummings"][0]

# send text to buddy
Messages.send_to_("sending this from python test", buddy_to_message)

我发现在尝试使用 pyobjc 中大量未记录的 ScriptingBridge 模块时真正有用的是搜索 class 上可用的方法,我试图在 repl 中访问

>>>[method for method in dir(Messages) if "bud" in method.lower()]
["buddies", "buddies"]  # found the buddies method
>>>[method for method in dir(Meessages.buddies()[0]) if "name" in method.lower()]
[ ... 'accessibilityParameterizedAttributeNames', 'className',
'elementWithCode_named_', 'entityName', 'firstName', 'fullName',
'fullName', 'lastName', 'name', 'name', 'scriptAccountLegacyName',
'valueWithName_inPropertyWithKey_']

# ... this one had a bunch of other junk but hopefully this illustrates the idea

关于目录的补充说明: 当然 dir() 也可以接受参数,你可以获得在对象上定义的方法列表,这些方法与 dir('name') 匹配的字符串但是 ObjectiveC class 名称几乎从不大写为我预料到了,所以我认为搜索所有小写字母很有用。