Skip to content

Commit

Permalink
2017年9月9日 修正消息队列阻塞
Browse files Browse the repository at this point in the history
  • Loading branch information
ZKeeer committed Sep 9, 2017
1 parent 773c522 commit a953f7f
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 60 deletions.
2 changes: 1 addition & 1 deletion autoreply.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def AutoReply(self, msg):
if k in msg['Content'] or k in msg['Text'] or k in msg_from:
msg_reply = self.reply_rule.get(k, "我收到消息了,待会儿回复")
msg_reply += " [来自ZKeeer微信助手]"
time.sleep(0.3)
time.sleep(0.5)
# 发送给好友自动回复内容
itchat.send(msg_reply, toUserName=msg['FromUserName'])
# 好友消息,自动回复消息备份发送至文件助手
Expand Down
43 changes: 42 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,45 @@
reply_table = "REPLY"
keywordlisten_table = "KEYWORDLISTEN"
signin_table = "SIGNIN"

msgbackup_table = "BACKUP"
today_menu = ['面包', '蛋糕', '荷包蛋', '烧饼', '饽饽', '油条', '馄饨', '火腿', '面条', '小笼包', '玉米粥', '肉包', '山东煎饼', '饺子', '煎蛋', '烧卖', '生煎',
'锅贴',
'包子', '酸奶', '苹果', '梨', '奶', '香蕉', '皮蛋瘦肉粥', '蛋挞', '南瓜粥', '煎饼', '玉米糊', '泡面', '粥', '馒头', '燕麦片', '水煮蛋', '米粉',
'豆浆', '牛奶',
'花卷', '豆腐脑', '煎饼果子', '小米粥', '黑米糕', '鸡蛋饼', '牛奶布丁', '水果沙拉', '鸡蛋羹', '南瓜馅饼', '鸡蛋灌饼', '奶香小馒头', '汉堡包', '披萨',
'八宝粥',
'三明治', '蛋包饭', '豆沙红薯饼', '驴肉火烧', '粥', '粢饭糕', '蒸饺', '白粥', '泡椒凤瓜', '香卤猪肝', '盐水河虾', '盐水鹅', '五香牛肉', '醋香皮蛋',
'凉拌黄瓜',
'五香茶干', '椒盐花生米', '东北小木耳', '三色泡萝卜', '凉拌腐竹', '青椒肉丝', '韮菜肉丝', '雪菜肉丝', '宫爆鸡丁', '三色炒玉米', '洋葱炒肥肠', '炒鱼片',
'鱼香肉丝',
'芦蒿肉丝', '西红柿炒鸡', '香菇炒青', '炒茼蒿', '青椒土豆丝', '丝瓜毛豆', '洋葱炒蛋', '油焖茄子', '大蒜肉丝', '海鲜炒粉丝', '石头豆腐羹', '淮扬煮干丝',
'外婆红烧肉',
'大碗酸菜鱼', '冬瓜排骨', '牛肉粉丝', '红烧肥肠', '糖醋带鱼', '油淋蚕豆', '香辣鹅四件', '黑菜烧咸肉', '糖醋排骨', '雪菜烧黑鱼', '红烧老鹅', '小鱼小虾', '煮鱼杂',
'鸭块水饺', '小葱涨蛋', '蚂蚁上树', '大碗杂烩', '茄汁锅巴', '香煎玉米烙', '雪菜野货', '砂锅肉圆', '铁板肥肠', '铁板牛柳', '铁板鱿鱼', '铁板黑椒牛仔骨',
'铁板蒜泥大虾',
'干锅茶树菇', '干锅有机花菜', '干锅手撕包菜', '干锅肥肠', '明炉羊肉', '明炉狗肉', '明炉牛肉', '黑鱼汤', '黄油草鸡汤', '鲫鱼汤', '昂刺鱼汤', '季花鱼汤',
'番茄蛋汤',
'紫菜蛋汤', '青菜豆腐', '西湖牛肉羹', '石头豆腐羹', '开胃酸辣羹', '咸菜蛋花汤', '烤春鸡', '德式乡村猪肘', '意香猪肉丸', '香菇鸡肉丸', '烤全翅新奥尔良风味',
'烤全翅加勒比风味',
'鲍菇串香肠', '照烧鱿鱼仔', '芝士条', '面包条', '香蒜面包', '美式香酥薯格', '美式洋葱圈', '天辣剁椒鸡串', '浓情香鸡翼', '香草凤尾虾', 'BBQ烧烤肋排',
'法式红酒拘蜗牛',
'孜然羊肉丸', '意香猪肉丸', '拌面', '蛋炒饭', '海带排骨汤', '排骨面(粉)', '扁食', '炒米粉', '莲子猪肚汤', '猪肚面(粉)', '蒸饺', '炒白果', '花旗乌鸡汤',
'乌鸡面(粉)', '小笼包', '炒面条', '党参猪心汤', '猪心面(粉)', '酸菜面(粉)', '炒粉干', '天麻猪脑汤', '猪脑面(粉)', '青菜面(粉)', '炒河粉', '茶树菇老鸭汤',
'老鸭面(粉)', '紫菜蛋汤', '拌青菜', '西红柿蛋汤', '汤水饺', '扁食面/粉', '荷包蛋面/粉', '香肠', '茶叶蛋', '煎荷包蛋', '鸡腿', '鸭腿', '香干', '鸡腿套餐',
'海带排骨罐套餐', '乌鸡罐套餐', '莲子猪罐套餐', '鸭腿套餐', '党参猪心罐套餐', '天麻猪脑罐套餐', '茶树菇老鸭罐套餐']
emoticons = ["""_(┐「ε:)_""", """_(:3 」∠)_""", """( ̄y▽ ̄)~*捂嘴偷笑""", """・゜・(PД`q。)・゜・""", """(ง •̀_•́)ง""",
""" (•̀ᴗ•́)و ̑̑""", """ヽ(•̀ω•́ )ゝ""", """(,,• ₃ •,,)""", """ (。˘•ε•˘。)""", """ (=゚ω゚)ノ""", """(○’ω’○)""",
""" (´・ω・`)""", """ ヽ(・ω・。)ノ""", """ (。-`ω´-)""", """ (´・ω・`)""", """(´・ω・)ノ""", """(ノ・ω・)ノ゙""",
"""(♥ó㉨ò)ノ♡""", """(ó㉨ò)""", """・㉨・""", """( ・◇・)?""", """ヽ(*´Д`*)ノ""", """(´°̥̥̥̥̥̥̥̥ω°̥̥̥̥̥̥̥̥`)""",
"""(╭ ̄3 ̄)╭♡""", """(☆゚∀゚)""", """⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄.""", """(´-ι_-`)""", """ಠ౪ಠ""", """ ಥ_ಥ""",
""" (/≥▽≤/)""", """ ヾ(o◕∀◕)ノ""", """ *★,°*:.☆\( ̄▽ ̄)/$:*.°★*""", """ヾ (o ° ω ° O ) ノ゙""", """╰(*°▽°*)╯""",
"""(。◕ˇ∀ˇ◕) o(*≧▽≦)ツ""", """≖‿≖✧""", """ >ㅂ<""", """ ˋ▽ˊ""", """ \(•ㅂ•)/♥""", """✪ε✪""", """✪υ✪""",
"""✪ω✪""", """ 눈_눈""", """ ,,Ծ‸Ծ,,""", """ π__π""", """ (/TДT)/""", """ʅ(´◔౪◔)ʃ""", """ (。☉౪ ⊙。)""",
""" o(*≧▽≦)ツ┏━┓拍桌狂笑""", """(●'◡'●)ノ♥""", """ <(▰˘◡˘▰)>""", """。◕‿◕。""", """ (。・`ω´・)""", """(♥◠‿◠)ノ""",
"""ʅ(‾◡◝)""", """(≖ ‿ ≖)✧""", """ (´∀`*)""", """ (^∀^)""", """(o^∇^o)ノ""", """ ヾ(=^▽^=)ノ""",
""" (* ̄∇ ̄*)""", """(*´∇`*)""", """(*゚▽゚*)""", """(。・ω・)ノ゙""", """ (≡ω≡.)""", """ (`・ω・´)""",
""" (´・ω・`)""", """ (●´ω`●)φ""", """(/= _ =)/~┴┴""", """(/"≡ _ ≡)/~┴┴""", """(╯‵□′)╯︵┻━┻""",
"""(┙>∧<)┙へ┻┻""", """ (╯-_-)╯╧╧""", """(╬▔皿▔)""", """(╬ ̄皿 ̄)凸""", """(`・д・´)""", """ (ノ`Д´)ノ""",
"""(゚皿゚メ)""", """(#`皿´)""", """ ( -д-)ノ""", """(°ο°)""", """ Σ( ° △ °|||)︴ """, """∑(っ °Д °;)っ""",
""" (°□°;)""", """ (⊙□⊙)""", """ ( ° ▽、° )""", """ ⊙▂⊙""", """ ミ ゚Д゚彡""", """╮(╯▽╰)╭""", """ ╮(╯_╰)╭""",
"""( ̄▽ ̄")""", """( ̄工 ̄lll)""", """(﹁"﹁)""", """( _ _)ノ|扶墙""", """ㄟ( ▔, ▔ )ㄏ""", """ (*´Д`*)"""]
37 changes: 34 additions & 3 deletions execution.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import os
import random
import re

