You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅使用Twisted向XMPP服务器发送消息?

使用Twisted实现XMPP单条消息发送

以下是用Twisted实现仅发送XMPP消息的完整代码,无需处理回复或维持长连接:

from twisted.internet import reactor
from twisted.words.protocols.jabber.jid import JID
from twisted.words.protocols.jabber.client import XMPPAuthenticator, ClientFactory
from twisted.words.xish import domish

# 替换为你的配置信息
JABBER_ID = "user@server.com"
PASSWORD = "secret"
RECEIVER = "sender_id@conference.server.com"
MESSAGE_CONTENT = "Hello world!"

class SendMessageFactory(ClientFactory):
    def __init__(self, jid, password, receiver, message):
        self.authenticator = XMPPAuthenticator(jid, password)
        self.receiver = receiver
        self.message = message

    def buildProtocol(self, addr):
        proto = self.authenticator.buildProtocol(addr)
        # 监听认证成功事件,触发消息发送
        proto.addObserver("//event/auth/success", self.send_message)
        return proto

    def send_message(self, event):
        # 构造XMPP消息结构
        msg = domish.Element(("jabber:client", "message"))
        msg["to"] = self.receiver
        msg["type"] = "groupchat"  # 群聊用groupchat,单聊用chat
        body = msg.addElement("body")
        body.addContent(self.message)
        
        # 发送消息
        event.sender.send(msg)
        # 发送完成后停止事件循环
        reactor.stop()

    def clientConnectionFailed(self, connector, reason):
        print(f"连接失败: {reason.getErrorMessage()}")
        reactor.stop()

if __name__ == "__main__":
    jid = JID(JABBER_ID)
    factory = SendMessageFactory(jid, PASSWORD, RECEIVER, MESSAGE_CONTENT)
    # 连接到XMPP服务器默认端口5222
    reactor.connectTCP(jid.host, 5222, factory)
    reactor.run()

关键说明:

  • 用ClientFactory管理连接生命周期,XMPPAuthenticator处理账号认证逻辑。
  • 通过addObserver监听认证成功事件,确保消息在认证通过后发送。
  • 用domish.Element构造符合XMPP协议的消息节点,指定接收方、消息类型和内容。
  • 消息发送完成后立即停止Twisted的事件循环,因为只需要单次发送功能。
  • 实现clientConnectionFailed处理连接失败的情况,避免程序挂起。

内容的提问来源于stack exchange,提问作者bontchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:20:14