Python实现某网站的微信营销群发实现

て烟熏妆下的殇ゞ 提交于 2019-12-14 01:09:19

某网站的微信营销群发实现

  • 抓取商品信息整理成图片带二维码的形式,最终形式类似淘宝上搜索的结果
  • 通过控制器发送特别款号,带款式说明,特性

大致就是itchat的使用与一些简单的抓包,另外还涉及到一些图片的处理,微信发图片有限制,之前有加过队列来处理,后面实际上使用很少

功能:从控制群发出指定款号,带上特别的信息,最后生成特定的图片发送到微信群,实现群控营销,可以批量发很多的群,群多的时候,发送消息的间隔要长一点,不然图片会被微信屏蔽,无法发出

# coding:utf-8

import itchat
import importlib
import sys
import time
import copy
from itchat.content import *
import json
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
import qrcode
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os.path
import random
import xlrd
import file as myFile
import multiprocessing as mp
from multiprocessing import Manager
#import multiprocessing Queue
import re

import requests

import os
os.makedirs('./image/', exist_ok=True)
os.makedirs('./infomation/', exist_ok=True)
os.makedirs('./codeImage/', exist_ok=True)
os.makedirs('./tempImage/', exist_ok=True)
os.makedirs('./WXCodeImage/', exist_ok=True)




global schedule;
global starttime;
global p;
global dumpfile;
global addflag;
global q;

# 二维码样式,1表示网站二维码,2表示小程序二维码,默认是网站二维码
codeType = 1
#
groomlist=[
'影儿商城-精品群-小杨',		#小杨					0
'影儿商城-会员1群-张金',		#张金					1
'影儿商城-会员2群-张金',		#张金					2
'发款群',
];

#推荐人id,可以改成自己的ID
memberid="1795466";
sendNickName="@小海"

#改群功能
sendgroup=u"发款群";

groupSources={};
infotip=u"长按查看商品详情"
insungroup='【恩裳】- 新零售二群';
zkqgroup='找款群'
#这个是发送任时间全局的,任务会一直增长
sendtime=0;
#这个是款号任务列表
tasklist=[];
#这个是查询到的信息列表
dictlist=[];
#这个是memberid列表
memberidset=set('1795466');
#这个是sheet里面的内容
contents=[];
insumSizeInfo=[];
result=[];
sendgoodids=[];
psalterids={};


#################
def initGroupSources():
	data={'roomid':'xxx','memberid':'1795466','flag':'1'};
	for group in groomlist:
		groupSources[group]=copy.deepcopy(data);

def setMemberId():
	groupSources['影儿商城-会员1群-张金']['memberid']='1795466';
	groupSources['影儿商城-会员2群-张金']['memberid']='1795466';
	# 小杨
	groupSources['影儿商城-精品群-小杨']['memberid']='1795466'; #小杨



	groupSources[sendgroup]['flag']=0

	groupSources[groomlist[0]]['flag']=1;
	groupSources[groomlist[1]]['flag']=1;
	groupSources[groomlist[2]]['flag']=1;



#memberidset
def initMemberidSet():
	memberidset=set();
	for r in groupSources:
		if len(groupSources[r]['roomid'])<10:
			continue;
		memberidset.add(groupSources[r]['memberid']);

#初绐化数据
def initData():
	# initSheetData();
	initGroupSources();
	setMemberId();
	initMemberidSet();


#读取款号
def readTaskList():
	pass
	# filename='/款号.txt';
	# file1 = myFile.File();
	# print("读取款号")
	# with file1.open(filename) as f:
	# 	for line in f:
	# 		line = myFile.delete_line_breaks(line)
	# 		if line not in tasklist:
	# 			tasklist.append(line);
	# 			print(line);


def resizeImg(souceimg):
	img = Image.open(souceimg)
	w,h = img.size;
	destw = 450.0
	rw = destw/w
	if w > h:
		rw = destw/w
	else:
		rw = destw/h

	nw = int(w*rw)
	nh = int(h*rw)
	img = img.resize((nw,nh),Image.ANTIALIAS)
	return img

