美文网首页
Python实现微信自动欢迎新人入群(Ⅰ )

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

作者: Odinmx | 来源:发表于2020-01-19 19:42 被阅读0次

    Python实现微信群欢迎机器人

    今天有人问我能不能实现wx自动欢迎新人入群。刚开始听到这个要求,本以为会很简单,毕竟Github上有很多开源的项目,完全直接可以克隆一个,根据自己的需求进行一下修改。当时我这么想,也这么做了,结果发Wechat网页版被禁止登录了!!Github上很多开源项目都是基于wechat网页版,通过HTTP进行的交互。后来经过寻找发现了一个WechatPCAPI,解决了我的问题。

    下面进入正题:

    首先将WechatPCAPI克隆到我们的目录,如下。


    图1.jpg

    下面是需要导入的包。

    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,WXID,昵称三个属性:

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

    接下来定义处理消息队列的函数,要检测新成员进群,首先要获取群ID,然后再更新指定群中成员的变化。如果发现本次更新的群成员信息与上次群成员信息不一致,则多出来的群成员即为新加入的。所以需要获得的消息类型有‘friend::chatroom’,‘member::chatroom’两种。获取这两种消息后,再次分别放到对应的队列中,进行下一步处理。

    def thead_handle_mess(wx_inst):
        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 'member::chatroom' in message.get('type'):
                    Per=Person()
                    Per.chatroom_id=message.get('data',{}).get('chatroom_id',"")
                    Per.wx_id = message.get('data', {}).get('wx_id', "")
                    Per.nick_name = message.get('data', {}).get('wx_nickname', "")
                    queue_Members.put(Per)
    

    接下来在定义更新群成员的函数:

    def thead_handle_getmember(wx_inst,Group_list):
        while True:
            for group in Group_list:
                wx_inst.get_member_of_chatroom(group)
            time.sleep(20)#间隔多长时间更新一次群成员列表
    

    然后定义获取群列表的函数:

    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 get_existed_member(wx_inst,Group_list):
        member_groups={}
        for group in Group_list:
            wx_inst.get_member_of_chatroom(group)
        while queue_Members.empty():
            time.sleep(0.5)
        while not queue_Members.empty():
            Person=queue_Members.get()
            if Person.chatroom_id not in  member_groups.keys():
                member_group={Person.chatroom_id:[Person]}
                member_groups.update(member_group)
            elif Person.wx_id not in get_all_id(member_group[Person.chatroom_id]):
                member_group[Person.chatroom_id].append(Person)
        return member_groups
    

    接下来我们再写欢迎群成员的函数:

    def thread_handle_member_welcome(wx_inst,member_groups):
        groups=member_groups
        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.wx_id not in get_all_id(groups[Person.chatroom_id]):
                    add_member(Person,groups)
                    try:
                        
                        wx_inst.send_text(to_user=Person.chatroom_id,msg=mess, at_someone=Person.wx_id)
                    except Exception as  e:
                        print(e)
                    print("Say welcome to {}".format(Person.nick_name))
                else:
                    pass
            else:
                pass
    

    这是两个杂项的功能,一个是获取所有的群成员wxid,另一个是用来向已有的列表中加入群成员。

    def get_all_id(List):
        id_list=[]
        for i in List:
            id_list.append(i.wx_id)
        return id_list
    def add_member(Person,member_groups):
        member_groups[Person.chatroom_id].append(Person)
    

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

    def main():
        print("初始化中...请稍候!")
        wx_inst=WechatPCAPI(on_message=onmessage)
        wx_inst.start_wechat(block=True)
        time.sleep(3)
        threading.Thread(target=thead_handle_mess,args=(wx_inst,)).start()
        wx_inst.update_frinds()
        Group_list=get_group_list()
        member_groups=get_existed_member(wx_inst,Group_list)
        print("运行中....")
        threading.Thread(target=thead_handle_getmember,args=(wx_inst,Group_list,)).start() 
        threading.Thread(target=thread_handle_member_welcome,args=(wx_inst,member_groups,)).start()
    
    def onmessage(message):
        queue_recved_message.put(message)
     #这是回调函数
    

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

    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.wx_id = ""
            self.nick_name = ""
    def onmessage(message):
        queue_recved_message.put(message)
    def thead_handle_mess(wx_inst):
        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 'member::chatroom' in message.get('type'):
                    Per=Person()#生成新的对象
                    Per.chatroom_id=message.get('data',{}).get('chatroom_id',"")
                    Per.wx_id = message.get('data', {}).get('wx_id', "")
                    Per.nick_name = message.get('data', {}).get('wx_nickname', "")
                    queue_Members.put(Per)
    def thead_handle_getmember(wx_inst,Group_list):
        while True:
            for group in Group_list:
                wx_inst.get_member_of_chatroom(group)
            time.sleep(60)
    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 get_existed_member(wx_inst,Group_list):
        member_groups={}
        for group in Group_list:
            wx_inst.get_member_of_chatroom(group)
        while queue_Members.empty():
            time.sleep(0.5)
        while not queue_Members.empty():
            Person=queue_Members.get()
            if Person.chatroom_id not in  member_groups.keys():
                member_group={Person.chatroom_id:[Person]}
                member_groups.update(member_group)
            elif Person.wx_id not in get_all_id(member_group[Person.chatroom_id]):
                member_group[Person.chatroom_id].append(Person)
        return member_groups
    def thread_handle_member_welcome(wx_inst,member_groups):
        groups=member_groups
        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.wx_id not in get_all_id(groups[Person.chatroom_id]):
                    add_member(Person,groups)
                    try:
                        
                        wx_inst.send_text(to_user=Person.chatroom_id,msg=mess, at_someone=Person.wx_id)
                    except Exception as  e:
                        print(e)
                    print("Say welcome to {}".format(Person.nick_name))
                else:
                    pass
            else:
                pass
    def main():
        print("初始化中...请稍候!")
        wx_inst=WechatPCAPI(on_message=onmessage)
        wx_inst.start_wechat(block=True)
        time.sleep(3)
        threading.Thread(target=thead_handle_mess,args=(wx_inst,)).start()
        wx_inst.update_frinds()
        Group_list=get_group_list()
        member_groups=get_existed_member(wx_inst,Group_list)
        print("运行中....")
        threading.Thread(target=thead_handle_getmember,args=(wx_inst,Group_list,)).start() 
        threading.Thread(target=thread_handle_member_welcome,args=(wx_inst,member_groups,)).start()
    def get_all_id(List):
        id_list=[]
        for i in List:
            id_list.append(i.wx_id)
        return id_list
    def add_member(Person,member_groups):
        member_groups[Person.chatroom_id].append(Person)
    if __name__ == "__main__":
        main()
    

    这个小程序还存在缺陷,下篇再写优化后的。
    Python实现微信自动欢迎新人入群(Ⅱ)

    新人写的不好,将就着看吧,如果有错误,请指出来,谢谢!

    相关文章

      网友评论

          本文标题:Python实现微信自动欢迎新人入群(Ⅰ )

          本文链接:https://www.haomeiwen.com/subject/lafdzctx.html