Python3 itchat实现微信定时发送群消息的实例代码

yipeiwu_com7年前Python基础

一、简介

1,使用微信,定时往指定的微信群里发送指定信息。

2,需要发送的内容使用excel进行维护,指定要发送的微信群名、时间、内容。

二、py库

1,itchat:这个是主要的工具,用于连接微信个人账号接口。以下是一些相关的知识点网站。

2,xlrd:这个是用来读Excel文件的工具。

3,apscheduler:这个是用来定时调度时间的工具。

三、实例代码

# coding=utf-8
from datetime import datetime
import itchat
import xlrd
from apscheduler.schedulers.background import BlockingScheduler
import os
def SentChatRoomsMsg(name, context):
  itchat.get_chatrooms(update=True)
  iRoom = itchat.search_chatrooms(name)
  for room in iRoom:
    if room['NickName'] == name:
      userName = room['UserName']
      break
  itchat.send_msg(context, userName)
  print("发送时间:" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n"
    "发送到:" + name + "\n"
    "发送内容:" + context + "\n")
  print("*********************************************************************************")
  scheduler.print_jobs()
def loginCallback():
  print("***登录成功***")
def exitCallback():
  print("***已退出***")
itchat.auto_login(hotReload=True, enableCmdQR=True, loginCallback=loginCallback, exitCallback=exitCallback)
workbook = xlrd.open_workbook(
  os.path.join(os.path.dirname(os.path.realpath(__file__)), "chatroomsfile\AutoSentChatroom.xlsx"))
# workbook = xlrd.open_workbook("D:\PyCharmCode\AutoLiulishouWechat\chatroomsfile\AutoSentChatroom.xlsx")
sheet = workbook.sheet_by_name('Chatrooms')
iRows = sheet.nrows
scheduler = BlockingScheduler()
index = 1
for i in range(1, iRows):
  textList = sheet.row_values(i)
  name = textList[0]
  context = textList[2]
  float_dateTime = textList[1]
  date_value = xlrd.xldate_as_tuple(float_dateTime, workbook.datemode)
  date_value = datetime(*date_value[:5])
  if datetime.now() > date_value:
    continue
  date_value = date_value.strftime('%Y-%m-%d %H:%M:%S')
  textList[1] = date_value
  scheduler.add_job(SentChatRoomsMsg, 'date', run_date=date_value,
    kwargs={"name": name, "context": context})
  print("任务" + str(index) + ":\n"
    "待发送时间:" + date_value + "\n"
     "待发送到:" + name + "\n"
    "待发送内容:" + context + "\n"
     "******************************************************************************\n")
  index = index + 1
if index == 1:
  print("***没有任务需要执行***")
scheduler.start()

总结

以上所述是小编给大家介绍的Python3 itchat实现微信定时发送群消息的实例代码 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

举例讲解Python的lambda语句声明匿名函数的用法

所谓匿名函数,即是不需要定义函数,像表达式一样使用,不需要函数名(很多时候名字让我很困扰),一些简单的函数简单化, 举个例子 我需要两个整数相加的函数,通常是这么定义的 def ad...

python3调用R的示例代码

由于工作需要,在做最优分箱的时候,始终写不出来高效的代码,所以就找到了R语言中的最优分箱的包,这个时候考虑到了在python中调用R语言,完美结合。在国内的中文网站搜了半天,搭建环境的时...

使用XML库的方式,实现RPC通信的方法(推荐)

使用XML库的方式,实现RPC通信的方法(推荐)

1、先说结论:使用xml-rpc的机制可以很方便的实现服务器间的RPC调用。 2、试验结果如下: 3、源码如下: 服务器端的源代码如下: import operator, math...

Python装饰器用法实例分析

本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下: 无参数的装饰器 #coding=utf-8 def log(func): def wrapper():...

Python合并多个Excel数据的方法

Python合并多个Excel数据的方法

安装模块 1、找到对应的模块   http://www.python-excel.org/ 2、用pip install 安装 pip install xlrd p...