import itchat

import config
import screenshoot
from autoreply import MsgAutoReply
from keywordlistener import KeywordListener as Keyword
from signin import SignInMPS

from takephoto import TakeGIF, TakePhoto

class Execution:
REVOCATIONPATH = "./Revocation/"
Expand All @@ -26,7 +28,7 @@ def Execution(self, message):
# "%s%s%s%s%s关键词" % ("="*4, "Command Message", "="*4, "\n\n", action)

command = message['Text']
msg_send = "{0}{1}{0}{2}".format("=" * 6, "助手消息", "\n\n")
msg_send = "{0}{1}{0}{2}".format("=" * 8, "助手消息", "\n\n")
if re.match(r"^查看文件\[.*\]", command):
filename = re.search(r"^查看文件\[(.*?)\]$", command).group(1)
result = self.ShowFile(filename)
Expand Down Expand Up @@ -106,6 +108,34 @@ def Execution(self, message):
elif re.match("^打开自动回复$", command):
msg_send += self.reply.OpenAutoReply()
itchat.send(msg_send, toUserName='filehelper')
elif re.match("^拍照$", command):
img_name = TakePhoto()
if img_name:
itchat.send("@img@{}".format(img_name), toUserName='filehelper')
else:
msg_send += "拍照失败,请重试"
itchat.send(msg_send, toUserName='filehelper')
elif re.match("^拍动图\d{0,2}$", command):
seconds = re.findall("^拍动图(\d+)",command)
if seconds:
seconds = int(seconds[0])
if seconds not in range(1,61):
msg_send += "时间输入错误,请重试"
itchat.send(msg_send, toUserName='filehelper')
return
else:
seconds = 5
img_name = TakeGIF(seconds)
if img_name:
itchat.send("@img@{}".format(img_name), toUserName='filehelper')
else:
msg_send += "拍照失败,请重试"
itchat.send(msg_send, toUserName='filehelper')
elif re.match("^今天吃什么$", command):
today_choice = random.choice(config.today_menu)
emotion = random.choice(config.emoticons)
msg_send += "今天就吃 {} 吧{}{}".format(today_choice, '\n', emotion)
itchat.send(msg_send, toUserName='filehelper')
elif re.match("^退出程序$", command):
itchat.send("退出程序成功", toUserName='filehelper')
itchat.logout()
Expand All @@ -129,6 +159,7 @@ def Execution(self, message):
r"清空自动回复{1}"
r"关闭自动回复{1}"
r"打开自动回复{1}"
r"今天吃什么{1}"
r"退出程序{1}"
r"其他指令暂不支持,请期待最新版本。".format("\n", "\n\n"),
toUserName="filehelper")
Expand All @@ -137,7 +168,7 @@ def ShowFile(self, filename):
if not os.path.exists(r"./Revocation/" + filename):
return "文件:{} 不存在".format(filename)

