1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 实现微信向多好友定时发送信息

实现微信向多好友定时发送信息

时间:2018-08-15 10:35:40

相关推荐

实现微信向多好友定时发送信息

@TOC利用WeChat向好友定时发送关心及天气信息,表达自己对朋友的关心

第一篇博客,不喜欢不要说出来哈_

在闲暇之余,通过学习整理了一份可以向微信好友批量发送消息的脚本,包含的内容如下:

1、获取天气信息

2、获取关心数据

3、好友配置表

4、实现微信发送

5、实现定时发送

6、等等

看了很多有帮助的博客

1、python 每天在指定时间段运行程序及关闭程序

/weixin_35737303/article/details/99561792?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522159488554919725247647094%2522%252C%2522scm%2522%253A%25220713.130102334…%2522%257D&request_id=159488554919725247647094&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v3~pc_rank_v3-1-99561792.pc_ecpm_v3_pc_rank_v3&utm_term=python%E6%8C%87%E5%AE%9A%E6%97%B6%E9%97%B4%E6%89%A7%E8%A1%8C%E7%A8%8B%E5%BA%8F

2、写一个python定时发送消息的脚本——每天跟你女盆友说晚安(没有女朋友,说不定可以有哟)/weixin_41048363/article/details/79679987

@[TOC] 正文

现在进入正文

最终效果图展示

获取天气&关心消息

费话不多说,先上代码,共有3个文件,两个.py(一个获取信息,一个发送信息) ,一个.json

获取信息.py

下面展示一些内联代码片

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';def geturltext(xingming,html):#获取天气情况r = requests.get(html)r.raise_for_status()r.encoding = r.apparent_encodingtx = r.textaim = re.findall(r'<input type="hidden" id="hidden_title" value="(.*?)月(.*?)日(.*?)时(.*?) (.*?) (.*?) (.*?)"', tx)# airdata = re.findall(r'<li class="li6">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>', tx)ult_index = re.findall(r'<li class="li1">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</li>', tx)cloth_index = re.findall(r'<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</a>\n</li>\n<li class="li4">', tx)wash_index = re.findall(r'<li class="li4">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>', tx)txt1 = '[爱心]->看一看'+xingming+'的天气预报[爱心]'+'\n'+getYMD()+'\n'txt2 = '天气情况: '+aim[0][5]+'\n'+'温度情况: '+aim[0][6]+'\n'# txt3 = '空气指数: '+airdata[0][0]+', '+airdata[0][2]+'\n'txt4 = '紫外线指数: '+ult_index[0][0]+', '+ult_index[0][2]+'\n'txt5 = '穿衣指数: '+cloth_index[0][0]+', '+cloth_index[0][2]+'\n'txt6 = '洗车指数: '+wash_index[0][0]+', '+wash_index[0][2]+'\n'txt = '\n'+txt1+txt2+txt4+txt5+txt6return txt

关心消息

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';def get_iciba_everyday_chicken_soup(xingming):url = '/dsapi/'r = requests.get(url)all = json.loads(r.text)Englis = all['content']Chinese = all['note']everyday_soup = '[玫瑰]->喝一碗'+xingming+'的心灵鸡汤[玫瑰]'+'\n'+Englis+'\n'+Chinese+'\n'return everyday_soup

突发奇想写的一个装饰文本消息的方法(丑爆了)

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';def zhuangshi():ic = '[怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火]'ic1 = '[玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]'ic2 = '[爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心]'return ic+ic1+ic2

获取得系统日历信息

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';def getYMD():#获得对应的农历ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十"]rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十",u"十一", u"十二", u"十三", u"十四", u"十五", u"十六", u"十七", u"十八", u"十九",u"二十", u"廿一", u"廿二", u"廿三", u"廿四", u"廿五", u"廿六", u"廿七", u"廿八", u"廿九", u"三十", u"卅一"]Gan = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]Zhi = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]ShX = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]numCn = ["天", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]lunar = sxtwl.Lunar()year = datetime.datetime.now().yearmonth = datetime.datetime.now().monthrday = datetime.datetime.now().dayday = lunar.getDayBySolar(year, month, rday)d = str(day.y) + "年" + str(day.m) + "月" + str(day.d) + "日"if day.Lleap:a = "润" + ymc[day.Lmc] + "月" + rmc[day.Ldi] + "日"else:a = ymc[day.Lmc] + "月" + rmc[day.Ldi] + "日"b = "星期" + numCn[day.week]c = Gan[day.Lyear2.tg] + Zhi[day.Lyear2.dz] + "年" + Gan[day.Lmonth2.tg] + Zhi[day.Lmonth2.dz] + "月" + Gan[day.Lday2.tg] + Zhi[day.Lday2.dz] + "日"txt = '今天日期:'+d + ', ' + b + '\n'+'中华农历: ' + a + ', ' + creturn txt