def makeCodeWithHeaderImage(url,memberid):
	registerUrl = "http://mall.yingerfashion.com/yinger-m/index.html#/loginView?member_id=%s&store_id=%s"%('memberid','memberid')
	homeUrl = "http://mall.yingerfashion.com/yinger-m/index.html#/homeView?store_id=2674273"
	qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4)
	qr.add_data(url)
	qr.make(fit=True)

	img = qr.make_image()
	img = img.convert("RGBA")

	icon = Image.open("%s.jpg"%memberid)  # 这里是二维码中心的图片

	img_w, img_h = img.size
	factor = 4
	size_w = int(img_w / factor)
	size_h = int(img_h / factor)

	icon_w, icon_h = icon.size
	if icon_w > size_w:
	    icon_w = size_w
	if icon_h > size_h:
	    icon_h = size_h
	icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

	w = int((img_w - icon_w) / 2)
	h = int((img_h - icon_h) / 2)
	icon = icon.convert("RGBA")
	img.paste(icon, (w, h), icon)
	# img.show()   # 显示图片,可以通过save保存
	# img.save('xufeicode.png')
	return img

# tagName 精选秒杀
# def makeCodeImage(souceimg,url,title,price,memberid,buyCount,tagName='',features='',scheme_price='',goodid=''):
def makeCodeImage(souceimg, dict, amemberid='1795466'):

	url = dict['url'] + amemberid
	title = dict['title']
	price = dict['price']
	buyCount = dict['buyCount']
	tagName = dict['tagName']
	features = dict['features']
	scheme_price=dict['scheme_price']
	goodid = dict['id']
	memberid = amemberid
	#缩放图片
	offset = 20
	infoImg1 = resizeImg(souceimg)

	#二维码图片
	# qrimg = qrcode.make(url);
	qrimg=''

	# 这里是正常的网站的二维码
	if codeType==1:
		qrimg = makeCodeWithHeaderImage(url, memberid)
	# 这里是小程序的二维码
	else:
		qrimg = Image.open('./WXCodeImage/%s.png'%goodid)
		qrimg = alphabg2white_PIL(qrimg)
	# qrimg = makeCodeWithHeaderImage(url, memberid)
	qrimg=qrimg.resize((100,100),Image.ANTIALIAS);
	#原图片
	# infoImg=Image.open(souceimg);
	infoImg = infoImg1
	w1,h1=infoImg.size;

	# 商品图片写tag
	newfontTag=ImageFont.truetype('STZHONGS.TTF',16)
	if len(tagName) > 0:
		drawInfoImage = ImageDraw.Draw(infoImg)
		infow1,infoh1 = newfontTag.getsize(tagName)
		drawInfoImage.rectangle((w1-infow1-6,h1-infoh1-3,w1,h1), fill = (221,36,83))		
		drawInfoImage.text((w1-infow1-3,h1-infoh1-3),tagName,(255,255,255),newfontTag)

	w = 450
	h = 450
	W = 450+offset*2
	H = 450+150+offset*1
	#大白底照片
	whiteimg=Image.new('RGB',(w+offset*2,100+h+offset+25+20),'white');
	whiteimg.paste(infoImg,(int((450-w1)/2)+offset,int((450-h1)/2)+offset));
	whiteimg.paste(qrimg,(W-offset-100,h+25+offset));

	draw=ImageDraw.Draw(whiteimg);
	newfont=ImageFont.truetype('STXIHEI.TTF',18)
	newfont1=ImageFont.truetype('STXIHEI.TTF',26)


	context="影儿推广:"+memberid;
	context='长按查看商品详情'
	tw,th=newfont.getsize(context);
	tw1,th1=newfont1.getsize('123')
	#先算出文本信息的size
	infow,infoh=newfont1.getsize(infotip);

	#第一行文字
	firstline="";
	#第二行文字
	secondline="";

	start = 0
	end = len(title) - 1;
	pos=[];
	for n in range(1,end):
		ww,hh=newfont.getsize(title[start:n])
		if ww>w-100:
			start=n-1;
			pos.append(start);

	#影儿推广:1234567
	if len(pos)<=1:
		pos.append(len(title));

	firstline=title[0:pos[0]];
	if len(pos)>=2:
		secondline=title[pos[0]:pos[1]];

	draw.text((int((W-tw)/2),h+offset),context,(0,0,0),font=newfont);
	#标题信息
	draw.text((offset,offset+h+th+10),firstline,(0,0,0),font=newfont);

	#第二行,这里用来描写特性,  没有特性时,直接输出标题
	if len(secondline)>0 and len(features) ==0:
		draw.text((offset,offset+h+th+th+15),secondline,(0,0,0),font=newfont);

	#有特性时,输出特性
	if len(features)>0:
		draw.text((offset,offset+h+th+th+15),features,(221,36,83),font = ImageFont.truetype('STXIHEI.TTF',14));



	#常规价格
	# draw.text((offset,12+h+th+th+20+30+10),price,(250,10,0),font=newfont);
	# draw.text((offset,(H-offset-th1-10)),price,(250,10,0),font=newfont1);

	# 正常销售
	# price='¥'+str(ret['data'][0]['price']);
	# 团购

	priceLength,priceHeight = newfont1.getsize('¥'+price)
	# print(priceLength)
	if float(scheme_price) > 0:
		price1=str(int(float(price) - float(scheme_price)));
		draw.rectangle((offset-2,(H-offset-th1-10+3),offset+25,(H-offset-th1-10+3)+27), fill = (221,36,83));
		draw.text((offset,(H-offset-th1-12)),'团',(255,255,255),font=ImageFont.truetype('STXIHEI.TTF',24));
		# ¥
		draw.text((offset+27,(H-offset-th1-10)+8),'¥',(221,36,83),font=ImageFont.truetype('STXIHEI.TTF',18));
		draw.text((offset+27+15,(H-offset-th1-10)),str(price1),(221,36,83),font=ImageFont.truetype('STXIHEI.TTF',26));

		# 价格的长度
		tempt = priceLength + 8
		draw.text((offset+27+tempt,(H-offset-th1-10+13)),'日常价'+str(price),(221,36,83),font=ImageFont.truetype('STXIHEI.TTF',14));

		normalw1,normalh1 = ImageFont.truetype('STXIHEI.TTF',14).getsize('日常价'+str(price))

		draw.line([(offset+27+tempt-5,(H-offset-th1-10+13+10)),(offset+27+tempt+normalw1+5,(H-offset-th1-10+13+10))], fill = (221,36,83), width = 1)
		priceLength += 44+normalw1

	# 正常销售
	else:
		draw.text((offset,(H-offset-th1-10)+8),'¥',(221,36,83),font=ImageFont.truetype('STXIHEI.TTF',18));
		draw.text((offset+15,(H-offset-th1-10)),str(price),(221,36,83),font=ImageFont.truetype('STXIHEI.TTF',26));
		priceLength -= 10

	#已付款人数
	buyCountLine = '%s人已付款'%buyCount
	draw.text((offset + priceLength + 10,(H-offset-th1-10)+15),buyCountLine,(64,64,64),font=ImageFont.truetype('STXIHEI.TTF',12));


	#长按显示商品详情
	# draw.text((w-85-int(infow/2),h+100+10+th),infotip,(250,0,0),font=newfont1);

	#先去掉后缀
	souceimg=os.path.splitext(souceimg)[0];
	#得到文件名字
	filenamepath,filename=os.path.split(souceimg);

	whiteimg.save('./codeImage/'+filename+'_code'+memberid+'.png');
	#print("%s_%s code图片保存成功!"%(filename,memberid));
	# whiteimg.show()

