Python使用wxpy模組實現微信兩兩群組消息同步

python使用wxpy模組提供的微信API介面實現兩兩群組的消息同步

 

安裝模組: pip install wxpy

注意:需要同步的微信群需要保存到通訊錄中

 

以下是自己閑來無事寫的程式碼,暫時還存在以下幾個問題,有能優化的大佬可以討論下:

1.暫時同步不了大文件,測試發現超過40M的文件無法同步;

2.頻發發送消息時可能導致有的消息丟失;

3.項目不穩定,有時會掉線,腳本需要重啟後重新登錄微信

 

直接上程式碼

import time
from wxpy import *

# 用同步的微信群,為雙重列表,最裡層列表為要同步的微信群,可以有多個
need_group = [['客戶1群', '技術1群'],
['客戶2群', '技術2群'],
['客戶3群', '技術3群'],
]

# 需要屏蔽的人
except_list = ["張三", "李四"]


# 保存搜索結果的對象雙重列表
group_obj_list = [[] for _ in range(len(need_group))]

# 初始化機器人,電腦彈出二維碼,用手機微信掃碼登陸
bot = Bot()

# 微信登陸後,更新微信群列表(包括未保存到通訊錄的群)
bot.groups(update=True, contact_only=False)

# 往微信助手發消息
bot.file_helper.send('wechat bot login success.')

# 查找群
try:
for i in range(len(need_group)):
     
     # 注意: 暫時發現需要搜索的群需要保存到通訊錄中
my_groups_Q1 = bot.groups().search(need_group[i][0])[0]
my_groups_Q2 = bot.groups().search(need_group[i][1])[0]

# 更新群消息
my_groups_Q1.update_group(members_details=True)
my_groups_Q2.update_group(members_details=True)

group_obj_list[i].append(my_groups_Q1)
group_obj_list[i].append(my_groups_Q2)

except:
pass


def send_message(msg, group_list):
try:
# 屏蔽某人
if msg.member.name not in except_list:
       # 使用API提供的函數同步消息
sync_message_in_groups(msg, group_list, prefix="")
except:
pass

# 暫時發現綁定監聽事件是阻塞事件,需要一個一個幫忙,用循環綁定的話只能綁定第一個

# 同步1群
@bot.register(group_obj_list[0], except_self=False)
def sync_my_groups_00(msg):

send_message(msg, group_obj_list[0])


# 同步2群
@bot.register(group_obj_list[1], except_self=False)
def sync_my_groups_01(msg):

send_message(msg, group_obj_list[1])


# 同步3群
@bot.register(group_obj_list[2], except_self=False)
def sync_my_groups_02(msg):

send_message(msg, group_obj_list[2])

# 每過30min往微信助手發送消息,不發則說明程式崩潰
while True:
DATE = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
bot.file_helper.send('程式運行中', DATE)
time.sleep(1800)
embed()
# 堵塞執行緒,讓機器人保持運行
bot.join()



同步微信群時默認的前綴為表情加微信名,如果想去掉的話,點擊進入sync_message_in_groups函數修改下源碼,如下圖