python开发微信定时发送消息接口
由于微信发送信息是需要先登录,而登录又需要二维码扫码。 所以保证微信不断线或被踢很关键。 曾不信邪,就最用戳的方法定时发送信息保证心跳,还是会在差不多20小时候被踢掉,并且需要再次用二维码扫码登录。
经过多次尝试后,还是妥协用到了多线程。 特将代码记录在这片博文中。
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import os
import os.path
import itchat,time
from itchat.content import TEXT
import datetime
import random
import _thread
#import threading
os.chdir("//网盘/***/项目目录")
GrpSleepName = '' # 心跳群
def resValue(res, name, val):
res1 = res.values()
j = 0
resV = False
for i in res1:
if j == 0 and val == i[name]:
resV = True
j = j + 1
return resV
# 自动回复
# 封装好的装饰器,当接收到的消息是Text,即文字消息
#@itchat.msg_register('Text') #1V1信息
@itchat.msg_register(TEXT, isGroupChat=True) #群信息
def text_reply(msg):
#global GrpName
sTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print ('接受到信息['+ sTime + ']')
def Send_weixin():
global GrpSleepName;
while 1:
if GrpSleepName != '':
print ("发送心跳群:" + GrpSleepName)
# 调用微信接口
itchat.send("我是机器人初代,心跳扑通扑通地", GrpSleepName)
# 休眠60分钟
#itchat.dump_login_status()
time.sleep(random.randint(3600,5400))
def login_weixin():
global GrpSleepName;
# 微信登录
if not resValue(itchat.load_login_status('itchat.pkl'), 'Ret', 0):
print("************************** 开启登录 **************************")
itchat.auto_login(hotReload=True) #源码中规定需要用回调函数。
#itchat.dump_login_status()
print("************************** 登录成功 **************************")
time.sleep(random.randint(4,9))
print("*********************** 获取目标群信息 ***********************")
sleepTo = '马甲群'
print ("发送心跳群:" + sleepTo)
# 获取自己的UserName
Groups = itchat.get_chatrooms(update=True)[0:]
for grp in Groups[1:]:
if sleepTo == grp.NickName:
GrpSleepName = grp.UserName
print ("发送心跳群:" + sleepTo + GrpSleepName)
print("**************************** RUN ****************************")
# 启动微信 长连进程
itchat.run()
def test(): #Use thread.start_new_thread() to create 2 new threads
_thread.start_new_thread(Send_weixin, ())
login_weixin() # 不需要单独启动新线程,因为内部本身就有触发一个新线程
if __name__=='__main__':
test()
浙公网安备 33010602011771号