# 填充图片白色
def alphabg2white_PIL(img):
    img=img.convert('RGBA')
    sp=img.size
    width=sp[0]
    height=sp[1]
    # print(sp)
    for yh in range(height):
        for xw in range(width):
            dot=(xw,yh)
            color_d=img.getpixel(dot)
            if(color_d[3]==0):
                color_d=(255,255,255,255)
                img.putpixel(dot,color_d)
    # img.show()
    return img

#保存图片文件
def downloadImage(url,filename,path='./image/'):
    r = requests.get(url)
    with open(path+filename+".png", 'wb') as f:
        f.write(r.content)
#    print("%s图片下载成功!"%filename);                  

def saveInfomation(dict):
    with open('./infomation/'+"infomation.txt",'ab+') as f:
        f.write(("------记录信息------"+"\n").encode('utf-8'));    	
        f.write((dict["id"]+"\n").encode('utf-8'));
        f.write((dict["title"]+dict["price"]+"\n").encode("utf-8"));
        f.write((dict["url"]+"\n").encode("utf-8"));  
        f.write((dict["imageUrl"]+"\n").encode("utf-8"));
        f.write(("------记录信息------"+"\n").encode('utf-8'));    	

def getAddressWithId(gid):
	r="http://mall.yingerfashion.com/yinger-m/index.html#/catListView?q=";
	return r+gid;
	