向另一个py爆露了一个接口

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';#封装 以参数形式获取指定信息,爆露给其他程序def informationInterfaceParmer(callName,cityPoztion):code = getURLcode(cityPoztion)html = getURL(code)text = get_iciba_everyday_chicken_soup(callName) + geturltext(callName, html)# resault = zhuangshi()+text+zhuangshi()# print(resault)return zhuangshi()+""+text+""+zhuangshi()

附上获取信息全部代码

// An highlighted blockvar foo = 'bar';import json,re,datetimeimport requests,itchat,sxtwlimport os,sysdef zhuangshi():ic = '[怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火][怄火]'ic1 = '[玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]'ic2 = '[爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心][爱心]'return ic+ic1+ic2def getYMD():#获得对应的农历ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十"]rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十",u"十一", u"十二", u"十三", u"十四", u"十五", u"十六", u"十七", u"十八", u"十九",u"二十", u"廿一", u"廿二", u"廿三", u"廿四", u"廿五", u"廿六", u"廿七", u"廿八", u"廿九", u"三十", u"卅一"]Gan = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]Zhi = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]ShX = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]numCn = ["天", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]lunar = sxtwl.Lunar()year = datetime.datetime.now().yearmonth = datetime.datetime.now().monthrday = datetime.datetime.now().dayday = lunar.getDayBySolar(year, month, rday)d = str(day.y) + "年" + str(day.m) + "月" + str(day.d) + "日"if day.Lleap:a = "润" + ymc[day.Lmc] + "月" + rmc[day.Ldi] + "日"else:a = ymc[day.Lmc] + "月" + rmc[day.Ldi] + "日"b = "星期" + numCn[day.week]c = Gan[day.Lyear2.tg] + Zhi[day.Lyear2.dz] + "年" + Gan[day.Lmonth2.tg] + Zhi[day.Lmonth2.dz] + "月" + Gan[day.Lday2.tg] + Zhi[day.Lday2.dz] + "日"txt = '今天日期:'+d + ', ' + b + '\n'+'中华农历: ' + a + ', ' + creturn txtdef get_iciba_everyday_chicken_soup(xingming):url = '/dsapi/'r = requests.get(url)all = json.loads(r.text)Englis = all['content']Chinese = all['note']everyday_soup = '[玫瑰]->喝一碗'+xingming+'的心灵鸡汤[玫瑰]'+'\n'+Englis+'\n'+Chinese+'\n'return everyday_soupdef getURLcode(location):#获取城市对应的代码url = "/forecast/"r = requests.get(url)r.raise_for_status()r.encoding = r.apparent_encodingtxt = r.textloc = re.findall(r' target="_blank">[\u4e00-\u9fa5]{1,5}?</a></li>', txt)cod = re.findall(r' <li><a href="/weather1d/[0-9]{9}.shtml"', txt)loca, loca_1, code, code_1 = [], [], [], []a_cdict = {}for item in loc:loca.append(re.findall(r'target="_blank">(.*?)</a></li>', item))for i in range(len(loca)):loca_1.append(loca[i][0])loca_1.insert(47, '固原')#这个城市没有爬取到for item in cod:code.append(re.findall(r'[0-9]{9}', item))for i in range(len(code)):code_1.append(code[i][0])a_cdict = dict(zip(loca_1, code_1))return str(a_cdict[location])def getURL(code):#获取城市对应的链接url = '/weather/'+code+'.shtml'return urldef geturltext(xingming,html):#获取天气情况r = requests.get(html)r.raise_for_status()r.encoding = r.apparent_encodingtx = r.textaim = re.findall(r'<input type="hidden" id="hidden_title" value="(.*?)月(.*?)日(.*?)时(.*?) (.*?) (.*?) (.*?)"', tx)# airdata = re.findall(r'<li class="li6">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>', tx)ult_index = re.findall(r'<li class="li1">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</li>', tx)cloth_index = re.findall(r'<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</a>\n</li>\n<li class="li4">', tx)wash_index = re.findall(r'<li class="li4">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>', tx)txt1 = '[爱心]->看一看'+xingming+'的天气预报[爱心]'+'\n'+getYMD()+'\n'txt2 = '天气情况: '+aim[0][5]+'\n'+'温度情况: '+aim[0][6]+'\n'# txt3 = '空气指数: '+airdata[0][0]+', '+airdata[0][2]+'\n'txt4 = '紫外线指数: '+ult_index[0][0]+', '+ult_index[0][2]+'\n'txt5 = '穿衣指数: '+cloth_index[0][0]+', '+cloth_index[0][2]+'\n'txt6 = '洗车指数: '+wash_index[0][0]+', '+wash_index[0][2]+'\n'txt = '\n'+txt1+txt2+txt4+txt5+txt6return txtdef sentauto(nicheng,txt):itchat.login()result = itchat.search_friends(nickName=nicheng)user_name = result[0]['UserName']itchat.send_msg(txt, user_name)#封装 获取指定信息,爆露给其他程序#默认使用,自己调用def informationInterface():code = getURLcode("北京")html = getURL(code)text = get_iciba_everyday_chicken_soup("哥") + geturltext("哥", html)# resault = zhuangshi()+text+zhuangshi()# print(resault)return zhuangshi()+""+text+""+zhuangshi()#封装 以参数形式获取指定信息,爆露给其他程序def informationInterfaceParmer(callName,cityPoztion):code = getURLcode(cityPoztion)html = getURL(code)text = get_iciba_everyday_chicken_soup(callName) + geturltext(callName, html)# resault = zhuangshi()+text+zhuangshi()# print(resault)return zhuangshi()+""+text+""+zhuangshi()if __name__ =="__main__":informationInterface()

