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

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实现微信自动欢迎新人入群(Ⅱ)

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容