def showinfo(dict):
	print("标题:%s"%dict["title"]);
	print("价格:%s"%dict["price"]);
	print("图片:%s"%dict["imageUrl"]);
	print("链接:%s"%dict["url"]);

# 是否可以用优惠券
def getProductIdByGoodsId(goods_id):
	headers={
	 'Accept':'''application/json, text/plain, */*''',
	 'Origin':'''http://mall.yingerfashion.com''',
	 'Referer':'http://mall.yingerfashion.com/yinger-m/index.html',
	 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
	};

	url = 'http://mall.yingerfashion.com/yingers/tokans/tokan.php?method=mobileapi.products.get_products_list&goods_id=%s&member_id=1795466'%(goods_id)
	r = requests.get(url,headers = headers)
	# print(r.text)

	url = 'http://mall.yingerfashion.com/index.php/api?'+r.text
	r= requests.get(url)

	ret = json.loads(r.text)
	return (ret['data'][0]['product_id'])

def isCanCoupons(product_id):
	headers={
	 'Accept':'''application/json, text/plain, */*''',
	 'Origin':'''http://mall.yingerfashion.com''',
	 'Referer':'http://mall.yingerfashion.com/yinger-m/index.html',
	 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
	};

	products = '[{"product_id":'+product_id+',"num":1}]'
	params= {
	 'method':'mobileapi.orderCoupons.calculateOrderCoupons',
	 'member_id': '1795466', 
	 'products':products,
	 'is_prepay': 'false',
	 'prepay_id': 'undefined',
	 'collocation_id': '0'
	 }

	# 查看优惠券的
	url='http://mall.yingerfashion.com/yingers/tokans/tokan.php';

	r=requests.get(url,params=params,headers=headers);
	# print(r.text);


	# print(r.text)

	url='http://mall.yingerfashion.com/index.php/api'
	target =url+'?'+r.text
	# print(target)
	r = requests.get(target)
	ret=json.loads(r.text);
	# print(ret)
	# print(ret['data']['coupons'][0])
	if(ret['data']['coupons'][0]['active'] != 0):
		print('可以用券')
		return 1
	print('不可用券')
	return 0

# 获取商品的小程序二维码
def getMiniWXCode(gid, member_id='1795466'):
	headers={
	     "Content-Type":"application/x-www-form-urlencoded"
	};

	url = 'https://mall.yingerfashion.com/index.php/miniprogram/default/getWXACodeUnlimit?'

	data='page=packageGoods%2FgoodsDetailView%2Findex&width=400&is_hyaline=true&scene=gid%3D';
	mid='%26mid%3D'
	data = data+gid+mid+member_id
	r = requests.post(url,headers = headers, data=data)
	ret = json.loads(r.text)
	if ret['msg'] != 'success':
		print('二维码图片请求失败!!!')
		return
	host = 'http://mall.yingerfashion.com/'
	imgUrl = host + ret['data']['img_url']
	return imgUrl

def getInformations(goodid, comment, features):
	headers={
	 'Accept':'''application/json, text/plain, */*''',
	 'Origin':'''http://mall.yingerfashion.com''',
	 'Referer':'http://mall.yingerfashion.com/yinger-m/index.html',
	 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
	};
	#q=6C59299140&offset=0&limit=10&sort=&fq=&timestamp=1552151320&appkey=mmGdRIvDvY7E1hxX&sign=B8F1B66E8EE40FD2280DC00CFF5B86E2
	params= {
	 'q': goodid, 
	 'offset': '0',
	 'limit':'10',
	 'timestamp':str(time.time()),
	 'appkey':'mmGdRIvDvY7E1hxX',
	 #'sign':'B8F1B66E8EE40FD2280DC00CFF5B86E2',
	 'sign':'4478D67A7D106F205CB9B5F08980899C',
	 }

	url='https://zone.yingerfashion.com/api/mobile/Goods/getGoodsList/cors';

	r=requests.get(url,params=params,headers=headers);
	#print(r.text);

	ret=json.loads(r.text);
	#请求失败
	#print(ret);
	if ret['status']!='OK' or len(ret['data'])==0:
		return None;
