Browse Source

修改log函数

liuyuqi-dellpc 8 years ago
parent
commit
789054c510
4 changed files with 70 additions and 62 deletions
  1. 2 0
      .gitignore
  2. 8 6
      bot.py
  3. 0 0
      conf/conf.ini.bak
  4. 60 56
      wxbot.py

+ 2 - 0
.gitignore

@@ -70,3 +70,5 @@ qr.png
 *.ini
 *.un~
 /temp/wxqr.png
+/temp
+/conf

+ 8 - 6
bot.py

@@ -4,7 +4,8 @@
 from wxbot import *
 import ConfigParser
 import json
-
+import logging
+import logging.config
 
 class TulingWXBot(WXBot):
     def __init__(self):
@@ -15,11 +16,11 @@ class TulingWXBot(WXBot):
 
         try:
             cf = ConfigParser.ConfigParser()
-            cf.read('conf.ini')
+            cf.read('conf/conf.ini')
             self.tuling_key = cf.get('main', 'key')
         except Exception:
             pass
-        print 'tuling_key:', self.tuling_key
+        logging.info('tuling_key:'+self.tuling_key)
 # 自动回复函数self:发送方用户id, uid, msg
     def tuling_auto_reply(self, uid, msg):
         if self.tuling_key:
@@ -39,8 +40,7 @@ class TulingWXBot(WXBot):
                         k['article'] + "\t" + k['detailurl'] + "\n"
             else:
                 result = respond['text'].replace('<br>', '  ')
-
-            print '    ROBOT:', result
+            logging.info('    ROBOT:'+ result)
             return result
         else:
             return u"知道啦,我是天问机器人,主人马上就来!"
@@ -96,13 +96,15 @@ class TulingWXBot(WXBot):
         else:
             src_name = msg['user']['name']
             reply = 'to ' + src_name + ': '
-            reply += u"对不起,只认字,其他杂七杂八的我都不认识,,,Ծ‸Ծ,,"
+            reply += u"主人马上就来!"
             self.send_msg_by_uid(reply, msg['user']['id'])
 
 '''
 主函数,执行TulingWXBot类里面的run方法
 '''
 def main():
+    logging.config.fileConfig("conf/logger.conf")
+    logger=logging.getLogger("example01")
     bot = TulingWXBot()
     bot.DEBUG = True
     bot.conf['qr'] = 'png'

+ 0 - 0
conf.ini.bak → conf/conf.ini.bak


+ 60 - 56
wxbot.py

@@ -17,6 +17,8 @@ import random
 from traceback import format_exc
 from requests.exceptions import ConnectionError, ReadTimeout
 import HTMLParser
+import logging
+import logging.config
 
 UNKONWN = 'unkonwn'
 SUCCESS = '200'
@@ -54,7 +56,7 @@ class SafeSession(requests.Session):
                                                         timeout,
                                                         allow_redirects, proxies, hooks, stream, verify, cert, json)
             except Exception as e:
-                print e.message, traceback.format_exc()
+                logging.info(e.message, traceback.format_exc())
                 continue
 
         #重试3次以后再加一次,抛出异常
@@ -118,6 +120,8 @@ class WXBot:
         self.encry_chat_room_id_list = []  # 存储群聊的EncryChatRoomId,获取群内成员头像时需要用到
 
         self.file_index = 0
+        logging.config.fileConfig("conf/logger.conf")
+        logger = logging.getLogger("example01")
 
     @staticmethod
     def to_unicode(string, encoding='utf-8'):
@@ -220,7 +224,7 @@ class WXBot:
             self.cursor += self.batch_count
             cur_batch = map(map_username_batch, cur_batch)
             user_info_list += self.batch_get_contact(cur_batch)
