Skip to content
This repository has been archived by the owner on May 5, 2024. It is now read-only.

Commit

Permalink
日志类型添加 捕获KeyboardInterrupt
Browse files Browse the repository at this point in the history
  • Loading branch information
Yinzo committed Mar 8, 2016
1 parent 441c763 commit b430f99
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 163 deletions.
48 changes: 23 additions & 25 deletions Group.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, operator, ip):
self.gid = ""
elif isinstance(ip, GroupMsg):
self.guin = ip.from_uin
self.gid = ip.group_code
self.gid = operator.uin_to_account(ip.group_code)
self.msg_id = int(random.uniform(20000, 50000))
self.group_code = 0
self.member_list = []
Expand All @@ -56,7 +56,7 @@ def __init__(self, operator, ip):
"tucao",
]
self.__game_handler = None
logging.info(str(self.gid) + "群已激活, 当前执行顺序: " + str(self.process_order))
logging.info("RUNTIMELOG " + str(self.gid) + "群已激活, 当前执行顺序: " + str(self.process_order))
self.tucao_load()

def update_config(self):
Expand All @@ -72,18 +72,18 @@ def handle(self, msg):
self.update_config()
if self.group_code <= 0:
self.group_code = msg.group_code
logging.info("msg handling.")
logging.info("RUNTIMELOG msg handling.")
# 仅关注消息内容进行处理 Only do the operation of handle the msg content
for func in self.process_order:
try:
if bool(self.config.conf.getint("group", func)):
logging.info("evaling " + func)
logging.info("RUNTIMELOG evaling " + func)
if eval("self." + func)(msg):
logging.info("msg handle finished.")
logging.info("RUNTIMELOG msg handle finished.")
self.msg_list.append(msg)
return func
except ConfigParser.NoOptionError as er:
logging.warning(str(er) + "没有找到" + func + "功能的对应设置,请检查共有配置文件是否正确设置功能参数")
logging.warning("RUNTIMELOG " + str(er) + "没有找到" + func + "功能的对应设置,请检查共有配置文件是否正确设置功能参数")
self.msg_list.append(msg)

def get_member_list(self):
Expand Down Expand Up @@ -120,7 +120,7 @@ def command_0arg(self, msg):
match = re.match(r'^(?:!|!)([^\s\{\}]+)\s*$', msg.content)
if match:
command = str(match.group(1))
logging.info("command format detected, command: " + command)
logging.info("RUNTIMELOG command format detected, command: " + command)

if command == "吐槽列表":
self.show_tucao_list()
Expand All @@ -133,7 +133,7 @@ def command_1arg(self, msg):
if match:
command = str(match.group(1))
arg1 = str(match.group(2))
logging.info("command format detected, command:{0}, arg1:{1}".format(command, arg1))
logging.info("RUNTIMELOG command format detected, command:{0}, arg1:{1}".format(command, arg1))
if command == "删除关键字" and unicode(arg1) in self.tucao_dict:
self.tucao_dict.pop(unicode(arg1))
self.reply("已删除关键字:{0}".format(arg1))
Expand All @@ -146,28 +146,28 @@ def show_tucao_list(self):
result = ""
for key in self.tucao_dict:
result += "关键字:{0} 回复:{1}\n".format(key, " / ".join(self.tucao_dict[key]))
logging.info("Replying the list of tucao")
logging.info("RUNTIMELOG Replying the list of tucao")
self.reply(result)

def callout(self, msg):
if "智障机器人" in msg.content:
logging.info(str(self.gid) + " calling me out, trying to reply....")
logging.info("RUNTIMELOG " + str(self.gid) + " calling me out, trying to reply....")
self.reply("干嘛(‘·д·)")
return True
return False

