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求脱单啊

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

中国加油,武汉加油!!

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

推荐阅读更多精彩内容