Skip to content

天楚锐齿

人工智能 云计算 大数据 物联网 IT 通信 嵌入式

天楚锐齿

  • 下载
  • 物联网
  • 云计算
  • 大数据
  • 人工智能
  • Linux&Android
  • 网络
  • 通信
  • 嵌入式
  • 杂七杂八

使用xmpp协议跟gtalk对话

2018-03-12

首先开通两个gtalk帐号,相互加为好友。如xxxxx@gmail.com和yyyyy@gmail.com。
然后安装xmpppy-0.5.0rc1以上版本的xmpp库。

用xxxxx@gmail.com登录gtalk,然后跟yyyyy@gmail.com对话。
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import  os, sys, string

import time
import codecs
import threading

import getpass
import xmpp

programName=”

class Xmpp_Msg_Class(threading.Thread):
def __init__(self, threadName, loginUser, loginPasswd, xmppServer, xmppDomain, xmppPort):
threading.Thread.__init__(self)
self.name = threadName

self.loginUser = loginUser
self.loginPasswd = loginPasswd
self.xmppServer = xmppServer
self.xmppDomain = xmppDomain
self.xmppPort = xmppPort

self.isQuit = False

self.xmppTo = ”
self.client = None
self.conn = None
self.connOK = False

def __del__(self):
time.sleep(1)   # some older servers will not send the message if you disconnect immediately after sending
if not self.client == None:
self.client.disconnect()

def quit(self):
self.isQuit = True

def run(self):
while True:
if self.isQuit:
break
if self.client == None:
if not self.ConnectToXmppServer():
print ‘ERROR: can not connect to XMPP server.’
self.client = None
time.sleep(5)
continue
if not self.client.isConnected():
if not self.client.reconnectAndReauth():
print ‘ERROR: can not connect to XMPP server.’
time.sleep(5)
continue
if self.client.Process(1) == None:
print ‘ERROR: lost connection!’
time.sleep(5)
time.sleep(0.1)

def ConnectToXmppServer(self):
print ‘Create Client: DOMAIN:%s, port:%u’ % (self.xmppDomain, 5222)
#self.client = xmpp.Client(self.xmppDomain, port=5222, debug=[‘always’])
self.client = xmpp.Client(self.xmppDomain, port=5222, debug=[])
print ‘Create Connect: SERVER:%s, port:%u’ % (self.xmppServer, self.xmppPort)
self.conn = self.client.connect((self.xmppServer, self.xmppPort), proxy=None, secure=None, use_srv=True)
if not self.conn:
print ‘ERROR: Could not connect to %s !’ % (self.xmppServer)
return False
print ‘INFO: Connected with ‘,self.conn
print ‘Create Auth: USER:%s, PASSWORD:%s’ % (self.loginUser.split(‘@’)[0], ‘******’)#self.loginPasswd)
auth=self.client.auth(self.loginUser.split(‘@’)[0], self.loginPasswd, resource=”, sasl=1)
if not auth:
print ‘ERROR: Could not authenticate with %s !’ % (self.xmppServer)
return False
print ‘INFO: Aauthenticated using ‘,auth
# …register some handlers (if you will register them before auth they will be thrown away)
print ‘Register Handle: presence/iq/message/disconnect’
self.client.RegisterHandler(‘presence’,self.presenceHandler)
self.client.RegisterHandler(‘iq’,self.iqHandler)
self.client.RegisterHandler(‘message’,self.messageHandler)
self.client.RegisterDisconnectHandler(self.disconnectHandler)
# …become available
print ‘INFO: Online’
self.client.sendInitPresence(requestRoster=0)   # you may need to uncomment this for old server
print “============> I’m online <=============”
self.connOK = True
return True

def presenceHandler(self, conn,presence_node):
“”” Handler for playing a sound when particular contact became online “””
for targetJID in self.xmppTo:
if presence_node.getFrom().bareMatch(targetJID):
print ‘USER: %s has login!’ % (targetJID)

def iqHandler(self, conn,iq_node):
“”” Handler for processing some “get” query from custom namespace”””
reply=iq_node.buildReply(‘result’)
# … put some content into reply node
self.conn.send(reply)
raise NodeProcessed  # This stanza is fully processed

def messageHandler(self, conn,mess_node):
print ‘Send message to <%s>, MSG: “%s”‘ % (str(mess_node.getFrom()), mess_node.getBody().encode(‘utf-8’))
id = self.client.send(xmpp.protocol.Message(str(mess_node.getFrom()), mess_node.getBody().encode(‘utf-8’)))
print ‘INFO: Sent message with id ‘,id