配置文件格式(friend.json)

注意(waring):

1、一定是昵称不能是微信号

2、城市只写名字就好,不要带”市“字,例如:北京市,就写北京

{

“friend1”:{“nickName”:“微信好友昵称”,“cityPoztion”:“所在城市”,“callName”:“与好友关系”}

}

发送.py

导入所以需要的库

// An highlighted blockvar foo = 'bar';from __future__ import import threading from datetime import tiimport datetime as dt from time import sleep from wxpy import *import json import windowimport multiprocessing

登录微信

// An highlighted blockvar foo = 'bar';bot = Bot(console_qr=2,cache_path='botoo.pk1')# bot = Bot(console_qr=True,cache_path=True)

设置程序在那个时间段可以运行

// An highlighted blockvar foo = 'bar';# 程序运行时间在白天7:47 到 7:58 晚上 20:01, 20:04DAY_START = time(7, 47) DAY_END = time(7, 58)NIGHT_START = time(20,1) NIGHT_END = time(20, 4)

获取消息文件内的信息

// An highlighted blockvar foo = 'bar';def get_news():# url = "/dsapi" # r = requests.get(url) # contents = r.json()['content'] # translation = r.json()['translation'] contents = window.informationInterface() #调用window模块攻取关心数据print(contents) return contents

向好友发送消息

// An highlighted blockvar foo = 'bar';def send_news(nickName,message): global t try:mfriend = bot.friends().search(nickName)[0] #朋友昵称 半夏おレ记忆 Christine 곽걸 洁儿 # mfriend.send(get_news()[0])#会发送多于的@符号,注掉则输出登录二维码时变慢 # mfriend.send(get_news()[1][5:]) mfriend.send(u'moring,早上好呀!') mfriend.send(message)mfriend.send(u'疫情期间出门要做好防护哟^_^') except: mfriend = bot.friends().search("发光如星")[0]mfriend.send(u'failed')

解析json文件,向json内的好友发送消息

// An highlighted blockvar foo = 'bar';#解析朋友js文件,向多人发送消息 def parseFriendInform():print("解析程序启动")file = open("./conf/information.json", encoding="utf-8") confJson = json.load(file) for i in confJson: j = confJson[i] for man in j: nickName = j['nickName'] cityPoztion = j['cityPoztion'] callName = j['callName'] # print(nickName,cityPoztion,callName) messige = window.informationInterfaceParmer(callName,cityPoztion)#天气信息 # messige = window.get_iciba_everyday_chicken_soup(callName)#关怀信息 send_news(nickName,messige)break #中断循环只调用一次

利用上面的时间段,定时发送,不要太频繁了,朋友 会烦的[捂脸]🤦‍♀️。

例如:下面这位[吐血],(反正她也看不见,就粘在这吧,😄😄😂)

