使用Python itchat接口对自动对微信群朋友定时问候(发送天气预报、黄历、每日一句)_cskywit的博客-程序员宅基地

技术标签: Python  

      itchat是一个支持微信控制的接口,可以对发送和接收的微信消息进行定制,网上有很多现成的实例,该API的使用可以参考http://itchat.readthedocs.io/zh/latest/,上面写得很详细,并且有实例,本文在此基础上参考了网络上的部分代码,完成每天上午自动对几个群的朋友进行问候,发送问候语、黄历和每日一句。其中黄历使用了极数据的黄历接口,见https://www.jisuapi.com/,但是该接口有使用100次的限制,也可以使用聚合数据接口,这个没有次数限制。每日一句使用了爱词霸的每日一句接口,网上有很多例子可供参考。天气预报使用了中国天气网数据,将城市代码换成自己所在城市的即可。代码比较简单,使用Pyhton3.6,功能已实现,贴出来供参考,下一步工作是将杂乱的功能函数封装成类,使代码更加紧凑。

     安装itchat方法:pip install itchat

    代码如下:

# coding=utf-8
from datetime import datetime
import itchat
from apscheduler.schedulers.background import BlockingScheduler
import  json
import  urllib.request
import requests
from urllib.parse import urlencode


cityList_bsgs = [
    {'code':'101290801','name':"楚雄"}
]
chatroom_list =['男朋友们','女朋友们']

def get_huangli():
    data = {}
    data["appkey"] = "换成自己的key"
    data["year"] = datetime.now().year
    data["month"] = datetime.now().month
    data["day"] = datetime.now().day
    url_values = urlencode(data)
    url = "http://api.jisuapi.com/huangli/date" + "?" + url_values
    r = requests.get(url)
    jsonarr = json.loads(r.text)
    if jsonarr["status"] != u"0":
        print(jsonarr["msg"])
        exit()
    result = jsonarr["result"]
    content1='天干地支:' + ','.join(result['suici'])
    content2='今日应当注意的生肖:' + result["chong"]
    content3='宜:' + ','.join(result['yi'])
    content4='忌:' + ','.join(result['ji'])
    return '今日黄历:'+content1+'\n'+content2+'\n'+content3+'\n'+content4

def get_iciba():
    url = 'http://open.iciba.com/dsapi/'
    r =requests.get(url)
    content = json.loads(r.text)
    return '每日一句:\n'+content['content'] +'\n'+content['note']

def getCityWeather_RealTime(cityID):
    url = "http://www.weather.com.cn/data/sk/" + str(cityID) + ".html"
    try:
        stdout = urllib.request.urlopen(url)
        weatherInfomation = stdout.read().decode('utf-8')

        jsonDatas = json.loads(weatherInfomation)

        city        = jsonDatas["weatherinfo"]["city"]
        temp        = jsonDatas["weatherinfo"]["temp"]
        fx          = jsonDatas["weatherinfo"]["WD"]        #风向
        fl          = jsonDatas["weatherinfo"]["WS"]        #风力
        sd          = jsonDatas["weatherinfo"]["SD"]        #相对湿度
        tm          = jsonDatas["weatherinfo"]["time"]

        content = city +" " + temp + "℃ " + fx + fl + " " + "相对湿度" + sd + " "  + "发布时间:" + tm
        twitter = {'image': "", 'message': content}

    except (SyntaxError) as err:
        print(">>>>>> SyntaxError: " + err.args)
    except:
        print(">>>>>> OtherError: ")
    else:
        return twitter
    finally:
        None