def repeat(self, msg):
if len(self.msg_list) > 0 and self.msg_list[-1].content == msg.content:
if str(msg.content).strip() not in ("", " ", "[图片]", "[表情]"):
logging.info(str(self.gid) + " repeating, trying to reply " + str(msg.content))
logging.info("RUNTIMELOG " + str(self.gid) + " repeating, trying to reply " + str(msg.content))
self.reply(msg.content)
return True
return False

def tucao(self, msg):
match = re.match(r'^(?:!|!)(learn|delete)(?:\s?){(.+)}(?:\s?){(.+)}', msg.content)
if match:
logging.info("tucao command detected.")
logging.info("RUNTIMELOG tucao command detected.")
command = str(match.group(1)).decode('utf8')
key = str(match.group(2)).decode('utf8')
value = str(match.group(3)).decode('utf8')
Expand All @@ -189,7 +189,7 @@ def tucao(self, msg):
else:
for key in self.tucao_dict.keys():
if str(key) in msg.content and self.tucao_dict[key]:
logging.info("tucao pattern detected, replying...")
logging.info("RUNTIMELOG tucao pattern detected, replying...")
self.reply(random.choice(self.tucao_dict[key]))
return True
return False
Expand All @@ -199,9 +199,9 @@ def tucao_save(self):
tucao_file_path = str(self.global_config.conf.get('global', 'tucao_path')) + str(self.gid) + ".tucao"
with open(tucao_file_path, "w+") as tucao_file:
cPickle.dump(self.tucao_dict, tucao_file)
logging.info("tucao saved. Now tucao list: {0}".format(str(self.tucao_dict)))
logging.info("RUNTIMELOG tucao saved. Now tucao list: {0}".format(str(self.tucao_dict)))
except Exception:
logging.error("Fail to save tucao.")
logging.error("RUNTIMELOG Fail to save tucao.")
raise IOError("Fail to save tucao.")

def tucao_load(self):
Expand All @@ -216,17 +216,17 @@ def tucao_load(self):
with open(tucao_file_name, "r") as tucao_file:
try:
self.tucao_dict = cPickle.load(tucao_file)
logging.info("tucao loaded. Now tucao list: {0}".format(str(self.tucao_dict)))
logging.info("RUNTIMELOG tucao loaded. Now tucao list: {0}".format(str(self.tucao_dict)))
except EOFError:
logging.info("tucao file is empty.")
logging.info("RUNTIMELOG tucao file is empty.")
# except Exception as er:
# logging.error("Fail to load tucao: ", er)
# raise IOError("Fail to load tucao: ", er)

def follow(self, msg):
match = re.match(r'^(?:!|!)(follow|unfollow) (\d+|me)', msg.content)
if match:
logging.info("following...")
logging.info("RUNTIMELOG following...")
command = str(match.group(1))
target = str(match.group(2))
if target == 'me':
Expand All @@ -249,16 +249,14 @@ def follow(self, msg):
def weather(self, msg):
match = re.match(ur'^(weather|天气) (\w+|[\u4e00-\u9fa5]+)', msg.content)
if match:
logging.info("查询天气...")
print msg.content
logging.info("RUNTIMELOG 查询天气...")
command = match.group(1)
city = match.group(2)
logging.info(msg.content)
print city
logging.info("RUNTIMELOG 查询天气语句: " + msg.content)
if command == 'weather' or command == u'天气':
query = Weather()
info = query.getWeatherOfCity(city)
logging.info(str(info))
logging.info("RESPONSE " + str(info))
self.reply(str(info))
return True
return False
Expand All @@ -271,13 +269,13 @@ def ask(self, msg):
command = match.group(1)
info = match.group(2)
# logging.info("info:")
logging.info(msg.content)
logging.info("RUNTIMELOG 图灵问答语句: " + msg.content)
# print info
if command == 'ask' or command == u'问':
# self.reply("我开始查询" + city + "的天气啦")
query = Turing()
info = query.getReply(info)
logging.info(str(info))
logging.info("RESPONSE " + str(info))
self.reply(str(info))
return True
return False
Expand Down
38 changes: 19 additions & 19 deletions HttpClient.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import cookielib, urllib, urllib2, socket, time, os
import cookielib, urllib, urllib2, socket, time, os, logging


