本文整理汇总了Python中pyxmpp2.client.Client.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python Client.disconnect方法的具体用法?Python Client.disconnect怎么用?Python Client.disconnect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyxmpp2.client.Client
的用法示例。
在下文中一共展示了Client.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SmsRobotClient
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class SmsRobotClient(EventHandler, XMPPFeatureHandler):
def __init__(self, your_jid, your_pass, target_jid, messages):
self.target_jid = target_jid
self.messages = messages
self.connected = False
self.established = False
settings = XMPPSettings({
u"password": your_pass,
u"starttls": True,
u"tls_verify_peer": False,
})
self.client = Client(JID(your_jid), [self], settings)
self.client.connect()
def run(self):
while self.messages:
if self.connected and not self.established:
print("Connecting...")
self.client.stream.send(Message(to_jid = self.target_jid,
body = "?", stanza_type = 'chat'))
self.client.run(timeout = 2)
@event_handler(AuthorizedEvent)
def handle_authorized(self, event):
self.connected = True
@message_stanza_handler()
def handle_message(self, stanza):
if not self.established:
if '"help"' not in stanza.body:
return
self.established = True
if not self.messages:
self.client.disconnect()
return None
body = 'sms:%s:%s' % self.messages.pop()
print(body)
return Message(to_jid = self.target_jid,
body = body, stanza_type = 'chat')
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
return QUIT
示例2: SayChat
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class SayChat(EventHandler, XMPPFeatureHandler):
def __init__(self):
self.droid = sl4a.Android()
settings = XMPPSettings({"software_name": "Say Chat"})
settings["jid"] = self.droid.dialogGetInput("Google Talk Username").result
settings["password"] = self.droid.dialogGetInput("Google Talk Password").result
settings["server"] = "talk.google.com"
settings["starttls"] = True
self.client = Client(
JID(settings["jid"]),
[self, VersionProvider(settings)],
settings)
def connect(self):
self.client.connect()
self.client.run()
def disconnect(self):
self.client.disconnect()
self.client.run(timeout = 2)
@message_stanza_handler()
def handle_message(self, stanza):
self.droid.ttsSpeak(
"{!s} says {!s}".format(stanza.from_jid.as_unicode(),
stanza.body))
return ""
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
return QUIT
@event_handler()
def handle_all(self, event):
"""If it's not logged, it didn't happen."""
logging.info("-- {}".format(event))
def run(self):
try:
self.connect()
except KeyboardInterrupt:
self.disconnect()
示例3: VersionChecker
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class VersionChecker(EventHandler):
"""Version checker implementation."""
def __init__(self, my_jid, target_jid, settings):
self.client = Client(my_jid, [self], settings)
self.target_jid = target_jid
def run(self):
"""Request client connection and start the main loop."""
self.client.connect()
self.client.run()
def disconnect(self):
"""Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection."""
self.client.disconnect()
self.client.run(timeout = 2)
@event_handler(AuthorizedEvent)
def handle_authorized(self, event):
"""Send the initial presence after log-in."""
request_software_version(self.client, self.target_jid,
self.success, self.failure)
def success(self, version):
print("Name: {0}".format(version.name))
print("Version: {0}".format(version.version))
if version.os_name is not None:
print("Operating System: {0}".format(version.os_name))
else:
print("Operating System name not available")
self.client.disconnect()
def failure(self, stanza):
print("Version query failed")
if stanza and stanza.stanza_type == "error":
cond_name = stanza.error.condition_name
text = stanza.error.text
if text:
print("Error: {0} ({1})".format(cond_name, text))
else:
print("Error: {0}".format(cond_name))
self.client.disconnect()
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
"""Quit the main loop upon disconnection."""
return QUIT
示例4: ChatBot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class ChatBot(MessageMixin, UserMixin, EventHandler, XMPPFeatureHandler):
got_roster = False
message_queue = None
ignore = set()
def __init__(self, jid, settings, botsettings=None):
if 'software_name' not in settings:
settings['software_name'] = self.__class__.__name__
if 'software_version' not in settings:
settings['software_version'] = __version__
version_provider = VersionProvider(settings)
self.client = Client(jid, [self, version_provider], settings)
self.presence = defaultdict(dict)
self.subscribes = ExpiringDictionary(default_timeout=5)
self.invited = {}
self.avatar_hash = None
self.settings = botsettings
def run(self):
self.client.connect()
self.jid = self.client.jid.bare()
logger.info('self jid: %r', self.jid)
self.update_on_setstatus = set()
self.client.run()
def disconnect(self):
'''Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection.'''
self.client.disconnect()
while True:
try:
self.client.run(timeout = 2)
except pyxmpp2.exceptions.StreamParseError:
# we raise SystemExit to exit, expat says XML_ERROR_FINISHED
pass
else:
break
def handle_early_message(self):
self.got_roster = True
q = self.message_queue
if q:
self.now = datetime.datetime.utcnow()
for sender, stanza in q:
self.current_jid = sender
self._cached_jid = None
try:
timestamp = stanza.as_xml().find('{urn:xmpp:delay}delay').attrib['stamp']
except AttributeError:
timestamp = None
self.handle_message(stanza.body, timestamp)
self.message_queue = self.__class__.message_queue = None
@event_handler(RosterReceivedEvent)
def roster_received(self, stanze):
self.delayed_call(2, self.handle_early_message)
self.delayed_call(getattr(config, 'reconnect_timeout', 24 * 3600), self.signal_connect)
nick, avatar_type, avatar_file = (getattr(config, x, None) for x in ('nick', 'avatar_type', 'avatar_file'))
if nick or (avatar_type and avatar_file):
self.set_vcard(nick, (avatar_type, avatar_file))
return True
def signal_connect(self):
logging.info('Schedule to re-connecting...')
self.client.disconnect()
@message_stanza_handler()
def message_received(self, stanza):
if stanza.stanza_type != 'chat':
return True
if not stanza.body:
logging.info("%s message: %s", stanza.from_jid, stanza.serialize())
return True
sender = stanza.from_jid
body = stanza.body
self.current_jid = sender
self.now = datetime.datetime.utcnow()
logging.info('[%s] %s', sender, stanza.body)
if str(sender.bare()) in self.ignore:
logging.info('(The above message is ignored on purpose)')
return True
if not self.got_roster:
if not self.message_queue:
self.message_queue = []
self.message_queue.append((sender, stanza))
else:
self.handle_message(body)
logging.info('done with new message')
return True
def send_message(self, receiver, msg):
if isinstance(receiver, str):
receiver = JID(receiver)
m = Message(
stanza_type = 'chat',
#.........这里部分代码省略.........
示例5: transmissionRobot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class transmissionRobot(EventHandler, XMPPFeatureHandler, TimeoutHandler):
userlist={};
lastcycle={};
def __init__(self, my_jid, settings):
version_provider = VersionProvider(settings)
self.client = Client(my_jid, [self, version_provider], settings)
self.rpc=transmissionrpc.Client(TRANSURL,TRANSPORT,TRANSUSER,TRANSPASS)
for user in SUBSCRIBERS:
self.userlist[JID(user).local]=JID(user)
def run(self):
"""Request client connection and start the main loop."""
self.client.connect()
self.client.run()
def disconnect(self):
"""Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection."""
self.client.disconnect()
self.client.run(timeout = 2)
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
logging.info(u"{0} requested presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(),
stanza_type = "subscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
logging.info(u"{0!r} accepted our subscription request"
.format(stanza.from_jid))
return True
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
logging.info(u"{0} canceled presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(),
stanza_type = "unsubscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
logging.info(u"{0!r} acknowledged our subscrption cancelation"
.format(stanza.from_jid))
return True
@message_stanza_handler()
def handle_message(self, stanza):
messagebody='Robot connected.'
if stanza.body=="connect":
if not stanza.from_jid.local in self.userlist:
self.userlist[stanza.from_jid.local]=stanza.from_jid;
else:
messagebody="Already connected."
msg = Message(stanza_type = stanza.stanza_type,
from_jid = self.client.jid, to_jid = stanza.from_jid,
subject = None, body = messagebody,
thread = stanza.thread)
return msg
elif stanza.body=="disconnect":
messagebody="Robot disconnected."
try:
del self.userlist[stanza.from_jid.local];
except:
messagebody="Already disconnected"
msg = Message(stanza_type = stanza.stanza_type,
from_jid = self.client.jid, to_jid = stanza.from_jid,
subject = None, body = messagebody,
thread = stanza.thread)
return msg
if stanza.from_jid.local+'@'+stanza.from_jid.domain in SUBSCRIBERS:
try:
#print stanza.body
torrent=self.rpc.add_torrent(stanza.body,timeout=10)
except:
return True
messagebody="Torrent added: "+str(torrent)
msg = Message(stanza_type = stanza.stanza_type,
from_jid = self.client.jid, to_jid = stanza.from_jid,
subject = None, body = messagebody,
thread = stanza.thread)
return msg
return True
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
"""Quit the main loop upon disconnection."""
return QUIT
@event_handler()
def handle_all(self, event):
"""Log all events."""
logging.info(u"-- {0}".format(event))
@timeout_handler(3,True)
#.........这里部分代码省略.........
示例6: QXBot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class QXBot(EventHandler, XMPPFeatureHandler):
def __init__(self):
my_jid = JID(USER+'/Bot')
self.my_jid = my_jid
settings = XMPPSettings({
"software_name": "qxbot",
"software_version": __version__,
"software_os": "Linux",
"tls_verify_peer": False,
"starttls": True,
"ipv6":False,
"poll_interval": 10,
})
settings["password"] = PASSWORD
version_provider = VersionProvider(settings)
event_queue = settings["event_queue"]
self.webqq = WebQQ(QQ, event_queue)
self.connected = False
#self.mainloop = TornadoMainLoop(settings)
self.mainloop = EpollMainLoop(settings)
self.client = Client(my_jid, [self, version_provider],
settings, self.mainloop)
self.logger = get_logger()
self.msg_dispatch = MessageDispatch(self, self.webqq, BRIDGES)
self.xmpp_msg_queue = Queue.Queue()
def run(self, timeout = None):
self.client.connect()
self.client.run(timeout)
def disconnect(self):
self.client.disconnect()
while True:
try:
self.run(2)
except:
pass
else:
break
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
self.logger.info(u"{0} join us".format(stanza.from_jid))
return stanza.make_accept_response()
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
self.logger.info(u"{0!r} accepted our subscription request"
.format(stanza.from_jid))
return stanza.make_accept_response()
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
self.logger.info(u"{0} canceled presence subscription"
.format(stanza.from_jid))
return stanza.make_accept_response()
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
self.logger.info(u"{0!r} acknowledged our subscrption cancelation"
.format(stanza.from_jid))
@presence_stanza_handler(None)
def handle_presence_available(self, stanza):
self.logger.info(r"{0} has been online".format(stanza.from_jid))
@presence_stanza_handler("unavailable")
def handle_presence_unavailable(self, stanza):
self.logger.info(r"{0} has been offline".format(stanza.from_jid))
@message_stanza_handler()
def handle_message(self, stanza):
if self.webqq.connected:
self.msg_dispatch.dispatch_xmpp(stanza)
else:
self.xmpp_msg_queue.put(stanza)
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
return QUIT
@event_handler(ConnectedEvent)
def handle_connected(self, event):
pass
@event_handler(RosterReceivedEvent)
def handle_roster_received(self, event):
""" 此处代表xmpp已经连接
开始连接QQ, 先将检查是否需要验证码的handler加入到mainloop
"""
checkhandler = CheckHandler(self.webqq)
self.mainloop.add_handler(checkhandler)
self.connected = True
@event_handler(CheckedEvent)
def handle_webqq_checked(self, event):
""" 第一步已经完毕, 删除掉检查的handler, 将登录前handler加入mainloop"""
bloginhandler = BeforeLoginHandler(self.webqq, password = QQ_PWD)
self.mainloop.remove_handler(event.handler)
#.........这里部分代码省略.........
示例7: Talkbot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class Talkbot(DB_oper,EventHandler,XMPPFeatureHandler,Messages,Command):
def __init__(self,jid,settings):
self.client = Client(JID(jid),[self],settings)
def run_bot(self):
self.client.connect()
self.client.run()
def stop_bot(self):
self.client.disconnect()
@event_handler(DisconnectedEvent)
def handle_disconnect(self,event):
return QUIT
@event_handler()
def handle_all(self,event):
logging.info(u"--{0}".format(event))
@message_stanza_handler()
def handle_message(self,stanza):
if stanza.stanza_type!='chat':
return True
current_jid = stanza.from_jid
body = stanza.body
if body[0]=='-':
logging.info(u"handle command which is {0}".format(body))
command = body.split(' ')[0]
print 'in main command is %s' % (command)
self.dispatch_command(command,stanza)
logging.info(u"handle command which is {0} done".format(body))
else:
logging.info(u"handle common message which is {0}".format(body))
self.dispatch_message(stanza.body,current_jid.bare())
logging.info(u"handle common message whcih is {0} done".format(body))
return True
@presence_stanza_handler("subscribe")
def handle_subscribe(self,stanza):
logging.info(u"{0} request presence subscripiton ".format(stanza.from_jid))
sender = stanza.from_jid
bare_jid = sender.bare().as_string()
self.add_user(bare_jid)
presence = Presence(to_jid=stanza.from_jid.bare(),stanza_type="subscribe")
return [stanza.make_accept_response(),presence]
def get_online_users(self):
users = [x.jid for x in self.client.roster if x.subscription=='both']
print self.client.roster
return users
def send_message(self,receiver,msg):
if isinstance(receiver,str):
receiver=JID(receiver)
message = Message(
stanza_type='chat',
from_jid = self.client.jid,
to_jid = receiver,
body = msg,)
self.send(message)
def send(self,stanza):
self.client.stream.send(stanza)
def do_unsubscribe(self,jid,type = 'unsubscribe'):
jid = JID(jid)
presence = Presence(to_jid=jid,stanza_type=type)
self.send(presence)
def delete_from_roster(self,jid):
self.client.roster.delItem(jid)
示例8: Rodney
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class Rodney(EventHandler, XMPPFeatureHandler):
"""Personal Secretary for facebook chat."""
def __init__(self, my_jid, settings, myname, events, text):
version_provider = VersionProvider(settings)
self.client = Client(my_jid, [self, version_provider], settings)
self.myname = myname # first and last name of user
self.logs = {}
self.parser = ttp.Parser() # twitter text processing lib handler
self.events = events
self.do_text = text
self.last_msg = ""
def run(self):
"""Request client connection and start the main loop."""
self.client.connect()
self.client.run()
def disconnect(self):
"""Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection."""
self.client.disconnect()
self.client.run(timeout=2)
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
logging.info(u"{0} requested presence subscription".format(stanza.from_jid))
presence = Presence(to_jid=stanza.from_jid.bare(), stanza_type="subscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
logging.info(u"{0!r} accepted our subscription request".format(stanza.from_jid))
return True
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
logging.info(u"{0} canceled presence subscription".format(stanza.from_jid))
presence = Presence(to_jid=stanza.from_jid.bare(), stanza_type="unsubscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
logging.info(u"{0!r} acknowledged our subscrption cancelation".format(stanza.from_jid))
return True
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
endtime = int(time.time())
filename = "rodney.{0}.log".format(endtime)
f = open(filename, "w")
from pprint import PrettyPrinter
pp = PrettyPrinter(depth=10, stream=f)
pp.pprint(self.logs)
print "My transcript has been written to {0}".format(filename)
"""Quit the main loop upon disconnection."""
return QUIT
@event_handler()
def handle_all(self, event):
"""Log all events."""
logging.info(u"-- {0}".format(event))
@event_handler(RosterReceivedEvent)
def handle_roster_received(self, event):
self.roster_items = self.client.roster.items()
print type(self.roster_items)
print "Roster received!"
@message_stanza_handler()
def handle_message(self, stanza):
""" Does message dispatching:
1) Checks when you're free on calendar
2) Sends you a text
3) Playful responses
"""
if stanza.body is None:
print stanza
elif stanza.body == self.last_msg:
print "bad"
return
else:
self.last_msg = stanza.body
parsed = self.parser.parse(stanza.body)
sender = (i for i in self.roster_items if i.jid == stanza.from_jid).next()
if sender.name not in self.logs.keys():
self.logs[sender.name] = []
if sender == None:
print "no name found, making it fuzz"
name = "fuzz"
else:
name = sender.name
print "{0} sent the message: {1}".format(name, stanza.body)
inmsg = stanza.body.lower()
if len(self.logs[name]) == 0 or "help" in parsed.tags:
res = " ".join(
#.........这里部分代码省略.........
示例9: XMPPBot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class XMPPBot(EventHandler, XMPPFeatureHandler):
autoReconnect = False
def __init__(self, my_jid, settings, autoReconnect=None, main_loop=None):
self.jid = my_jid
self.settings = settings
if autoReconnect is not None:
self.autoReconnect = autoReconnect
self.do_quit = False
self.main_loop = main_loop
def newclient(self):
version_provider = VersionProvider(self.settings)
self.client = Client(
self.jid, [self, version_provider], self.settings,
main_loop=self.main_loop,
)
def start(self):
while not self.do_quit:
logging.info('XMPP connecting...')
self.connect()
self.run()
if not self.autoReconnect:
self.do_quit = True
def connect(self):
self.newclient()
self.client.connect()
def run(self):
self.client.run()
def disconnect(self):
self.do_quit = True
self.client.disconnect()
try:
self.client.run(timeout=2)
except RuntimeError: # IOLoop is already running
pass
@property
def roster(self):
return self.client.roster
@message_stanza_handler()
def handle_message(self, stanza):
if stanza.stanza_type and stanza.stanza_type.endswith('chat') and stanza.body:
logging.info("%s said: %s", stanza.from_jid, stanza.body)
self.last_chat_message = stanza
else:
logging.info("%s message: %s", stanza.from_jid, stanza.serialize())
return True
def send_message(self, receiver, msg):
m = Message(
stanza_type = 'chat',
from_jid = self.client.jid,
to_jid = receiver,
body = msg,
)
self.send(m)
def send(self, stanza):
self.client.stream.send(stanza)
def delayed_call(self, seconds, func, *args, **kwargs):
self.client.main_loop.delayed_call(seconds, partial(func, *args, **kwargs))
def get_vcard(self, jid, callback):
'''callback is used as both result handler and error handler'''
q = Iq(
to_jid = jid.bare(),
stanza_type = 'get'
)
vc = ET.Element("{vcard-temp}vCard")
q.add_payload(vc)
self.stanza_processor.set_response_handlers(q, callback, callback)
self.send(q)
def update_roster(self, jid, name=NO_CHANGE, groups=NO_CHANGE):
self.client.roster_client.update_item(jid, name, groups)
@presence_stanza_handler()
def handle_presence_available(self, stanza):
logging.info('%s[%s]', stanza.from_jid, stanza.show or 'available')
return True
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
if self.do_quit:
return QUIT
else:
logging.warn('XMPP disconnected. Reconnecting...')
# We can't restart here because the stack will overflow
return True
@event_handler()
def handle_all(self, event):
"""Log all events."""
#.........这里部分代码省略.........
示例10: BotChat
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class BotChat(EventHandler, XMPPFeatureHandler):
trytimes = 0
def __init__(self):
my_jid = JID(USER+'/Bot')
self.my_jid = my_jid
settings = XMPPSettings({
"software_name": "Clubot",
"software_version": __version__,
"software_os": "Linux",
"tls_verify_peer": False,
"starttls": True,
"ipv6":False,
"poll_interval": 10,
})
settings["password"] = PASSWORD
version_provider = VersionProvider(settings)
self.connected = False
mainloop = TornadoMainLoop(settings)
self.client = Client(my_jid, [self, version_provider], settings, mainloop)
#self.client = Client(my_jid, [self, version_provider], settings)
self.logger = get_logger()
self.trytimes = 0
self.sended = []
Logics.empty_status()
def run(self, timeout = None):
self.client.connect()
self.client.run(timeout)
def disconnect(self):
self.client.disconnect()
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
self.logger.info(u"{0} join us".format(stanza.from_jid))
frm = stanza.from_jid
presence = Presence(to_jid = frm, stanza_type = "subscribe")
Logics.add(frm, None, stanza.show)
r =[stanza.make_accept_response(), presence]
if frm not in self.sended:
self.message_bus.send_sys_msg(stanza, new_member(frm))
self.message_bus.send_back_msg(stanza, welcome(frm))
self.sended.append(frm)
return r
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
self.logger.info(u"{0!r} accepted our subscription request"
.format(stanza.from_jid))
frm = stanza.from_jid
presence = Presence(to_jid = frm, stanza_type = "subscribe")
Logics.add(frm, None, stanza.show)
r =[presence]
r =[stanza.make_accept_response(), presence]
if frm not in self.sended:
self.message_bus.send_sys_msg(stanza, new_member(frm))
self.message_bus.send_back_msg(stanza, welcome(frm))
self.sended.append(frm)
return r
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
self.logger.info(u"{0} canceled presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(),
stanza_type = "unsubscribe")
nick = Logics.get_one(stanza.from_jid).nick
self.message_bus.send_sys_msg(stanza, u'{0} 离开群'.format(nick))
Logics.drop(stanza.from_jid.bare())
r =[stanza.make_accept_response(), presence]
return r
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
self.logger.info(u"{0!r} acknowledged our subscrption cancelation"
.format(stanza.from_jid))
Logics.drop(stanza.from_jid.bare())
return True
@presence_stanza_handler(None)
def handle_presence_available(self, stanza):
self.logger.info(r"{0} has been online".format(stanza.from_jid))
if stanza.from_jid.bare().as_string() != USER:
Logics.set_online(stanza.from_jid, stanza.show)
self.message_bus.send_offline_message(stanza)
@presence_stanza_handler("unavailable")
def handle_presence_unavailable(self, stanza):
self.logger.info(r"{0} has been offline".format(stanza.from_jid))
frm = stanza.from_jid
if frm.bare().as_string() == USER:
self.logger.info('bot go to offline')
self.disconnect()
Logics.set_offline(frm)
@message_stanza_handler()
def handle_message(self, stanza):
body = stanza.body
frm = stanza.from_jid.bare().as_string()
#.........这里部分代码省略.........
示例11: Bot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class Bot(EventHandler, XMPPFeatureHandler):
def __init__(self, my_jid, settings):
version_provider = VersionProvider(settings)
self.main_loop = SelectMainLoop(settings)
#self.main_loop = ThreadPool(settings)
#self.main_loop.start(daemon=True)
self.client = Client(my_jid, [self, version_provider], settings, main_loop=self.main_loop)
#self.client = Client(my_jid, [self, version_provider], settings)
def run(self):
"""Request client connection and start the main loop."""
self.client.connect()
self.client.run()
def disconnect(self):
"""Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection."""
self.client.disconnect()
self.client.run(timeout = 2)
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
logging.info(u"{0} requested presence subscription".format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(), stanza_type = "subscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
logging.info(u"{0!r} accepted our subscription request".format(stanza.from_jid))
return True
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
logging.info(u"{0} canceled presence subscription".format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(), stanza_type = "unsubscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
logging.info(u"{0!r} acknowledged our subscrption cancelation".format(stanza.from_jid))
return True
# @message_stanza_handler()
# def handle_message(self, stanza):
# """Echo every non-error ``<message/>`` stanza.
# Add "Re: " to subject, if any.
# """
# if stanza.subject:
# subject = u"Re: " + stanza.subject
# else:
# subject = None
# if stanza.body is None:
# txt = None
# else:
# txt = stanza.body+'!'
# msg = Message(stanza_type = stanza.stanza_type,
# from_jid = stanza.to_jid, to_jid = stanza.from_jid,
# subject = subject, body = txt,
# thread = stanza.thread)
# return msg
@message_stanza_handler()
def handle_message(self, stanza):
if stanza.stanza_type == 'chat' and not hasattr(stanza, 'processed'):
#print stanza
stanza.processed = True
to_jid = stanza.to_jid.as_unicode()
from_jid = stanza.from_jid.as_unicode()
im_tcp_tunneler.handle_message(from_jid, to_jid, stanza.body)
return True
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
"""Quit the main loop upon disconnection."""
return QUIT
@event_handler()
def handle_all(self, event):
"""Log all events."""
logging.info(u"-- {0}".format(event))
示例12: EchoBot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class EchoBot(EventHandler, XMPPFeatureHandler):
"""Echo Bot implementation."""
def __init__(self, my_jid, settings):
version_provider = VersionProvider(settings)
self.client = Client(my_jid, [self, version_provider], settings)
def run(self):
"""Request client connection and start the main loop."""
self.client.connect()
self.client.run()
def disconnect(self):
"""Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection."""
self.client.disconnect()
self.client.run(timeout = 2)
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
logging.info(u"{0} requested presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(),
stanza_type = "subscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
logging.info(u"{0!r} accepted our subscription request"
.format(stanza.from_jid))
return True
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
logging.info(u"{0} canceled presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid = stanza.from_jid.bare(),
stanza_type = "unsubscribe")
return [stanza.make_accept_response(), presence]
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
logging.info(u"{0!r} acknowledged our subscrption cancelation"
.format(stanza.from_jid))
return True
@message_stanza_handler()
def handle_message(self, stanza):
"""Echo every non-error ``<message/>`` stanza.
Add "Re: " to subject, if any.
"""
if stanza.subject:
subject = u"Re: " + stanza.subject
else:
subject = None
msg = Message(stanza_type = stanza.stanza_type,
from_jid = stanza.to_jid, to_jid = stanza.from_jid,
subject = subject, body = stanza.body,
thread = stanza.thread)
print stanza
print msg
return msg
@event_handler(DisconnectedEvent)
def handle_disconnected(self, event):
"""Quit the main loop upon disconnection."""
return QUIT
@event_handler()
def handle_all(self, event):
"""Log all events."""
logging.info(u"-- {0}".format(event))
示例13: MagpieClient
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class MagpieClient(EventHandler, XMPPFeatureHandler):
""" 启动并分别连接登录 XMPP 和 WebQQ
"""
def __init__(self, QQ, QQ_PWD, xmpp_account, xmpp_pwd, control_account,
debug=True, command=None):
self.input_queue = InputQueue(self.send_control_msg)
self.qq = QQClient(QQ, QQ_PWD, debug)
self.qq.set_control_msg(self.send_control_msg, self)
self.command = command or Command(self, self.qq)
self.jid = JID(xmpp_account + '/Bridge')
self.control_account = control_account
settings = XMPPSettings(
{"software_name": "Magpie",
"software_version": ".".join(str(x) for x in __version__),
"software_os": "Linux",
"tls_verify_peer": False,
"starttls": True,
"ipv6": False,
"password": xmpp_pwd,
"poll_interval": 10})
version_provider = VersionProvider(settings)
mainloop = TornadoMainLoop(settings)
self.client = Client(self.jid, [self, version_provider],
settings, mainloop)
def run(self, timeout=None):
self.client.connect()
self.client.run()
def disconnect(self):
self.client.disconnect()
@presence_stanza_handler("subscribe")
def handle_presence_subscribe(self, stanza):
logger.info(u"{0} join us".format(stanza.from_jid))
frm = stanza.from_jid
presence = Presence(to_jid=frm, stanza_type="subscribe")
r = [stanza.make_accept_response(), presence]
return r
@presence_stanza_handler("subscribed")
def handle_presence_subscribed(self, stanza):
logger.info(u"{0!r} accepted our subscription request"
.format(stanza.from_jid))
frm = stanza.from_jid
presence = Presence(to_jid=frm, stanza_type="subscribe")
r = [stanza.make_accept_response(), presence]
return r
@presence_stanza_handler("unsubscribe")
def handle_presence_unsubscribe(self, stanza):
logger.info(u"{0} canceled presence subscription"
.format(stanza.from_jid))
presence = Presence(to_jid=stanza.from_jid.bare(),
stanza_type="unsubscribe")
r = [stanza.make_accept_response(), presence]
return r
def make_message(self, to, typ, body):
""" 构造消息
`to` - 接收人 JID
`typ` - 消息类型
`body` - 消息主体
"""
if typ not in ['normal', 'chat', 'groupchat', 'headline']:
typ = 'chat'
m = Message(from_jid=self.jid, to_jid=to, stanza_type=typ, body=body)
return m
def send_control_msg(self, msg):
logger.info(u"Send message {0} to {1}"
.format(msg, self.control_account))
m = self.make_message(JID(self.control_account), "chat", msg)
self.stream.send(m)
def send_status(self, statustext):
to_jid = JID(self.control_account)
p = Presence(status=statustext, to_jid=to_jid)
self.stream.send(p)
@presence_stanza_handler("unsubscribed")
def handle_presence_unsubscribed(self, stanza):
logger.info(u"{0!r} acknowledged our subscrption cancelation"
.format(stanza.from_jid))
return True
# @presence_stanza_handler(None)
# def handle_presence_available(self, stanza):
# logger.info(r"{0} has been online".format(stanza.from_jid))
# @presence_stanza_handler("unavailable")
# def handle_presence_unavailable(self, stanza):
# logger.info(r"{0} has been offline".format(stanza.from_jid))
@message_stanza_handler()
def handle_message(self, stanza):
#.........这里部分代码省略.........
示例14: ChatBot
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class ChatBot(MessageMixin, UserMixin, EventHandler, XMPPFeatureHandler):
got_roster = False
message_queue = None
def __init__(self, jid, settings):
if 'software_name' not in settings:
settings['software_name'] = self.__class__.__name__
if 'software_version' not in settings:
settings['software_version'] = __version__
version_provider = VersionProvider(settings)
self.client = Client(jid, [self, version_provider], settings)
self.presence = defaultdict(dict)
self.subscribes = ExpiringDictionary(default_timeout=5)
self.invited = {}
def run(self):
self.client.connect()
self.jid = self.client.jid.bare()
logger.info('self jid: %r', self.jid)
self.update_on_setstatus = set()
self.client.run()
def disconnect(self):
'''Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection.'''
self.client.disconnect()
while True:
try:
self.client.run(timeout = 2)
except pyxmpp2.exceptions.StreamParseError:
# we raise SystemExit to exit, expat says XML_ERROR_FINISHED
pass
else:
break
def handle_early_message(self):
self.got_roster = True
q = self.message_queue
if q:
self.now = datetime.datetime.utcnow()
for sender, stanza in q:
self.current_jid = sender
self._cached_jid = None
try:
timestamp = stanza.as_xml().find('{urn:xmpp:delay}delay').attrib['stamp']
except AttributeError:
timestamp = None
self.handle_message(stanza.body, timestamp)
self.message_queue = None
@event_handler(RosterReceivedEvent)
def roster_received(self, stanze):
self.delayed_call(2, self.handle_early_message)
return True
@message_stanza_handler()
def message_received(self, stanza):
if stanza.body is None:
# She's typing
return True
sender = stanza.from_jid
body = stanza.body
self.current_jid = sender
self.now = datetime.datetime.utcnow()
logging.info('[%s] %s', sender, stanza.body)
if not self.got_roster:
if not self.message_queue:
self.message_queue = []
self.message_queue.append((sender, stanza))
else:
self.handle_message(body)
logging.info('done with new message')
return True
def send_message(self, receiver, msg):
if isinstance(receiver, str):
receiver = JID(receiver)
m = Message(
stanza_type = 'chat',
from_jid = self.jid,
to_jid = receiver,
body = msg,
)
self.send(m)
def reply(self, msg):
self.send_message(self.current_jid, msg)
def send(self, stanza):
self.client.stream.send(stanza)
def delayed_call(self, seconds, func, *args, **kwargs):
self.client.main_loop.delayed_call(seconds, partial(func, *args, **kwargs))
@event_handler(DisconnectedEvent)
#.........这里部分代码省略.........
示例15: XMPPClient
# 需要导入模块: from pyxmpp2.client import Client [as 别名]
# 或者: from pyxmpp2.client.Client import disconnect [as 别名]
class XMPPClient(EventHandler, XMPPFeatureHandler):
"""
xmpp 客户端
"""
def __init__(self):
self.subject_to_fun_dic = {}
self.xmpp_client = None
self.is_auth = False
self.protocol = PT_XMPP
self.jid_bare_str = None
def init(self, jid, password, c2s_port=5222):
"""
初始化
:param jid: jid
:param password: 密码
:return:
"""
self.JID = jid if isinstance(jid, JID) else JID(jid)
self.jid_bare_str = self.JID.bare().as_string()
self.password = password
self.settings = XMPPSettings({u"password": password,
u"starttls": True,
u"tls_verify_peer": False,
u"c2s_port":c2s_port})
if c2s_port != 5222:
logger.warn("XMPPClient::init c2s_port is :%s!!!!!" % c2s_port)
@gevent_adaptor(use_join_result=False)
def start(self):
"""
服务开始
:return:
"""
logger.warn("XMPPClient::start listen on %s:%s:%s" % (self.protocol, self.JID, self.password))
self.xmpp_client = Client(self.JID, [self], self.settings)
self.xmpp_client.connect()
self.xmpp_client.run()
self.is_auth = False
def stop(self):
"""
Request disconnection and let the main loop run for a 2 more
seconds for graceful disconnection.
"""
logger.warn("XMPPClient::stop listen on %s:%s:%s" % (self.protocol, self.JID, self.password))
assert self.xmpp_client
self.xmpp_client.disconnect()
self.xmpp_client.run(timeout=2)
self.is_auth = False
def restart(self):
"""
服务重启
:return:
"""
logger.warn("XMPPClient::restart listen on %s:%s:%s" % (self.protocol, self.JID, self.password))
self.stop()
self.start()
@xmpp_send_adaptor()
def _send(self, tgt_jid, subject, body):
"""
发送消息
:param tgt_jid:目的jid
:param subject: 主题
:param body: 文本
:return:
"""
if not self.xmpp_client.stream:
self.restart()
self.wait_for_auth()
tgt_jid = tgt_jid if isinstance(tgt_jid, JID) else JID(tgt_jid)
msg = Message(to_jid=tgt_jid, body=body, subject=subject,stanza_type="normal")
# _send与send的区别,send的锁有点奇怪,有时候会卡主,暂时不用锁
# def send(self, stanza):
# """Write stanza to the stream.
#
# :Parameters:
# - `stanza`: XMPP stanza to send.
# :Types:
# - `stanza`: `pyxmpp2.stanza.Stanza`
# """
# with self.lock:
# return self._send(stanza)
self.xmpp_client.stream._send(msg)
logger.info("XMPPClient::_send, src_jid:%s ,src_pass:%s, des_jid:%s, subject:%s, body:%s" %\
(self.JID,self.password, tgt_jid, subject, body))
@gevent_adaptor()
def send_async(self, sto_jid, ssubject, sbody):
"""
协程非阻塞发送
:param sto_jid:
:param ssubject:
:param sbody:
:return:
"""
#.........这里部分代码省略.........