if re.search(r"png|jpg|bmp|jpeg|gif", filename):
if re.search(r"png|jpg|bmp|jpeg|gif|webp", filename):
msg_type = "img"
elif re.search(r"avi|rm|map4|wmv", filename):
msg_type = "vid"
Expand Down
25 changes: 12 additions & 13 deletions keywordlistener.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# -*-encoding:utf-8-*-
import re
import sqlite3
from time import localtime, strftime

import itchat

import config
import sqlite3


class KeywordListener:
Expand All @@ -28,7 +30,7 @@ def AddKeyword(self, keyword):
if db_cursor.execute("""SELECT * FROM {} WHERE KEYWORD = '{}';""".format(self.table, keyword)).fetchall():
return "关键词已存在,不用重复添加"
else:
db_connect.execute("""INSERT INTO {} VALUES ('{}');""".format(self.table,keyword))
db_connect.execute("""INSERT INTO {} VALUES ('{}');""".format(self.table, keyword))
db_connect.commit()
return "添加成功"
except BaseException as e:
Expand All @@ -37,7 +39,6 @@ def AddKeyword(self, keyword):
finally:
db_cursor.close()
db_connect.close()
self.keyword_list = self.GetKeyword()

def DeleteKeyword(self, kw):
db_connect = sqlite3.connect(self.db)
Expand All @@ -55,7 +56,6 @@ def DeleteKeyword(self, kw):
finally:
db_cursor.close()
db_connect.close()
self.keyword_list = self.GetKeyword()

