Python定时发送信息到微信

简介: Python定时发送信息到微信

1.想要一个定时提醒天气情况的场景,就想到了用python,这个是基于wxpy 来实现的

注意点:

需要安装对应插件包
python2 和 python3 有引入包不一样注意环境
想在服务器一直运行 可以参考 tmux

代码如下:

# -*- coding: utf-8 -*
import time
import random
import requests
from wxpy import *
import socket
import http
import  json
import urlparse
#from urllib.parse import urlencode
import datetime
import urllib
from threading import Timer
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def get_everydayWords():
    url = 'http://open.iciba.com/dsapi/'
    r = requests.get(url)
    content = json.loads(r.text)
return '每日一句:\n'+content['content'] +'\n'+content['note'] + "\n"
def get_huangli():
    data = {}
    data["appkey"] = ''  //填写自己申请的key  地址:jisuapi.com
    data["year"] = datetime.now().year
    data["month"] = datetime.now().month
    data["day"] = datetime.now().day
    url_values =urllib.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"])
return "今日无黄历信息"
    result = jsonarr["result"]
    xingqi = '星期' + result['week']
    yangli = '阳历日期:' + result['yangli']
    nongli = '农历日期:' + result['nongli']
    wuxing = '今日五行:' + result['wuxing']
    chong ='今日注意的生肖:' + result["chong"]
    suici = '岁次:' + ','.join(result['suici'])
    star = '本月星座:' + result['star']
    shengxiao = '今年生肖:' + result['shengxiao']
    yi = '宜:' + ','.join(result['yi'])
    ji = '忌:' + ','.join(result['ji'])
return xingqi + '黄历:' + '\n'  +  '\n' + yangli + '\n' + nongli + '\n' + wuxing + '\n' + chong + "\n" + suici + "\n" + star + "\n" + shengxiao + "\n" + yi + "\n" + ji + "\n"
def get_html(url, data=None):
# 模拟浏览器来获取网页的html代码
    header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
# 设定超时时间,防止被网站认为是爬虫
    timeout = random.choice(range(80, 180))
while True:
try:
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = "utf-8"
if rep.text[2] != 's':  # 该api调用时有失败的可能,一个简单的判断调用是否成功
break
except timeout as e:
            print("3:", e)
            time.sleep(random.choice(range(8, 15)))
except socket.error as e:
            print("4:", e)
            time.sleep(random.choice(range(20, 60)))
except http.client.BadStatusLine as e:
            print("5:", e)
            time.sleep(random.choice(range(30, 80)))
except http.client.IncompleteRead as e:
            print("6:", e)
            time.sleep(random.choice(range(5, 15)))
except:
print ('获取内容失败')
            time.sleep(10)
    result = ''
    temp = rep.json()
    result = rep.json()
    nowTime=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    result = result['data']
    ondeday = result['yesterday']
    result2 = '今日'+ ondeday['date'] + '\n' \
    + '温度:'+ ondeday['low'] + ' --- ' + ondeday['high'] + '\n' \
    + '日出:' + ondeday['sunrise'] + ' --- ' + '日落:' + ondeday['sunset'] + '\n' \
    + '风向:' + ondeday['fx'] + ' --- ' + ondeday['fl'] + '\n' \
    + '天气:' + ondeday['type'] + '\n' \
    + '提示:' + ondeday['notice'] + '\n' \
    + '湿度:' + result['shidu'] + '\n' \
    + '空气质量:' + result['quality'] + '\n' \
    + 'pm25:' + str(result['pm25']) + '\n' \
    + '------------------------------'  + '\n'
for item in result['forecast']:
      result2 =  result2 + '日期:'+item['date'] + '\n' \
        + '风力:' + item['fl'] + '\n' \
        + '风向:' + item['fx'] + '\n' \
        + '最高温:' + item['high'] + '\n' \
        + '最低温:' + item['low'] + '\n' \
        + '温馨提醒:' + item['notice'] + '\n' \
        + '日出时间:' + item['sunrise'] + '\n' \
        + '日落时间:' + item['sunset'] + '\n' \
        + '天气:' + item['type'] + '\n' \
        + '------------------------------' + '\n' \
    result2 =  result2 + '发送时间:' +  nowTime +  '\n'
