gtalk机器人

# -*- coding: utf-8 -*-
import xmpp
import time
import urllib
 
GET_MSG_PER = 30
GET_MSG_URL = 'http://***/api_gtalk_get'
SEND_MSG_URL = 'http://***/api_gtalk_send'
ADMIN_GID = '***@gmail.com'
 
SEND_ALL_MSG_TO_ADMIN = False
 
class Bot:
    """ Jabber Bot Base Class """
    JID = ''
    PASSWORD = ''
 
    client = None
    once = 0
 
    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(server=('talk.google.com',5223)) == '':
            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()
        content = msg.getBody() #.encode('utf-8')
        self.send(fromid, content)
        if( not content or not content.strip() ):
            return
 
        #open('msg.txt', 'ab+').write(fromid.encode('utf-8') + content.encode('utf-8') + '\r\n')
        #return
    
        u = urllib.urlopen(SEND_MSG_URL, urllib.urlencode({'gtalk':fromid.encode('utf-8'),'msg':content.encode('utf-8')}))
        c = u.read()
        u.close
        
        self.send(fromid, c)
 
        global SEND_ALL_MSG_TO_ADMIN
        if(fromid == ADMIN_GID ):
            if( content[0:2] == '/c') :
                SEND_ALL_MSG_TO_ADMIN = False
            elif( content[0:2] == '/o' ):
                SEND_ALL_MSG_TO_ADMIN = True
        if( SEND_ALL_MSG_TO_ADMIN  ) :
            self.send2admin(fromid + " " +content)
 
    def send2admin (self, message):
        self.send(ADMIN_GID, message)
 
    def readmsg (self, s) :
        if( self.once == s ) :
            return
        self.once = s
        print ' s ' , s
 
        u = urllib.urlopen(GET_MSG_URL)
        c = u.read()
        u.close()
        if( not c ) :
            return
 
        for line in c.split('<<line>>') :
            line = line.strip()
            if( not line ) :
                continue
            row = line.split(';')
            emails = row[0].split(',')
            for email in emails :
                email = email.strip()
                if not email or email.find('@') == -1 :
                    continue
                print email
                print ''.join(row[1:])
                self.send(email, ''.join(row[1:]) )
 
        #self.send(c[0].strip(), ''.join(c[1:]) )
        
if __name__ == '__main__':
    gb = Bot ('unotice@gmail.com', '******')
    gb.send2admin ('Bot  Started')
 
    # 开始运行
    while (gb.step()):
        s = int(time.strftime('%S'))
        if( s % GET_MSG_PER == 0 ):
            gb.readmsg(s)            
        pass

参考资料

python/gtalk机器人.txt · 最后更改: 2009/03/08 01:02 由 kenvin
到顶部
chimeric.de = chi`s home Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0 红麦软件 红麦软件