def ClearKeyword(self):
db_connect = sqlite3.connect(self.db)
Expand All @@ -68,7 +68,6 @@ def ClearKeyword(self):
return "清空关键词失败,请重试"
finally:
db_connect.close()
self.keyword_list = self.GetKeyword()

def GetKeyword(self):
db_connect = sqlite3.connect(self.db)
Expand All @@ -86,6 +85,7 @@ def GetKeyword(self):
return result_list

def ShowKeyword(self):
self.keyword_list = self.GetKeyword()
msg_send = "现有的关键词:\n"
for item in self.keyword_list:
if item:
Expand Down Expand Up @@ -115,9 +115,7 @@ def GetMsgFrom(self, msg):
if msg['ActualUserName'] == itchat.get_friends()[0]['UserName']:
return
if itchat.search_chatrooms(userName=msg['FromUserName']):
msg_group += r'[ '
msg_group += itchat.search_chatrooms(userName=msg['FromUserName'])['NickName']
msg_group += r' ]'
msg_group += "[ {} ]".format(itchat.search_chatrooms(userName=msg['FromUserName'])['NickName'])
return msg_from, msg_group

def GetMsgContent(self, msg):
Expand All @@ -139,10 +137,10 @@ def GetMsgContent(self, msg):
x, y, location = \
re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*",
msg['OriContent']).group(1, 2, 3)
if not location:
msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
if location:
msg_content = location
else:
msg_content = r"" + location
msg_content = r"纬度->{} 经度->{}".format(x, y)