# 'http://mall.yingerfashion.com/'+
	title=ret['data'][0]['name'];
	# 去掉一口价
	title = re.sub(r'【一口价\S*?】', '', title)

	# 正常销售
	price=str(ret['data'][0]['price']);
	# 团购
	# if float(ret['data'][0]['scheme_price']) > 0:
		# price='团购 '+str(int(float(ret['data'][0]['price']) - float(ret['data'][0]['scheme_price']))) + ' /日常  '+str(ret['data'][0]['price']);
	imageUrl=ret['data'][0]['image_default'][0];

	# 如果没有地址前缀,就加上去
	if imageUrl.find('http')==-1:
		imageUrl = 'http://mall.yingerfashion.com/' + imageUrl

	# imageUrl = imageUrl.replace('http://mall.yingerfashion.com/','')

#http://mall.yingerfashion.com/yinger-m/index.html#/detailView?goods_id=103075&member_id=1719359
	goodsurl='http://mall.yingerfashion.com/yinger-m/index.html#/detailView?goods_id='+ret['data'][0]['goods_id'];
	goodsurl=goodsurl+"&member_id=";

	#商品的gid码
	gid=ret['data'][0]['goods_id']
	WXCodeImageUrl = ''
	if codeType==2:
		WXCodeImageUrl = getMiniWXCode(gid)

	#购买人数
	buyCount = str(ret['data'][0]['buy_count']);
	tagName = ret['data'][0].setdefault('tag_name','')
	# 取第一个
	if len(tagName) > 0:
		tagName = tagName[0]

	# 先拿到product_id
	isCanCoupons1 = isCanCoupons(getProductIdByGoodsId(ret['data'][0]['goods_id']));
	
	for keyword in ret['data'][0]['keyword']:
		if keyword.find('秒杀')!=-1:
			tagName = '精选秒杀'
		if keyword.find('折上折')!=-1 and isCanCoupons1!=1:
			tagName = '2件8折'



	# 不是团购可以用券
	if isCanCoupons1==1 and ret['data'][0]['scheme_price'] <= 0:
		if len(features) > 0 :
			features = '可用券 | ' + features
		else:
			features = '可用券' + features

	# 不可以用券,不是团购
	if isCanCoupons1 != 1 and ret['data'][0]['scheme_price'] <= 0:
		tagName = '一口价'
	# print(features)

	dict = {'id':goodid,
	'title': title, 
	'price': price, 
	'url': goodsurl, 
	'imageUrl': imageUrl, 
	'comment':comment, 
	'buyCount':buyCount, 
	'tagName':tagName,
	'features':features, 
	'scheme_price':ret['data'][0]['scheme_price'],
	'isCanCoupons':isCanCoupons1,
	'WXCodeImageUrl':WXCodeImageUrl};

	return dict;

def queryinfo(goodid, comment, features):
	dict1=getInformations(goodid, comment, features);
	if dict1==None:
		return dict1;
	#showinfo(dict1);

	# 下载商品图片
	downloadImage(dict1["imageUrl"], dict1["id"]);
	# 下载商品小程序二维码
	if codeType==2:
		downloadImage(dict1["WXCodeImageUrl"], dict1['id'], path = "./WXCodeImage/")
	# saveInfomation(dict1);
	#time.sleep(2);
	return dict1;
#################

def lc():
    print('开始登陆')
def ec():
    print('退出登陆')


def getrooms():
	rooms = itchat.get_chatrooms(update=True);
	for r in rooms:
		if r['NickName'] in groomlist:
			temp=r['NickName'];
			print(temp);
			groupSources[temp]['roomid']=r['UserName'];
	return groupSources;

def addMsg(dict):
	global addflag;

	if dict is None:
		return;
	global dumpfile;
	i=0;
	count=0;
	sendgoodids.append(dict['id']);
	dumpfile.dump(sendgoodids,'已发送款号记录');
	print("添加发送消息任务款号:%s"%dict['id']);
	#表示暂时不需要添加消息了
	addflag.value = 0;
	for r in groupSources:
		if len(groupSources[r]['roomid'])<10 or groupSources[r]['flag']==0:
			continue;
		#添加发送消息任务,随机秒数
		i=i+random.randint(5,10);
		count=count+1;
		schedule.add_job(func=sendgroupmesaage,args=(r,dict),trigger='date',next_run_time=datetime.datetime.now()+datetime.timedelta(seconds=1+i));
		
	#print(u"-----------发送结束------------");
	#print("添加 %d 条消息任务" % (count));		