class HttpClient:
Expand All @@ -8,9 +8,9 @@ class HttpClient:
# __req = urllib2.build_opener(urllib2.HTTPCookieProcessor(__cookie),logprint)
__req = urllib2.build_opener(urllib2.HTTPCookieProcessor(__cookie))
__req.addheaders = [
('Accept', 'application/javascript, */*;q=0.8'),
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
('User-Agent',
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"),
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"),
('Referer', 'http:https://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1')
]
urllib2.install_opener(__req)
Expand All @@ -28,13 +28,11 @@ def getTimeStamp(self):

def Get(self, url, refer=None):
try:
# print "requesting " + str(url) + " with cookies:"
# print self.__cookie
req = urllib2.Request(url)
# if not (refer is None):
# req.add_header('Referer', refer)
req.add_header('Referer', 'http:https://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1')
# print req.headers
if refer is None:
req.add_header('Referer', 'http:https://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1')
else:
req.add_header('Referer', refer)
tmp_req = urllib2.urlopen(req)
self.__cookie.save('cookie/cookie.data',ignore_discard=True,ignore_expires=True)
return tmp_req.read()
Expand All @@ -43,18 +41,20 @@ def Get(self, url, refer=None):

def Post(self, url, data, refer=None):
try:
# print "requesting " + str(url) + " with data:"
# print data
# print "Cookies: "
# print self.__cookie
req = urllib2.Request(url, urllib.urlencode(data))
if refer is not None:
req.add_header('Referer', refer)
else:
if refer is None:
req.add_header('Referer', 'http:https://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2')
# print "Headers: "
# print req.headers
tmp_req = urllib2.urlopen(req, timeout=180)
else:
req.add_header('Referer', refer)
# logging.DEBUG("REQUEST requesting {url} with header:\t{header}\tdata:\t{data}".format(
# header = req.headers,
# url = str(url),
# data = str(data),
# ))
try:
tmp_req = urllib2.urlopen(req, timeout=180)
except:
raise IOError
self.__cookie.save('cookie/cookie.data',ignore_discard=True,ignore_expires=True)
return tmp_req.read()
except urllib2.HTTPError, e:
Expand Down
27 changes: 12 additions & 15 deletions MsgHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,10 @@ def handle(self, msg_list):
# 仅处理程序管理层面上的操作 Only do the operation of the program management

if not isinstance(msg, (Msg, Notify)):
logging.error("Handler received a not a Msg or Notify instance.")
raise TypeError("Handler received a not a Msg or Notify instance.")
raise TypeError("RUNTIMELOG Handler received a not a Msg or Notify instance.")

elif isinstance(msg, MsgWithContent):
logging.info(str(self.__get_account(msg)) + ":" + msg.content)
logging.info("DATASTREAM " + str(self.__get_account(msg)) + ":" + msg.content)

if isinstance(msg, GroupMsg): # 群聊信息的处理
# 判断群对象是否存在,group_code实际上为群号
Expand All @@ -46,12 +45,12 @@ def handle(self, msg_list):
# 维护一个线程队列,然后每一个线程处理各自的信息
self.process_threads[msg.group_code] = MsgHandleQueue(self.__group_list[msg.group_code])
self.process_threads[msg.group_code].start()
logging.debug("Now group list: " + str(self.__group_list))
logging.debug("RUNTIMELOG Now group list: " + str(self.__group_list))

tgt_group = self.__group_list[msg.group_code]
if len(tgt_group.msg_list) >= 1 and msg.msg_id == tgt_group.msg_list[-1].msg_id:
# 若如上一条seq重复则抛弃此条信息不处理
logging.info("消息重复,抛弃")
logging.info("RUNTIMELOG 消息重复,抛弃")
return

tgt_group.msg_id = msg.msg_id
Expand All @@ -65,14 +64,14 @@ def handle(self, msg_list):
# 维护一个线程队列,然后每一个线程处理各自的信息
self.process_threads[tid] = MsgHandleQueue(self.__pm_list[tid])
self.process_threads[tid].start()
logging.debug("Now pm thread list: " + str(self.__pm_list))
logging.debug("RUNTIMELOG Now pm thread list: " + str(self.__pm_list))

tgt_pm = self.__pm_list[tid]
if len(tgt_pm.msg_list) >= 1 and msg.time == tgt_pm.msg_list[-1].time \
and msg.from_uin == tgt_pm.msg_list[-1].from_uin \
and msg.content == tgt_pm.msg_list[-1].content:
# 私聊没有seq可用于判断重复,只能抛弃同一个人在同一时间戳发出的内容相同的消息。
logging.info("消息重复,抛弃")
logging.info("RUNTIMELOG 消息重复,抛弃")
return

tgt_pm.msg_id = msg.msg_id
Expand All @@ -85,14 +84,14 @@ def handle(self, msg_list):
self.__sess_list[tid] = Sess(self.__operator, msg)
self.process_threads[tid] = MsgHandleQueue(self.__sess_list[tid])
self.process_threads[tid].start()
logging.debug("Now sess thread list: " + str(self.__sess_list))
logging.debug("RUNTIMELOG Now sess thread list: " + str(self.__sess_list))

tgt_sess = self.__sess_list[tid]
if len(tgt_sess.msg_list) >= 1 and msg.time == tgt_sess.msg_list[-1].time \
and msg.from_uin == tgt_sess.msg_list[-1].from_uin \
and msg.content == tgt_sess.msg_list[-1].content:
# 私聊没有seq可用于判断重复,只能抛弃同一个人在同一时间戳发出的同一内容的消息。
logging.info("消息重复,抛弃")
logging.info("RUNTIMELOG 消息重复,抛弃")
return
tgt_sess.msg_id = msg.msg_id
self.process_threads[tid].append(msg)
Expand All @@ -107,8 +106,7 @@ def handle(self, msg_list):
self.__kick_message(msg)

else:
logging.warning("Unsolved Msg type :" + str(msg.poll_type))
raise TypeError("Unsolved Msg type :" + str(msg.poll_type))
raise TypeError("RUNTIMELOG Unsolved Msg type :" + str(msg.poll_type))

def __get_account(self, msg):
assert isinstance(msg, (Msg, Notify)), "function get_account received a not Msg or Notify parameter."
Expand All @@ -123,14 +121,13 @@ def __get_account(self, msg):
return str(msg.msg_id).join("[]") + str(self.__operator.get_friend_info(msg.send_uin))

def __input_notify_handler(self, msg):
logging.info(str(self.__get_account(msg)) + " is typing...")
logging.info("DATASTREAM " + str(self.__get_account(msg)) + " is typing...")

def __buddies_status_change_handler(self, msg):
pass

def __kick_message(self, msg):
logging.warning(str(msg.to_uin) + " is kicked. Reason: " + str(msg.reason))
logging.warning("[{0}]{1} is kicked. Reason: {2}".format(
logging.warning("RUNTIMELOG [{0}]{1} is kicked. Reason: {2}".format(
str(msg.to_uin),
self.__operator.username,
str(msg.reason),
Expand All @@ -150,7 +147,7 @@ def run(self):
while 1:
if len(self.msg_queue):
self.handler.handle(self.msg_queue.pop(0))
logging.debug("queue handling.Now queue length:" + str(len(self.msg_queue)))
logging.debug("RUNTIMELOG queue handling.Now queue length:" + str(len(self.msg_queue)))
else:
time.sleep(1)

Expand Down
Loading

0 comments on commit b430f99

Please sign in to comment.