def disconnectHandler(self, conn,disconn_node):
print ‘INFO: Disconnect!’

def SendMsg(self, xmppTo, xmppMsg):
self.xmppTo = xmppTo

if not self.connOK:
print ‘ERROR: not connected to XMPP server.’
return

for tojid in self.xmppTo:
print ‘Send message to <%s>, MSG: “%s”‘ % (tojid, xmppMsg)
id = self.client.send(xmpp.protocol.Message(tojid, xmppMsg))
print ‘INFO: Sent message with id ‘,id
if self.client.Process(1) == None:
print ‘ERROR: lost connection!’

def OutputHelp():
print ‘Use XMPP to send messages to gtalk: ‘
print ‘Usage: ‘ + programName + ‘ ‘
print ‘Example: ‘ + programName + ‘ ‘
print ‘ ‘

if __name__ == ‘__main__’ :
programName = sys.argv[0]
if len(sys.argv) > 1:
OutputHelp()
sys.exit(0)

password = getpass.getpass(prompt=’Please input the password for “xxxxx@gmail.com”: ‘).strip()
if password == “”:
sys.exit(0)
xmpp_msg = Xmpp_Msg_Class(‘CHART’, ‘xxxxx@gmail.com’, password, ‘talk.google.com’, ‘gmail.com’, 443)
xmpp_msg.start()
time.sleep(5)
xmpp_msg.SendMsg([‘yyyyy@gmail.com’], ‘test测试1’)
while True:
input = raw_input(‘======>>>msg(“q” is quit)>>>: ‘).strip()
if input == ‘q’:
xmpp_msg.quit()
break
if input == ”:
continue
xmpp_msg.SendMsg([‘yyyyy@gmail.com’], input)
xmpp_msg.join()

sys.exit()

1,298次阅读

Post navigation

前一篇:

Linux组播测试工具及网络 RTT 延时测试工具

后一篇:

Hadoop性能模型(1)

发表回复 取消回复

要发表评论,您必须先登录。

个人介绍

需要么,有事情这里找联系方式:关于天楚锐齿

=== 美女同欣赏,好酒共品尝 ===

微信扫描二维码赞赏该文章:

扫描二维码分享该文章:

分类

  • Linux&Android (81)
  • Uncategorized (1)
  • 下载 (28)
  • 云计算 (38)
  • 人工智能 (9)
  • 大数据 (35)
  • 嵌入式 (34)
  • 杂七杂八 (35)
  • 物联网 (65)
  • 网络 (25)
  • 通信 (22)

归档

近期文章

  • 飞书机器人发送卡片interactive消息
  • Springboot JPA实现对数据库表统一的增删改查
  • WEB的内容安全策略CSP(Content-Security-Policy)
  • CSS利用@media和viewport实现响应式布局自动适配手机电脑等
  • VUE前端增加国际化支持

近期评论

  • linux爱好者 发表在《Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误》
  • maxshu 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • Ambition 发表在《使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序》
  • maxshu 发表在《Android9下用ethernet 的Tether模式来做路由器功能》

阅读量

  • 使用Android的HIDL+AIDL方式编写从HAL层到APP层的程序 - 23,810次阅读
  • 卸载深信服Ingress、SecurityDesktop客户端 - 18,519次阅读
  • 车机技术之车规级Linux-Automotive Grade Linux(AGL) - 10,570次阅读
  • linux下的unbound DNS服务器设置详解 - 9,323次阅读
  • 在Android9下用ndk编译vSomeIP和CommonAPI以及使用例子 - 9,136次阅读
  • linux的tee命令导致ssh客户端下的shell卡住不动 - 8,639次阅读
  • Linux策略路由及iptables mangle、ip rule、ip route关系及一种Network is unreachable错误 - 8,126次阅读
  • 车机技术之360°全景影像(环视)系统 - 8,088次阅读
  • 车机技术之Android Automotive - 7,940次阅读
  • Windows下安装QEMU并在qemu上安装ubuntu和debian - 7,840次阅读

其他操作

  • 注册
  • 登录
  • 条目 feed
  • 评论 feed
  • WordPress.org

联系方式

地址
深圳市科技园

时间
周一至周五:  9:00~12:00,14:00~18:00
周六和周日:10:00~12:00

标签

android AT命令 CAN centos docker Hadoop hdfs ip java kickstart linux mapreduce mini6410 modem nova OAuth openstack os python socket ssh uboot 内核 协议 安装 嵌入式 性能 报表 授权 操作系统 数据 数据库 月报 模型 汽车 深信服 源代码 统计 编译 脚本 虚拟机 调制解调器 车机 金融 鉴权
© 2025 天楚锐齿