#返回dict类型: twitter = {'image': imgPath, 'message': content}
def getCityWeather_AllDay(cityID):
    url = "http://www.weather.com.cn/data/cityinfo/" + str(cityID) + ".html"
    try:
        stdout = urllib.request.urlopen(url)
        weatherInfomation = stdout.read().decode('utf-8')
        jsonDatas = json.loads(weatherInfomation)

        city        = jsonDatas["weatherinfo"]["city"]
        temp1       = jsonDatas["weatherinfo"]["temp1"]
        temp2       = jsonDatas["weatherinfo"]["temp2"]
        weather     = jsonDatas["weatherinfo"]["weather"]
        img1        = jsonDatas["weatherinfo"]["img1"]
        img2        = jsonDatas["weatherinfo"]["img2"]
        ptime        = jsonDatas["weatherinfo"]["ptime"]

        content = city + "," + weather + ",最高气温:" + temp2 + ",最低气温:"  + temp1
        twitter = {'image': "icon\d" + img1, 'message': content}

    except (SyntaxError) as err:
        print(">>>>>> SyntaxError: " + err.args)
    except:
        print(">>>>>> OtherError: ")
    else:
        return twitter
    finally:
        None

def get_context():
    for city in cityList_bsgs:
        title_small = "[楚雄实时天气预报]"
        twitter = getCityWeather_RealTime(city['code'])
        print(title_small + twitter['message'])
        twitter_realTime = title_small + twitter['message']

    for city in cityList_bsgs:
        title_small = "[楚雄全天天气预报]"
        twitter = getCityWeather_AllDay(city['code'])
        print(title_small + twitter["message"])
        twitter_wholeDay = title_small + twitter["message"]
    return "美好的一天从我的问候开始:各位亲人早上好!\n"+twitter_realTime+"\n"+twitter_wholeDay+'\n'+get_huangli()+'\n'+get_iciba()

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")
    print("发送到:" + name + "\n")
    print("发送内容:" + context + "\n")
    print("*********************************************************************************")
    scheduler.print_jobs()

def loginCallback():
    print("***登录成功***")

def exitCallback():
    print("***已退出***")

itchat.auto_login(hotReload=True, enableCmdQR=True, loginCallback=loginCallback, exitCallback=exitCallback)
scheduler = BlockingScheduler()
#name = '老寸家'
#context =get_context()
for sent_chatroom in chatroom_list:
    scheduler.add_job(SentChatRoomsMsg, 'cron', day_of_week ='0-6',hour =7,minute =30,kwargs={"name": sent_chatroom, "context": get_context()})
    print("任务" + ":\n"+"待发送到:" + sent_chatroom + "\n"+"待发送内容:" + get_context() + "\n")
    print("******************************************************************************\n")

scheduler.start()

       以上是在Windows上的实现,由于想每天上午7点半在微信群自动问候:所以需要部署在服务器上,这里选择腾讯云Ubuntu服务器,在部署过程中遇到的问题是,服务器没有图形界面,itchat需要用二维码登录微信,在终端上打印出来的二维码不完整,没法登录,后来将登录部分代码调整如下,问题得到解决:

#若为Linux服务器如下,否则二维码显示不正常。如部分的linux系统,块字符的宽度为一个字符(正常应为两字符),故赋值为2
itchat.auto_login(hotReload=True, enableCmdQR=2, loginCallback=loginCallback, exitCallback=exitCallback)

后面遇到的问题是:执行python weixin.py &后程序执行,但关闭终端后程序自动退出,解决如下:

使用以下命令执行:nohup python -u weixin.py &

可以使用tail -f nohup.out查看程序执行情况,这样就可以关闭远程连接让程序自动执行了。

第二天早上七点半,两个微信群准时收到了使用我的微信账号自动发送的问候消息:

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cskywit/article/details/81506517

智能推荐

java 聊天机器人_用Java实现基于Web端的AI机器人聊天-程序员宅基地

本文详细介绍了如何用Java实现Web聊天机器人。通过创建一个新项目来学习一下!一、创建一个新项目添加所需的依赖项打开pom.xml文件在IDE中将下列内容添加到区域 JCenterhttps://jcenter.bintray.com将下列内容添加到区域org.goldrenardab1.0.7org.vaadin.arturavataaar1.0.0二、实现bot逻辑bot逻辑是用人工智能标记..._智能对话机器人 web

iOS学习笔记——ARC两三事(strong、weak详解,ARC与非ARC混编)_非 arc项目能用strong吗-程序员宅基地