#给单独一个群发消息
def sendgroupmesaage(groupname,dict):
	global dumpfile;
	global addflag;

	gid=dict['id'];
	imagepath="./image/"+gid+".png";
	# title=dict["title"]+"\n"+dict["price"];
	title=dict["price"];

	url=dict["url"]
	sstr="@img@"+'./codeImage/'+gid+'_code'+groupSources[groupname]['memberid']+'.png';

	# 活动
	sales = '💢【双十二嘉年华:12/06-12/13】💢\n'
	# sales = ''
	comment='【私聊下单有惊喜~】\n'
	if len(dict['comment'])>0:
		comment+='\n'+dict['comment']+'\n'+'\n'
	print(u"开始发送:%s 群消息,商品款号:%s--%s" % (groupname,gid,time.strftime("%H:%M:%S",time.localtime())));

	itchat.send(sstr,groupSources[groupname]['roomid'])
	time.sleep(1);
	itchat.send(sales + comment+"【购买链接】\n"+url+groupSources[groupname]['memberid'], groupSources[groupname]['roomid'])
	result.append("开始发送:%s 群消息,商品款号:%s,%d" % (groupname,gid,time.time()-starttime));

	overmsg='系统消息: %s 消息已全部发送完成'%(dict['id']);
	if len(schedule.get_jobs())==0:
		addflag.value = 1;
		print("-----------发送结束------------");
		dumpfile.dump(result,'发送报告');
		if len(dictlist)>0 :
			addMsg(dictlist.pop(0));
		else:
			print("-----------当前没有任务列表为空-----------");
			

#是否是查询信息,检查一下
def isQueryMsg(msg):

	strarr = msg.text.split('#')
	# print(strarr)
	strmsg=strarr[0]
	if msg.text.find(sendNickName)==-1:
		return '';

	# strmsg=msg.text;
	#去掉@名字
	strmsg=strmsg.replace(sendNickName,"");
	#大写
	strmsg=strmsg.upper();
	strmsg=strmsg.strip();

	gid=strmsg;
	l=len(strmsg)
	if l>=10:
		strmsg=strmsg[l-10:]
		pass
	#取数字
	t=strmsg[2:];

	gid=strmsg;
	if (len(gid)>=8) and (t.isdigit()):
		return gid.upper();

	# 这里没有限制了
	return strmsg.upper();



#生成群图片所需要的二维码推广图片
def makeGroupCodeImage(dict):
		imagepath="./image/"+dict['id']+".png";
		#这里先得到memberid

		# 这里有推广图片
		if os.path.exists('./sales/%s.png'%dict['id']):
			imagepath="./sales/"+dict['id']+".png"
		if os.path.exists('./sales/%s.jpg'%dict['id']):
			imagepath="./sales/"+dict['id']+".jpg"

		smems=set();
		for r in groupSources:
			if len(groupSources[r]['roomid'])<10:
				continue;
			smems.add(groupSources[r]['memberid']);
		
		#memberid,不同的memberid 图片不同
		for r in smems:
			makeCodeImage(imagepath, dict, r);	


#小钟群里面的消息
def dealXiaoZhongQunMsg(msg):
	gid=isQueryMsg(msg);
	strarr = msg.text.split('#')
	comment=''
	features=''

	# 取点评
	if len(strarr)>1:
		comment = strarr[1]

		#取特性,,,款号#评论#特性
		if len(strarr)==3:
			features = strarr[2]

	if len(gid)<8:
		return;

	global p;
	global q;
	print(gid);
	p.apply_async(processQuery(gid,0,comment,features));
#	print("添加任务成功");
	return '添加---%s---任务成功,等待任务执行'%gid

# 带对象参数注册,对应消息对象将调用该方法
# 文本消息
@itchat.msg_register(TEXT,isGroupChat=True)
def text_reply(msg):

	FromUserName = msg['FromUserName'];

	if msg.text.find(sendNickName)==-1:
		return;
	#这里处理控制总群的消息
	if msg['FromUserName']==groupSources[sendgroup]['roomid']:
		return dealXiaoZhongQunMsg(msg);

	return;