return result2
def get_now(city, data=None):
# 模拟浏览器来获取网页的html代码
    header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    url = 'https://free-api.heweather.com/s6/weather/now?location='+city+'&key=614d3a7941034ba48088f689788e789f'
# 设定超时时间,防止被网站认为是爬虫
    timeout = random.choice(range(80, 180))
while True:
try:
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = "utf-8"
if rep.text[2] != 's':  # 该api调用时有失败的可能,一个简单的判断调用是否成功
break
except timeout as e:
            print("3:", e)
            time.sleep(random.choice(range(8, 15)))
except socket.error as e:
            print("4:", e)
            time.sleep(random.choice(range(20, 60)))
except http.client.BadStatusLine as e:
            print("5:", e)
            time.sleep(random.choice(range(30, 80)))
except http.client.IncompleteRead as e:
            print("6:", e)
            time.sleep(random.choice(range(5, 15)))
except:
print ('获取内容失败')
            time.sleep(10)
    result = ''
    temp = rep.json()
    temp = temp['HeWeather6'][0]
    update = temp['update']
    now = temp['now']
    nowTime=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    result = '实时天气预报---' + '更新时间:'+ update['loc'] + '\n'+'\n'\
    + '当前天气:'+ now['cond_txt'] + '\n'\
    + '当前温度:'+ now['tmp'] + '°C' + '\n'\
    + '体感温度:'+ now['fl'] + '°C' + '\n'\
    + '风向:'+ now['wind_dir'] + ' ' + now['wind_sc'] + '级 '+ now['wind_spd'] + '公里/小时'+ '\n'\
    + '相对湿度:'+ now['hum'] + '%' + '\n'\
    + '降水量:'+ now['pcpn'] + 'ml' + '\n'\
    + '能见度:'+ now['vis'] + '公里' + '\n'\
    + '云量:'+ now['cloud']  + '\n'
    result =  result + '发送时间:' +  nowTime 
return result
def auto_send():  # unix时间戳设定为每天早上7:30分自动发送消息
while True:
        time_now = int(time.time())
        now = datetime.now()
        now_str = now.strftime('%Y/%m/%d %H:%M:%S')[11:]
        t = Timer(1,auto_send)
# t.start()
        print(now_str)
#发送全部  7点24 发送 每天早上
if now_str in ['07:24:00']:
for i in ['苏州']:
                url = 'https://www.sojson.com/open/api/weather/json.shtml?city=%s' %i
                weather = get_html(url) 
                word = get_everydayWords()
                huangli = get_huangli()
# 选择对象发送消息
                bot.file_helper.send(weather)
                print(bot.groups().search(u''))
                my_friend = bot.friends().search(u'Lie')[0]
                my_friend2 = bot.friends().search(u'cc')[0]
# my_group = bot.groups().search('Test')[0]
                my_friend.send(word + weather + huangli)
                my_friend2.send(word + weather + huangli)
                my_group.send(word + weather + huangli)
if now_str in ['09:00:00','10:00:00','11:00:00','12:00:00','13:00:00','14:00:00','15:00:00','16:00:00','16:08:00','17:00:00','18:00:00','19:00:00','20:00:00','21:00:00',]:
            city = '苏州'
            weather = get_now(url) 
            word = get_everydayWords()
            huangli = get_huangli()
# 选择对象发送消息
            bot.file_helper.send(weather)   // 这是发送给登陆微信的微信助手
            print(bot.groups().search(u''))
            my_friend = bot.friends().search(u'Lie')[0]  // 好友
            my_friend2 = bot.friends().search(u'cc')[0]
            my_group = bot.groups().search('Test')[0] // 群组
            my_friend.send(weather)
            my_friend2.send(weather)
            my_group.send(weather)