本文为博主原创,转载请注明出处:最近项目开始使用ARC进行编程,起初并不是很喜欢ARC,总感觉自己管理内存更加踏实一些,但用了之后才发现ARC真是太方便了,不用再去花时间思考对象该不该被释放了,这样就能更专注于业务逻辑的编写。ARC中抛弃了属性原有的关键字retain和assign。使用了全新的strong、weak和unsafe_unretained。stro_非 arc项目能用strong吗

Springboot整合Web(Servlet,Filter,Listener)_spring boot webserlet 并加入web listener_喜气..._...-程序员宅基地

Springboot整合Web一:Springboot整合Servlet1通过注解扫描完成Servlet组件的注册package com.lidadaibiao.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebSer..._spring boot webserlet 并加入web listener_喜气..._...

Low-fragmentation Heap-程序员宅基地

Heap fragmentation is a state in which available memory is broken into small, noncontiguous blocks. When a heap is fragmented, memory allocation can fail even when the total available memory in the he...

IDEA 启动时生成图案_idea 控制台图案-程序员宅基地

如何更改启动时显示的字符拼成的字母,SpringBoot呢?也就是 banner 图案;只需一步:到项目下的 resources 目录下新建一个banner.txt 即可。图案可以到:https://www.bootschool.net/ascii 这个网站生成,然后拷贝到文件中即可!..._idea 控制台图案

jQuery实现的上下滚动公告栏详细讲解-程序员宅基地

之前做项目的时候,一直都想着做一个上下滚动的公告栏,作为展示网站的最新公告信息,因为刚开始自己的思路并不是太清晰,在网上找了很多的源码,但是却发现都不能让自己满意,有的还会出现一些小问题,比如,有时候公告上下滚动的时候,两条公告会重叠在一起。最后我还是决定自己写一个上下滚动的公告栏。jQuery实现上下滚动公告栏原理虽然在网上找的有些代码有时候会出现一些问题,但是思路咱还是可以借...

随便推点

unity android 打包后运行卡在Made with unity 画面_unity打包安卓 启动卡住-程序员宅基地

logcat 不显示任何错误LOG。编辑器模式下运行无碍。emm..检查发现是调用了高德封装的API中一个单例常量屏幕宽高。在声明全局变量时候就直接调用了,大概类似这样:float notInsClam= AMap.Instance.height * 0.3f;//分配模型范围这样出现问题其实是很好理解的,因为屏幕宽高一定是在程序运行后才取到的,所以先后顺序出了问题得话,这个值就赋不上了。为什么编辑器模式下可以运行呢,我猜可能是Windows和Android处理逻辑和顺序有差异吧_unity打包安卓 启动卡住

IDEA中的RunDashBoard使用_找到 .idea 下面的 workspace.xml_小小平不平凡的博客-程序员宅基地

找到.idea下面的workspace.xml文件,在xml找到RunDashboard组件,如下图所示添加如下option内容<option name="configurationTypes"> <set> <option value="SpringBootApplicationConfigurationType" /> </set></option>..._找到 .idea 下面的 workspace.xml

python Unicode转ascii码的一种方法-程序员宅基地

缘起看到这样的数据:Marek Čech、Beniardá怎样变成相对应的ascii码呢解决import unicodedatas = u"Marek Čech" #(u表示是unicode而非 ascii码,不加报错!)line = unicodedata.normalize('NFKD',s).encode('ascii','ign...

data.getData()返回的Uri-程序员宅基地

有三种形式:content://,file://,/document/ content://可以intent.setAction(Intent.ACTION_VIEW),intent.setData(uri)启动,uri.getPath()得到的是真实的路径; file://可以intent.setAction(Intent.ACTION_VIEW),intent.setDataAndType(_data.getdata

MBSE建模学习之八:需求和需求图_mbse需求关系-程序员宅基地

MBSE建模工作中的需求建模概念。_mbse需求关系

机器学习实战第二章——KNN算法(源码解析)-程序员宅基地

#coding=utf-8 ''''' Created on 2015年12月29日 @author: admin ''' from numpy import array from numpy import tile from numpy import zeros import operator from os import listdir # 创建数据集,并返回数据集

推荐文章

热门文章

相关标签