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

yipeiwu_com6年前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批量读取文件名并写入txt文件中

本文实例为大家分享了python批量读取文件名并写入txt中的具体代码,供大家参考,具体内容如下 先说下脚本使用的环境吧,在做项目的过程中需要动态加载图片,使用Unity的Resour...

详解Python中find()方法的使用

 find()方法判断字符串str,如果起始索引beg和结束end索引能找到在字符串或字符串的一个子串中。 语法 以下是find()方法的语法: str.find(str,...

浅谈Python由__dict__和dir()引发的一些思考

关于__dict__和dir()的区别和作用请参考这篇文章: 基于Python __dict__与dir()的区别详解 说下我当时遇到的问题: class Demo: def _...

手动实现把python项目发布为exe可执行程序过程分享

1. 手动制作python的exe可执行程序Python没有内建一个编译为exe的功能。给python程序的部署带来不少的麻烦。所以就会出现一些py2exe之类的很不错的工具,用于自动把...

python全栈知识点总结

全栈即指的是全栈工程师,指掌握多种技能,并能利用多种技能独立完成产品的人。就是与这项技能有关的都会,都能够独立的完成。 全栈只是个概念,也分很多种类。真正的全栈工程师涵盖了web开发、D...