-            print "[INFO] Get batch contacts"
+            logging.info("[INFO] Get batch contacts")
 
         self.member_list = user_info_list
         special_users = ['newsapp', 'filehelper', 'weibo', 'qqmail',
@@ -282,8 +286,8 @@ class WXBot:
                 f.write(json.dumps(self.group_members))
             with open(os.path.join(self.temp_pwd,'account_info.json'), 'w') as f:
                 f.write(json.dumps(self.account_info))
-        print '[INFO] Get %d contacts' % len(self.contact_list)
-        print '[INFO] Start to process messages .'
+        logging.info('[INFO] Get %d contacts' % len(self.contact_list))
+        logging.info('[INFO] Start to process messages .')
         return True
 
 
@@ -536,7 +540,7 @@ class WXBot:
                 msg_content['data'] = pos
                 msg_content['detail'] = data
                 if self.DEBUG:
-                    print '    %s[Location] %s ' % (msg_prefix, pos)
+                    logging.info('    %s[Location] %s ' % (msg_prefix, pos))
             else:
                 msg_content['type'] = 0
                 if msg_type_id == 3 or (msg_type_id == 1 and msg['ToUserName'][:2] == '@@'):  # Group text message
@@ -551,28 +555,28 @@ class WXBot:
                     msg_content['data'] = content
                 if self.DEBUG:
                     try:
-                        print '    %s[Text] %s' % (msg_prefix, msg_content['data'])
+                        logging.info('    %s[Text] %s' % (msg_prefix, msg_content['data']))
                     except UnicodeEncodeError:
-                        print '    %s[Text] (illegal text).' % msg_prefix
+                        logging.info('    %s[Text] (illegal text).' % msg_prefix)
         elif mtype == 3:
             msg_content['type'] = 3
             msg_content['data'] = self.get_msg_img_url(msg_id)
             msg_content['img'] = self.session.get(msg_content['data']).content.encode('hex')
             if self.DEBUG:
                 image = self.get_msg_img(msg_id)
-                print '    %s[Image] %s' % (msg_prefix, image)
+                logging.info('    %s[Image] %s' % (msg_prefix, image))
         elif mtype == 34:
             msg_content['type'] = 4
             msg_content['data'] = self.get_voice_url(msg_id)
             msg_content['voice'] = self.session.get(msg_content['data']).content.encode('hex')
             if self.DEBUG:
                 voice = self.get_voice(msg_id)
-                print '    %s[Voice] %s' % (msg_prefix, voice)
+                logging.info('    %s[Voice] %s' % (msg_prefix, voice))
         elif mtype == 37:
             msg_content['type'] = 37
             msg_content['data'] = msg['RecommendInfo']
             if self.DEBUG:
-                print '    %s[useradd] %s' % (msg_prefix,msg['RecommendInfo']['NickName'])
+                logging.info('    %s[useradd] %s' % (msg_prefix,msg['RecommendInfo']['NickName']))
         elif mtype == 42:
             msg_content['type'] = 5
             info = msg['RecommendInfo']
@@ -582,18 +586,19 @@ class WXBot:
                                    'city': info['City'],
                                    'gender': ['unknown', 'male', 'female'][info['Sex']]}
             if self.DEBUG:
-                print '    %s[Recommend]' % msg_prefix
-                print '    -----------------------------'
-                print '    | NickName: %s' % info['NickName']
-                print '    | Alias: %s' % info['Alias']
-                print '    | Local: %s %s' % (info['Province'], info['City'])
-                print '    | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]
-                print '    -----------------------------'
+                logging.info('    %s[Recommend]' % msg_prefix)
+                logging.info('    -----------------------------')
+                logging.info('    | NickName: %s' % info['NickName'])
+                logging.info('    | NickName: %s' % info['NickName'])
+                logging.info('    | Alias: %s' % info['Alias'])
+                logging.info('    | Local: %s %s' % (info['Province'], info['City']))
+                logging.info('    | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']])
+                logging.info('    -----------------------------')
         elif mtype == 47:
             msg_content['type'] = 6
             msg_content['data'] = self.search_content('cdnurl', content)
             if self.DEBUG:
-                print '    %s[Animation] %s' % (msg_prefix, msg_content['data'])
+                logging.info('    %s[Animation] %s' % (msg_prefix, msg_content['data']))
         elif mtype == 49:
             msg_content['type'] = 7
             if msg['AppMsgType'] == 3:
@@ -612,40 +617,39 @@ class WXBot:
                                    'content': msg.get('Content')  # 有的公众号会发一次性3 4条链接一个大图,如果只url那只能获取第一条,content里面有所有的链接
                                    }
             if self.DEBUG:
-                print '    %s[Share] %s' % (msg_prefix, app_msg_type)
-                print '    --------------------------'
-                print '    | title: %s' % msg['FileName']
-                print '    | desc: %s' % self.search_content('des', content, 'xml')
-                print '    | link: %s' % msg['Url']
-                print '    | from: %s' % self.search_content('appname', content, 'xml')
-                print '    | content: %s' % (msg.get('content')[:20] if msg.get('content') else "unknown")
-                print '    --------------------------'
-
+                logging.info('    %s[Share] %s' % (msg_prefix, app_msg_type))
+                logging.info('    --------------------------')
+                logging.info('    | title: %s' % msg['FileName'])
+                logging.info('    | desc: %s' % self.search_content('des', content, 'xml'))
+                logging.info('    | link: %s' % msg['Url'])
+                logging.info('    | from: %s' % self.search_content('appname', content, 'xml'))
+                logging.info('    | content: %s' % (msg.get('content')[:20] if msg.get('content') else "unknown"))
+                logging.info('    --------------------------')
         elif mtype == 62:
             msg_content['type'] = 8
             msg_content['data'] = content
             if self.DEBUG:
-                print '    %s[Video] Please check on mobiles' % msg_prefix
+                logging.info('    %s[Video] Please check on mobiles' % msg_prefix)
         elif mtype == 53:
             msg_content['type'] = 9
             msg_content['data'] = content
             if self.DEBUG:
-                print '    %s[Video Call]' % msg_prefix
+                logging.info('    %s[Video Call]' % msg_prefix)
         elif mtype == 10002:
             msg_content['type'] = 10
             msg_content['data'] = content
             if self.DEBUG:
-                print '    %s[Redraw]' % msg_prefix
+                logging.info('    %s[Redraw]' % msg_prefix)
         elif mtype == 10000:  # unknown, maybe red packet, or group invite
             msg_content['type'] = 12
             msg_content['data'] = msg['Content']
             if self.DEBUG:
-                print '    [Unknown]'
+                logging.info('    [Unknown]')
         else:
             msg_content['type'] = 99
             msg_content['data'] = content
             if self.DEBUG:
-                print '    %s[Unknown]' % msg_prefix
+                logging.info('    %s[Unknown]' % msg_prefix)
         return msg_content
 
     def handle_msg(self, r):
@@ -675,7 +679,7 @@ class WXBot:
                         f.write(msg['StatusNotifyUserName'])
                     with open(os.path.join(self.temp_pwd,'wxid.txt'), 'w') as f:
                         f.write(wxid_str)
-                    print "[INFO] Contact list is too big. Now start to fetch member list ."
+                    logging.info("[INFO] Contact list is too big. Now start to fetch member list .")
                     self.get_big_contact()
 
             elif msg['MsgType'] == 37:  # friend request
@@ -715,7 +719,7 @@ class WXBot:
             user['name'] = HTMLParser.HTMLParser().unescape(user['name'])
 
             if self.DEBUG and msg_type_id != 0:
-                print u'[MSG] %s:' % user['name']
+                logging.info(u'[MSG] %s:' % user['name'])
             content = self.extract_msg_content(msg_type_id, msg)
             message = {'msg_type_id': msg_type_id,
                        'msg_id': msg['MsgId'],
@@ -766,17 +770,17 @@ class WXBot:
                     elif selector == '0':  # 无事件
                         pass
                     else:
-                        print '[DEBUG] sync_check:', retcode, selector
+                        logging.info('[DEBUG] sync_check:', retcode, selector)
                         r = self.sync()
                         if r is not None:
                             self.handle_msg(r)
                 else:
-                    print '[DEBUG] sync_check:', retcode, selector
+                    logging.info('[DEBUG] sync_check:', retcode, selector)
                     time.sleep(10)
                 self.schedule()
             except:
-                print '[ERROR] Except in proc_msg'
-                print format_exc()
+                logging.info('[ERROR] Except in proc_msg')
+                logging.info(format_exc())
             check_time = time.time() - check_time
             if check_time < 0.8:
                 time.sleep(1 - check_time)
@@ -944,7 +948,7 @@ class WXBot:
 
     def upload_media(self, fpath, is_img=False):
         if not os.path.exists(fpath):
-            print '[ERROR] File not exists.'
+            logging.info('[ERROR] File not exists.')
             return None
         url_1 = 'https://file.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
         url_2 = 'https://file2.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
@@ -976,7 +980,7 @@ class WXBot:
                 # 当file返回值不为0时则为上传失败,尝试第二服务器上传
                 r = self.session.post(url_2, files=files)
             if json.loads(r.text)['BaseResponse']['Ret'] != 0:
-                print '[ERROR] Upload media failure.'
+                logging.info('[ERROR] Upload media failure.')
                 return None
             mid = json.loads(r.text)['MediaId']
             return mid
@@ -1065,7 +1069,7 @@ class WXBot:
                     result = True
                     for line in f.readlines():
                         line = line.replace('\n', '')
-                        print '-> ' + name + ': ' + line
+                        logging.info('-> ' + name + ': ' + line)
                         if self.send_msg_by_uid(line, uid):
                             pass
                         else:
@@ -1080,7 +1084,7 @@ class WXBot:
                     return False
         else:
             if self.DEBUG:
-                print '[ERROR] This user does not exist .'
+                logging.info('[ERROR] This user does not exist .')
             return True
 
     @staticmethod
@@ -1098,28 +1102,28 @@ class WXBot:
     def run(self):
         self.get_uuid()
         self.gen_qr_code(os.path.join(self.temp_pwd,'wxqr.png'))
-        print '[INFO] Please use WeChat to scan the QR code .'
+        logging.info('[INFO] Please use WeChat to scan the QR code .')
 
         result = self.wait4login()
         if result != SUCCESS:
-            print '[ERROR] Web WeChat login failed. failed code=%s' % (result,)
+            logging.info('[ERROR] Web WeChat login failed. failed code=%s' % (result,))
             return
 
         if self.login():
-            print '[INFO] Web WeChat login succeed .'
+            logging.info('[INFO] Web WeChat login succeed .')
         else:
-            print '[ERROR] Web WeChat login failed .'
+            logging.info('[ERROR] Web WeChat login failed .')
             return
 
         if self.init():
-            print '[INFO] Web WeChat init succeed .'
+            logging.info('[INFO] Web WeChat init succeed .')
         else:
-            print '[INFO] Web WeChat init failed'
+            logging.info('[INFO] Web WeChat init failed')
             return
         self.status_notify()
         if self.get_contact():
-            print '[INFO] Get %d contacts' % len(self.contact_list)
-            print '[INFO] Start to process messages .'
+            logging.info('[INFO] Get %d contacts' % len(self.contact_list))
+            logging.info('[INFO] Start to process messages .')
         self.proc_msg()
 #第一步:获取uuid
     def get_uuid(self):
@@ -1151,8 +1155,8 @@ class WXBot:
             # img = Image.open(qr_file_path)
             # img.show()
         elif self.conf['qr'] == 'tty':
-            print(qr.terminal(quiet_zone=1))
-
+            logging.info(qr.terminal(quiet_zone=1))
+            
     def do_request(self, url):
         r = self.session.get(url)
         r.encoding = 'utf-8'
@@ -1184,7 +1188,7 @@ class WXBot:
             url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time()))
             code, data = self.do_request(url)
             if code == SCANED:
-                print '[INFO] Please confirm to login .'
+                logging.info('[INFO] Please confirm to login .')
                 tip = 0
             elif code == SUCCESS:  # 确认登录成功
                 param = re.search(r'window.redirect_uri="(\S+?)";', data)
@@ -1195,13 +1199,13 @@ class WXBot:
                 self.base_host = temp_host[:temp_host.find("/")]
                 return code
             elif code == TIMEOUT:
-                print '[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,)
+                logging.info('[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,))
 
                 tip = 1  # 重置
                 retry_time -= 1
                 time.sleep(try_later_secs)
             else:
-                print ('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
+                logging.info('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
                        (code, try_later_secs))
                 tip = 1
                 retry_time -= 1
@@ -1211,7 +1215,7 @@ class WXBot:
 
     def login(self):
         if len(self.redirect_uri) < 4:
-            print '[ERROR] Login failed due to network problem, please try again.'
+            logging.info('[ERROR] Login failed due to network problem, please try again.')
             return False
         r = self.session.get(self.redirect_uri)
         r.encoding = 'utf-8'