Python实现微信自动欢迎新人入群(Ⅱ)

Python实现微信自动欢迎新人入群(Ⅱ)

承接上篇,在完成这个小脚本后,部署到腾讯云服务器上运行,发现时不时的发生崩溃。一步步排查后发现,是脚本资源占用高,然后导致了崩溃。时不时的崩溃,既然找到了原因,那就及时修复它。然后找了个维护的借口,争取了一夜的维护时间。

下面进入正题:

首先,目录结构不用变动,我们只是修改Main.py的一些功能函数。

下面是需要导入的包:

from WechatPCAPI import WechatPCAPI
import time
import logging
from queue import Queue
import threading

导入的包较上次也是没有变动的。

同上篇一样,需要定义三个队列用来处理接收到的信息:

queue_recved_message = Queue()#用来处理所有消息
queue_groups=Queue() #用来处理群ID消息
queue_Members=Queue()#用来处理群成员信息

群成员这个数据结构有了些许变化,群成员现在只有群ID,昵称这两个属性了:

class Person:
    def __init__(self):
        self.chatroom_id = ""
        self.nick_name = ""

接下来定义处理消息队列的函数,首先还是要获取指定关键词的群列表。由于群成员新进群或者被移除群聊时,wx都会产生一条消息,这条消息的类型是‘msg::chatroom’ ,数据类型是‘10000’,具体的消息内容就是‘xxx通过xx方式加入了群聊’或者‘xxx被移除了群聊’,所以要响应新成员进群,我们只需要判断‘msg::chatroom’的chatroom_id,以及消息内容便可。

def thead_handle_mess(wx_inst):
    with open('config.json', 'r')as f:
        j = json.loads(f.read())
    chatroom=j['chatroom']
    while True:
        if not queue_recved_message.empty():
            message = queue_recved_message.get()
            if 'friend::chatroom' in message.get('type'):
                if chatroom in message.get('data', {}).get('chatroom_name', ""):
                    queue_groups.put(message.get(
                    'data', {}).get('chatroom_id', ""))
            elif 'msg::chatroom' in message.get('type'):
                if 'data_type' in message.get('data').keys():
                    if message.get('data').get('data_type') == '10000' and "加入" in message.get('data').get('msg'):
                        Per = Person()  # 生成新的对象
                        Per.chatroom_id =message.get('data').get('from_chatroom_wxid')
                        Per.nick_name = message.get('data').get('msg').split("\"")[1]
                        queue_Members.put(Per)

接下来定义获取群列表的函数:

def get_group_list():
    Group_list = []
    while queue_groups.empty():
        time.sleep(1)
    while not queue_groups.empty():
        Group_list.append(queue_groups.get())
    return Group_list

然后就是欢迎群成员的函数:

def thread_handle_member_welcome(wx_inst, group_list):
    groups = group_list
    with open('config.json', 'r')as f:
        j = json.loads(f.read())
    mess=j['mess']
    while True:
        if not queue_Members.empty():
            Person = queue_Members.get()
            if Person.chatroom_id in groups:
                M=str(Person.nick_name)+","+mess
                wx_inst.send_text(to_user=Person.chatroom_id,msg=M)
                print("say welcome to {}".format(Person.nick_name))
            time.sleep(2)

这里面有个问题,群成员的nickname是自己这一端显示的成员nickname。例如:有个成员叫member,你给他的备注是猪,那么欢迎语中的nickname就是猪,这点使用时需要注意下。

这样这个小程序的所有组件就写完了,接下来的工作是将它们组合起来:

def main():
    print("初始化中...请稍候!")
    wx_inst = WechatPCAPI(on_message=onmessage)
    wx_inst.start_wechat(block=True)
    while not wx_inst.get_myself():
        time.sleep(3)
    threading.Thread(target=thead_handle_mess, args=(wx_inst,)).start()
    wx_inst.update_frinds()
    Group_list = get_group_list()
    print("运行中....")
    threading.Thread(target=thread_handle_member_welcome,args=(wx_inst, Group_list,)).start()

设置下日志记录功能,方便日后排错。

file_name = str(time.strftime("%Y-%m-%d", time.localtime()))+".log"
logging.basicConfig(filename=file_name,level=logging.INFO)

完整的代码:

# coding: utf-8
from WechatPCAPI import WechatPCAPI
import time
import logging
from queue import Queue
import threading
file_name = str(time.strftime("%Y-%m-%d", time.localtime()))+".log"
logging.basicConfig(filename=file_name, level=logging.INFO)
queue_recved_message = Queue()  # 用来处理所有消息
queue_groups = Queue()  # 用来处理群ID消息
queue_Members = Queue()  # 用来处理群成员信息
class Person:
    def __init__(self):
        self.chatroom_id = ""
        self.nick_name = ""
def onmessage(message):
    queue_recved_message.put(message)
def thead_handle_mess(wx_inst):
    with open('config.json', 'r')as f:
        j = json.loads(f.read())
    chatroom=j['chatroom']
    while True:
        if not queue_recved_message.empty():
            message = queue_recved_message.get()
            if 'friend::chatroom' in message.get('type'):
                if chatroom in message.get('data', {}).get('chatroom_name', ""):
                    queue_groups.put(message.get(
                    'data', {}).get('chatroom_id', ""))
            elif 'msg::chatroom' in message.get('type'):
                if 'data_type' in message.get('data').keys():
                    if message.get('data').get('data_type') == '10000' and "加入" in message.get('data').get('msg'):
                        Per = Person()  # 生成新的对象
                        Per.chatroom_id =message.get('data').get('from_chatroom_wxid')
                        Per.nick_name = message.get('data').get('msg').split("\"")[1]
                        queue_Members.put(Per)
def get_group_list():
    Group_list = []
    while queue_groups.empty():
        time.sleep(1)
    while not queue_groups.empty():
        Group_list.append(queue_groups.get())
    return Group_list
def thread_handle_member_welcome(wx_inst, group_list):
    groups = group_list
    with open('config.json', 'r')as f:
        j = json.loads(f.read())
    mess=j['mess']
    while True:
        if not queue_Members.empty():
            Person = queue_Members.get()
            if Person.chatroom_id in groups:
                M=str(Person.nick_name)+","+mess
                wx_inst.send_text(to_user=Person.chatroom_id,msg=M)
                print("say welcome to {}".format(Person.nick_name))
            time.sleep(2)
def main():
    print("初始化中...请稍候!")
    wx_inst = WechatPCAPI(on_message=onmessage)
    wx_inst.start_wechat(block=True)
    while not wx_inst.get_myself():
        time.sleep(3)
    threading.Thread(target=thead_handle_mess, args=(wx_inst,)).start()
    wx_inst.update_frinds()
    Group_list = get_group_list()
    print("运行中....")
    threading.Thread(target=thread_handle_member_welcome,args=(wx_inst, Group_list,)).start()
if __name__ == "__main__":
    main()

2020求脱单啊

文中有错的地方,欢迎指出!!

中国加油,武汉加油!!

你可能感兴趣的:(Python实现微信自动欢迎新人入群(Ⅱ))