概述
Django+itchat+apscheduler实现向指定微信群和微信好友定时发送信息和文件。
想法的来源:每天需要在部门群中发送工作日报,有时候想早点休息但是又不想太早发送日报到群里(原因你懂得。。。),想着如果能够定时发送信息到群里汇报工作就好了,有个Python编写的微信自动控制包itchat很好用,可以使用很简单便捷的接口实现网页登录微信,向好友和微信群发送消息与文件,比较喜欢利用Django框架做Web端,同时有同事也希望使用这个功能,就做成了一个Web服务,定时任务使用apscheduler,这只是一个雏形,不过可以实现预期功能,代码写的不太好请见谅。
下面介绍一下具体做法:
后端使用Python3+Django2,编写了WeChatSendServer.py的文件并创建了一个自定义的WechatScheduler类,代码如下:
# 启动异步定时任务
import itchat
from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
from apscheduler.triggers.date import DateTrigger
import logging
# Get an instance of a logger
logger = logging.getLogger('collect')
class WechatScheduler(object):
def __init__(self, date_time, file_name, group_name, send_message):
self.mychat = itchat.Core()
self.date_time = date_time
self.file_name = file_name
self.group_name = group_name
self.send_message = send_message
def wechat_login_server(self):
# 主要实现获取登录二维码供用户登录
mychat = self.mychat
uuid = mychat.get_QRuuid()
print("uuid is ============", uuid)
qr_io = mychat.get_QR(enableCmdQR=2)
qr_io.seek(0)
return qr_io
def wechat_sendfile_server(self):
mychat = self.mychat
status = mychat.check_login()
if status == '200':
print("登录成功==============")
mychat.web_init()
mychat.show_mobile_login()
mychat.get_contact(True)
mychat.start_receiving()
scheduler = BackgroundScheduler()
# 调度器使用DjangoJobStore()
# scheduler.add_jobstore(DjangoJobStore(), "default")
trigger = DateTrigger(run_date=self.date_time)
# job = scheduler.add_job(send_file_by_time, trigger='date', next_run_time='2019-05-13 14:52:30')
job = scheduler.add_job(self.send_file_by_time, trigger)
print(job)
scheduler.start()
# job.remove()
return
def send_file_by_time(self):
# 根据设置的定时时间和指定的微信群或者好友,定时发送消息和文件
mychat = self.mychat
print("开始发送文件-----------------------》start")
group = mychat.get_chatrooms(update=True)
to_group = ' '
to_flag = ' '
for g in group:
if g['NickName'] == self.group_name: # 从群中找到指定的群聊
to_group = g['UserName']
to_flag = g['NickName']
break
print("群名称是===============》", to_group)
if to_flag == self.group_name and self.send_message != '':
mychat.send_msg(self.send_message, toUserName=to_group)
logger.info('有文字信息发送')
mychat.send_file(self.file_name, toUserName=to_group)
print("完成发送文件《-----------------------end")
return
elif to_flag == self.group_name:
mychat.send_msg(self.send_message, toUserName=to_group)
logger.info('无文字信息发送')
mychat.send_file(self.file_name, toUserName=to_group)
print("完成发送文件《-----------------------end")
return
else:
#发送个人
users = mychat.search_friends(self.group_name)
userName = users[0]['UserName']
print(userName)
mychat.send_msg(self.send_message, toUserName=userName)
logger.info('有文字信息发送')
res = mychat.send_file(self.file_name, toUserName=userName)
print("完成发送文件《-----------------------end")
return
同时编写了对应的Controller文件,WeChatSendController.py文件,代码如下:
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.shortcuts import HttpResponse, render, redirect
from .WechatSendServer import WechatScheduler
import os, base64
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger('collect')
wechatsend = WechatScheduler('2019-05-13 14:52:30', 'file_name', 'wechat_receive', '')
def wechat_set_controller(request):
response = {}
response['code'] = 0
response['message'] = 'success'
# POST
if request.method == 'POST':
logger.info('设置定时时间和任务')
file_name = request.FILES.get('file_name')
file_path = os.path.abspath(os.path.join("upload_dir", file_name.name))
print(file_path)
destination = open(file_path, 'wb+') # 打开特定的文件进行二进制的写操作
for chunk in file_name.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
date_time = request.POST.get('date_time')
wechat_receive = request.POST.get('group_name')
send_message = request.POST.get('send_message')
print("date_time is {0} and wechat_receive is {1} and send_message is {2}".format(date_time, wechat_receive,
send_message))
wechatsend1 = WechatScheduler(date_time, file_path, wechat_receive, send_message)
global wechatsend
wechatsend = wechatsend1
return JsonResponse(response)
def wechat_send_controller(request):
response = {}
response['code'] = 0
response['message'] = 'success'
# POST
if request.method == 'GET':
logger.info('获取登录二维码')
response['data'] = wechatsend.wechat_login_server()
res = HttpResponse(response['data'])
return res
def wechat_login_controller(request):
# wechatsend = WechatScheduler()
# mychat = wechatsend.mychat
response = {}
response['code'] = 0
response['message'] = 'success'
# POST
if request.method == 'GET':
logger.info('执行登录操作')
response['data'] = wechatsend.wechat_sendfile_server()
return JsonResponse(response)
对应urls.py文件代码如下:
from django.contrib import admin
from django.urls import path
from wechatsend.views import sendfile
from django.views.generic.base import TemplateView, RedirectView
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html')),
path('admin/', admin.site.urls),
path('setdate/', sendfile.WechatSendController.wechat_set_controller),
path('send/', sendfile.WechatSendController.wechat_send_controller),
path('login/', sendfile.WechatSendController.wechat_login_controller),
# path('index/', sendfile.WechatSendController.wechat_set_controller),
]
实现页面如下:
首先,指定微信群或者个人好友(微信群需要保存到通讯录)
然后,设置定时时间,推送内容,推送文件
然后,点击提交日报
再点击获取二维码,用手机微信扫描登录
最后再点击登录,这个时候会发现手机微信提示微信在网页登录了,到时间后相关内容将推送到微信群活好友。
具体代码可以私信找我要,仅供学习交流。
最后
以上就是风趣咖啡豆为你收集整理的Django+itchat+apscheduler实现向指定微信群和微信好友定时发送信息和文件的全部内容,希望文章能够帮你解决Django+itchat+apscheduler实现向指定微信群和微信好友定时发送信息和文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复