if __name__ == "__main__":
    tuling = Tuling(api_key='') //填写自己的图灵机器人key
    bot = Bot(cache_path=True,console_qr = True)  // 添加缓存,不用每次都扫码登陆,如果是linux 则显示二维码,需安装对应插件包
    myself = bot.self
    bot.enable_puid('wxpy_puid.pkl')
    @bot.register(msg_types=TEXT)  // 图灵机器人调用    
def auto_reply_all(msg):
        tuling.do_reply(msg)
    auto_send()
    bot.join()
相关文章
|
1月前
|
存储 算法 API
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
160 82
|
10天前
|
Python
使用 Python 合并微信与支付宝账单,生成财务报告
这篇博客介绍了如何使用 Python 脚本合并微信与支付宝账单数据,生成自动化财务报告。通过 pandas 库,学习如何清洗、合并和分析账单数据,以及如何生成 Markdown 格式的财务报告。
|
3月前
|
Python
自动化微信朋友圈:Python脚本实现自动发布动态
本文介绍如何使用Python脚本自动化发布微信朋友圈动态,节省手动输入的时间。主要依赖`pyautogui`、`time`、`pyperclip`等库,通过模拟鼠标和键盘操作实现自动发布。代码涵盖打开微信、定位朋友圈、准备输入框、模拟打字等功能。虽然该方法能提高效率,但需注意可能违反微信使用条款,存在风险。定期更新脚本以适应微信界面变化也很重要。
286 61
|
5月前
|
Python
Python编程获取当前日期的所属周日期信息
Python编程获取当前日期的所属周日期信息
88 1
|
3月前
|
JavaScript API C#
【Azure Developer】Python代码调用Graph API将外部用户添加到组,结果无效,也无错误信息
根据Graph API文档,在单个请求中将多个成员添加到组时,Python代码示例中的`members@odata.bind`被错误写为`members@odata_bind`,导致用户未成功添加。
62 10
|
3月前
|
Android开发 开发者 Python
通过标签清理微信好友:Python自动化脚本解析
微信已成为日常生活中的重要社交工具,但随着使用时间增长,好友列表可能变得臃肿。本文介绍了一个基于 Python 的自动化脚本,利用 `uiautomator2` 库,通过模拟用户操作实现根据标签批量清理微信好友的功能。脚本包括环境准备、类定义、方法实现等部分,详细解析了如何通过标签筛选并删除好友,适合需要批量管理微信好友的用户。
158 7
|
4月前
|
缓存 监控 Linux
Python 实时获取Linux服务器信息
Python 实时获取Linux服务器信息
|
4月前
|
存储 数据采集 数据库
用 Python 爬取淘宝商品价格信息时需要注意什么?
使用 Python 爬取淘宝商品价格信息时,需注意法律和道德规范,遵守法律法规和平台规定,避免非法用途。技术上,可选择 Selenium 和 Requests 库,处理反爬措施如 IP 限制、验证码识别和请求频率控制。解析页面数据时,确定数据位置并清洗格式。数据存储可选择 CSV、Excel、JSON 或数据库,定期更新并去重。还需进行错误处理和日志记录,确保爬虫稳定运行。
|
4月前
|
数据采集 Web App开发 iOS开发
如何利用 Python 的爬虫技术获取淘宝天猫商品的价格信息?
本文介绍了使用 Python 爬虫技术获取淘宝天猫商品价格信息的两种方法。方法一使用 Selenium 模拟浏览器操作,通过定位页面元素获取价格;方法二使用 Requests 和正则表达式直接请求页面内容并提取价格。每种方法都有详细步骤和代码示例,但需注意反爬措施和法律法规。
|
5月前
|
小程序 Python
利用Python编程提取身份证的信息
利用Python编程提取身份证的信息
74 2

热门文章

最新文章