// An highlighted blockvar foo = 'bar';#定时间段发送信息 def runTimerTick(): print("启动程式")print("------------------------优雅的分隔线---------------------------") other_process =None #是否有其他进程while True: current_time = datetime.now().time() print(current_time)parseFirentRunning = False #解析进程不可运行 if ((DAY_START <= current_time <= DAY_END) or (current_time >= NIGHT_START) and (current_time <= NIGHT_END)):#判断时间在解析进程运行时间段内parseFirentRunning = True#在时间段内开启解析进程 if parseFirentRunning and other_process is None: parser_process = multiprocessing.Process(target=parseFriendInform()) parser_process.start() print("解析进程启动成功,正在解析。") #非运行时间关闭解析进程 if not parseFirentRunning and other_process is not None: print("关闭解析进程,正在关闭") parser_process.terminate()parser_process.join()other_process = None print("解析进程关闭成功,关闭成功") sleep(500)print("------------------------优雅的分隔线---------------------------")

最重要的来了,开始运行吧

// An highlighted blockvar foo = 'bar';if __name__ == "__main__":print("程式开始运行") print("------------------------优雅的分隔线---------------------------") runTimerTick()

#附上发送类所有代码

// An highlighted blockvar foo = 'bar';from __future__ import unicode_literalsimport threadingfrom datetime import time,datetimeimport datetime as dtfrom time import sleepfrom wxpy import *import jsonimport windowimport multiprocessingbot = Bot(console_qr=2,cache_path='botoo.pk1')# bot = Bot(console_qr=True,cache_path=True)# 程序运行时间在白天7:03 到 7:10 晚上24:00 到 凌晨 24:01DAY_START = time(7, 47)DAY_END = time(7, 58)NIGHT_START = time(20,1)NIGHT_END = time(20, 4)def get_news():# url = "/dsapi"# r = requests.get(url)# contents = r.json()['content']# translation = r.json()['translation']contents = window.informationInterface() #调用过去消息模块攻取关心数据print(contents)return contents"""{"friend1":{"nickName":"半夏","cityPoztion":"南京","callName":"哥"},"friend2":{"nickName":"半夏","cityPoztion":"南京","callName":"哥"}}"friend4":{"nickName":"lb1402304","cityPoztion":"杭州","callName":"兄弟"},"""def send_news(nickName,message):global ttry:mfriend = bot.friends().search(nickName)[0] #朋友昵称 # mfriend.send(get_news()[0])#会发送多于的@符号,注掉则输出登录二维码时变慢# mfriend.send(get_news()[1][5:])mfriend.send(u'moring,早上好呀!')mfriend.send(message)mfriend.send(u'疫情期间出门要做好防护哟^_^')except:mfriend = bot.friends().search("**")[0] # **你的微信昵称mfriend.send(u'failed')#解析朋友js文件,向多人发送消息def parseFriendInform():print("解析程序启动")file = open("./conf/information.json", encoding="utf-8")confJson = json.load(file)for i in confJson:j = confJson[i]for man in j:nickName = j['nickName']cityPoztion = j['cityPoztion']callName = j['callName']# print(nickName,cityPoztion,callName)messige = window.informationInterfaceParmer(callName,cityPoztion)#天气信息# messige = window.get_iciba_everyday_chicken_soup(callName)#关怀信息send_news(nickName,messige)break #中断循环只调用一次#定时间段发送信息def runTimerTick():print("启动程式")print("------------------------优雅的分隔线---------------------------")other_process =None #是否有其他进程while True:current_time = datetime.now().time()print(current_time)parseFirentRunning = False #解析进程不可运行if ((DAY_START <= current_time <= DAY_END) or (current_time >= NIGHT_START) and (current_time <= NIGHT_END)):#判断时间在解析进程运行时间段内parseFirentRunning = True#在时间段内开启解析进程if parseFirentRunning and other_process is None:parser_process = multiprocessing.Process(target=parseFriendInform())parser_process.start()print("解析进程启动成功,正在解析。")#非运行时间关闭解析进程if not parseFirentRunning and other_process is not None:print("关闭解析进程,正在关闭")parser_process.terminate()parser_process.join()other_process = Noneprint("解析进程关闭成功,关闭成功")sleep(500)print("------------------------优雅的分隔线---------------------------")#定时间启动程序def runTimerTick2(h,m):second = 1while True:now = datetime.now().time()# print(now)# print(now.hour,now.minute)if(now.hour == h and now.minute == m):parseFriendInform()breaksleep(1)print(second)second+=1if __name__ == "__main__":print("程式开始运行")print("------------------------优雅的分隔线---------------------------")# runTimerTick2(19,00)runTimerTick()

以上是我写的些经验,大家可以借鉴,如有错误还行指正,请多包含呀!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。