elif msg['Type'] == 'Sharing':
msg_content = msg['Text']
Expand All @@ -156,6 +154,7 @@ def Listener(self, msg):
:param msg: 微信消息
:return:
"""
self.keyword_list = self.GetKeyword()
mytime = localtime()
msg_time = strftime("%Y/%m/%d %H:%M:%S", mytime)

Expand All @@ -170,9 +169,9 @@ def Listener(self, msg):
msg_from, msg_group = self.GetMsgFrom(msg)
msg_content = self.GetMsgContent(msg)

msg_send = "{0}{1}{0}{2}".format("="*6, "关键词消息", "\n\n")
msg_send = "{0}{1}{0}{2}".format("=" * 6, "关键词消息", "\n\n")
msg_send += "Time: {0}{1}Who: {2}{1}".format(msg_time, "\n\n", msg_from)
if msg_group:
if re.findall(r"\[(.*)\]", msg_group):
msg_send += "Group: {}{}".format(msg_group, "\n\n")
msg_send += "Content: {}".format(msg_content)

Expand Down
35 changes: 26 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,24 @@ def msg_acceptor(msg):


def clearmsglist_func():
record = {'MsgId': "", "time": 0.0}
while True:
if msglist:
if int(msglist[0].get("Visitor", 0)) >= visitors:
msglist.pop(0)
if msglist:
record.update({msglist[0].get('MsgId', ''): time.time()})
else:
# 消息阻塞清理
if msglist[0].get('MsgId', '') == record.get('MsgId', ''):
if time.time() - record.get('time', '') > 10.0:
msglist.pop(0)
else:
record.update({'MsgId': msglist[0].get('MsgId', ''), "time": time.time()})
else:
time.sleep(0.1)


def Pretreat(func):
def wapper(*args, **kwargs):
msgid = ''
Expand All @@ -80,21 +91,22 @@ def wapper(*args, **kwargs):
traceback.print_exc(file=open('log.txt', 'a'))
finally:
# 最终必须更新消息ID,证明访问过该消息
msgid = msglist[0].get('MsgId', '')
# 互斥锁,该消息的访问次数的修改必须是串行
global visitor_wait
while visitor_wait:
pass
visitor_wait = True
msglist[0]['Visitor'] = (msglist[0].get('Visitor', 0) + 1)
visitor_wait = False

if msglist:
msgid = msglist[0].get('MsgId', '')
# 互斥锁,该消息的访问次数的修改必须是串行
global visitor_wait
while visitor_wait:
pass
visitor_wait = True
msglist[0]['Visitor'] = (msglist[0].get('Visitor', 0) + 1)
visitor_wait = False

return wapper


@Pretreat
def execute_func():
global exec_command
# 1.文件助手命令
if msglist[0].get('ToUserName', "") == "filehelper" and msglist[0].get('Type', "") == "Text":
exec_command.Execution(msglist[0])
Expand All @@ -103,6 +115,7 @@ def execute_func():
@Pretreat
def revocation_func():
# 2.撤回消息
global rmsg
rmsg.SaveMsg(msglist[0])
rmsg.Revocation(msglist[0])
rmsg.ClearTimeOutMsg()
Expand All @@ -111,6 +124,7 @@ def revocation_func():
@Pretreat
def keywordlisten_func():
# 3.关键词监听
global listener
if msglist[0].get('Type', '') in ['Text', 'Sharing', 'Map', 'Card'] \
and msglist[0].get('FromUserName', '') != 'filehelper':
listener.Listener(msglist[0])
Expand All @@ -119,18 +133,21 @@ def keywordlisten_func():
@Pretreat
def autoreply_func():
# 4.自动回复
global reply
if os.path.exists("openautoreply"):
reply.AutoReply(msglist[0])


def signin_func():
global signfunc
while True:
# 功能:公众号签到
signfunc.SignIn()
time.sleep(3600)


def keeponline_func():
global keeponline
while True:
# 功能:保持在线
keeponline.ActiveWX()
Expand Down
Loading

0 comments on commit a953f7f

Please sign in to comment.