# 统一发群消息
# '影儿商城-精品群-小杨',		#小杨					5
# '影儿商城-会员1群-张金',	#张金					6
# '影儿商城-会员2群-张金'
@itchat.msg_register(TEXT, isGroupChat = False)
def repeatTEXT(msg):
	if msg['User']['NickName'].find('影儿小杨')!=-1 or  msg['User']['NickName'].find('影儿张金')!=-1:

		print('接收到文本消息:%s'%msg.text)
		# itchat.send(msg.text, groupSources[sendgroup]['roomid'])
		itchat.send(msg.text, groupSources['影儿商城-精品群-小杨']['roomid'])
		time.sleep(0.5)
		itchat.send(msg.text, groupSources['影儿商城-会员1群-张金']['roomid'])
		time.sleep(0.5)
		itchat.send(msg.text, groupSources['影儿商城-会员2群-张金']['roomid'])

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat = False)
def repeatOther(msg):
	if msg['User']['NickName'].find('影儿小杨')!=-1 or  msg['User']['NickName'].find('影儿张金')!=-1:

		msg.download('./tempImage/'+msg.fileName)
		typeSymbol={
			PICTURE: 'img',
			VIDEO: 'vid', }.get(msg.type, 'fil');

		vvstr='@%s@%s'%(typeSymbol, './tempImage/' + msg.fileName)
		print('接收到图片视频消息:%s'%vvstr)
		# itchat.send(msg.text, groupSources[sendgroup]['roomid'])
		itchat.send(vvstr, groupSources['影儿商城-精品群-小杨']['roomid'])
		time.sleep(0.5)
		itchat.send(vvstr, groupSources['影儿商城-会员1群-张金']['roomid'])
		time.sleep(0.5)
		itchat.send(vvstr, groupSources['影儿商城-会员2群-张金']['roomid'])



def showdictlist(list):

	print('----任务列表----')
	i=0;
	for r in list:
		i=i+1;
		print(str(i)+' : '+r['id']);
	print('----任务列表----')


#进程查询函数
def processQuery(gid,insert, comment, features):
	print("%d 进程处理查询"%os.getpid())
#	print("gid=%s,insert=%d"%(gid,insert));
	if len(gid)<8:
		return;
	dict = queryinfo(gid, comment, features);
	if dict==None:
		print("款号: %s 未找到!"%gid);
		return;

	#去重
	for dic in dictlist:
		if dict['id']==dic['id']:
			dictlist.remove(dic);


	if insert==-1:
		dictlist.append(copy.deepcopy(dict));
		showdictlist(dictlist);

	else:
		dictlist.insert(0,copy.deepcopy(dict));
		showdictlist(dictlist);
	#生成推广图片
	makeGroupCodeImage(dict);

#	if q.full()==False:
#		q.put(dictlist.pop(0))
	#开始发送任务
	if len(dictlist)>0 and addflag.value ==1:
		addMsg(dictlist.pop(0));

#用一个进程来读发送款号的字典
def processAddMsg(q):
#	print('正在运行 %s'%os.getpid());
	global addflag;
	while True:
#		print('读取任务列表');
		time.sleep(3);
		#可以添加标记
		#如果可以添加发送消息款号
		if addflag.value==1:
			if q.empty() == False:
				try:
					ret = q.get();
					addMsg(ret);
				except Exception as e:
					print(e)
				finally:
					pass

def main():
	global schedule;
	global starttime;
	global p;
	global dumpfile;
	global addflag;
	global q;

	addflag = Manager().Value('d',1);
	dictlist=Manager().dict();
	dumpfile = myFile.File();


	initData();
	#读取任务列表
	# readTaskList();

	itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec)

	# 获取好友列表
	getrooms();
	setMemberId();
	starttime=time.time();

	#启动任务系统
	schedule=BackgroundScheduler();
	schedule.start();

	#开启进程查询款号
	p = mp.Pool(2);
#	q = mp.Manager().Queue();

	#向进程添加任务,异步执行
	for gid in tasklist:
		p.apply_async(processQuery(gid,-1,''));

#	p1=mp.Process(target=processAddMsg,args=(q,));
#	p1.start();
#	p.apply_async(processAddMsg,(q,));



	itchat.run();

if __name__ == '__main__':
	main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!