Django+itchat+apscheduler实现向指定微信群和微信好友定时发送信息和文件

news/2025/3/5 12:29:09/

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_timeself.file_name = file_nameself.group_name = group_nameself.send_message = send_messagedef wechat_login_server(self):# 主要实现获取登录二维码供用户登录mychat = self.mychatuuid = mychat.get_QRuuid()print("uuid is ============", uuid)qr_io = mychat.get_QR(enableCmdQR=2)qr_io.seek(0)return qr_iodef wechat_sendfile_server(self):mychat = self.mychatstatus = 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()returndef send_file_by_time(self):# 根据设置的定时时间和指定的微信群或者好友,定时发送消息和文件mychat = self.mychatprint("开始发送文件-----------------------》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']breakprint("群名称是===============》", 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")returnelif 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")returnelse:#发送个人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'] = 0response['message'] = 'success'# POSTif 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 wechatsendwechatsend = wechatsend1return JsonResponse(response)def wechat_send_controller(request):response = {}response['code'] = 0response['message'] = 'success'# POSTif request.method == 'GET':logger.info('获取登录二维码')response['data'] = wechatsend.wechat_login_server()res = HttpResponse(response['data'])return resdef wechat_login_controller(request):# wechatsend = WechatScheduler()# mychat = wechatsend.mychatresponse = {}response['code'] = 0response['message'] = 'success'# POSTif 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, RedirectViewurlpatterns = [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),
]

实现页面如下:

首先,指定微信群或者个人好友(微信群需要保存到通讯录)

然后,设置定时时间,推送内容,推送文件

然后,点击提交日报

再点击获取二维码,用手机微信扫描登录

最后再点击登录,这个时候会发现手机微信提示微信在网页登录了,到时间后相关内容将推送到微信群活好友。

具体代码可以私信找我要,仅供学习交流。

 


http://www.ppmy.cn/news/713251.html

相关文章

Python | 1 行代码,实现微信消息发送

还是接之前「食行生鲜」签到的问题,之前我们讲到,将签到结果通过短信发送到手机,但是我发现 twilio 有些不稳定,为了防止漏签,我在服务器上设置了两次定时任务,通常情况下第一个收不到短信,第二…

Python程序员的浪漫-实现每天定时给Ta推送微信公众号消息提醒(超详细教程)

前段阵子,小🍠平台刷到热门视频,程序员男朋友给她实现了每天定时推送消息给她,其中内容包含当地的天气情况、在一起多少天了,离她过生日还有多少天等信息,她开心不得于是发了小🍠平台觉得很浪漫…

php微信公众号发送多条消息模板,整合ThinkPHP功能系列之微信公众号模板消息发送...

模板消息还是在商城类的微信项目中使用比较多,模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如绑定手机号通知,商品购买成功通知等,不支持广告等营销类消息以及其它所有可能对用户造…

个人微信开发api文档

个人微信开发api文档 个人微信开发api文档,个人微信开发sdk,个人微信开发协议接口 微信开发sdk服务端调用接口 1、基础消息类型 1、客户端发送的心跳包 HeartBeatReq 1001; 2、消息接收确认回复(接收或拒绝接收) MsgReceivedAck…

钉钉如何群里定时发送文件_简单好用的钉钉群消息助手

点击上方"IT牧场",选择"设为星标" 技术干货每日送达! 我们常常会遇到向钉钉群中发送消息的需求,所以我开源了一个钉钉群消息助手。 瓦力 瓦力是一个轻量级的钉钉群消息发送助手,通过瓦力你只需要配置一个发送消息的模板(支持多个地址,且可以在运行时动…

python 发送微信语音消息_全网最全的Windows下Anaconda2 / Anaconda3里Python语言实现定时发送微信消息给好友或群里(图文详解)...

不多说,直接上干货! 缘由: (1)最近看到情侣零点送祝福,感觉还是很浪漫的事情,相信有很多人熬夜为了给爱的人送上零点祝福,但是有时等着等着就睡着了或者时间并不是卡的那么准就有点强迫症了,这是也许程序会解决我们的问题。 (2)如果你女朋友需要天天给她微信发“晚安”,…

用python实现微信定时发文

-如果你女朋友需要天天给她微信发“晚安”,你一般怎么做呢? -每天用手机敲出来 -忘记了怎么办? -设个闹钟 -哥不扶墙,就服你 作为程序员哥哥,你如果再怎么low,那就有点愧对你的身份了。一想&#xff0…

使用树莓派定时给微信群发消息

需求强烈 单位领导要求在微信群天天定时汇报个人情况,此处个人情况内容是固定的(这个很重要)。春节过年,哪能天天记着去发微信,而且心理惦记个事也是很难受的,因此决定看看能不能开发程序解决!…