開起Python輸入以下程式碼,並修改所需的測試帳號,即可開始操控Gtalk
#Python語言: python gtalk機器人 # coding: utf-8 # 這是根據xmpp封裝的Jabber聊天機器人類, 可以通過繼承,重載部分函數來自定義功能. # Jabber ID(JID): 比如gamcat@gmail.com import xmpp class Bot: """ Jabber Bot Base Class """ JID = '' PASSWORD = '' client = None def __init__ (self, jid, password): self.JID = xmpp.JID(jid) self.PASSWORD = password self.login() def login (self): self.client = xmpp.Client(self.JID.getDomain(), debug=[]) if self.client.connect() == '': raise 'JabberBot not connected.' if self.client.auth(self.JID.getNode(), self.PASSWORD) == None: raise 'JabberBot authentication failed.' self.client.RegisterHandler('message', self.message_callback) self.client.RegisterHandler('presence', self.presence_callback) self.client.sendInitPresence() def message_callback (self, client, message): """ 默認消息回調(可通過繼承自定義) """ def presence_callback (self, client, message): """ 默認事件回調,包括下面幾個(可通過繼承自定義) """ type = message.getType() who = message.getFrom().getStripped() if type == 'subscribe': self.subscribe(who) elif type == 'unsubscribe': self.unsubscribe(who) elif type == 'subscribed': self.subscribed(who) elif type == 'unsubscribed': self.unsubscribed(who) elif type == 'available' or type == None: self.available(message) elif type == 'unavailable': self.unavailable(who) def subscribe (self, jid): """ 加好友 """ self.client.send(xmpp.Presence(to=jid, typ='subscribed')) self.client.send(xmpp.Presence(to=jid, typ='subscribe')) def unsubscribe (self, jid): """ 取消好友 """ self.client.send(xmpp.Presence(to=jid, typ='unsubscribe')) self.client.send(xmpp.Presence(to=jid, typ='unsubscribed')) def subscribed (self, jid): """ 已加 """ def unsubscribed (self, jid): """ 已退 """ def available (self, message): """ 上線 """ def unavailable (self, jid): """ 下線 """ def send (self, jid, message): """ 發消息給某人""" self.client.send(xmpp.protocol.Message(jid, message)) def step (self): """ 用在迴圈中 """ try: self.client.Process(1) except KeyboardInterrupt: # Ctrl+C停止 return False return True #=========================== # 測試 #=========================== class Bot(Bot): def message_callback (self, cl, msg): fromid = msg.getFrom().getStripped() cont = msg.getBody() self.send2admin(msg) def send2admin (self, message): self.send('admin@gmail.com', 'Test') if __name__ == '__main__': gb = Bot ('yourbot@gmail.com', '******') gb.send2admin ('Bot Started') # 開始運行 while (gb.step()): pass
程式碼來源 : Python Gtalk機器人
沒有留言:
張貼留言