卖坚果的怪叔叔 卖坚果的怪叔叔
  • 首页
  • 生活
  • 技术
  • 记录
  • 工具箱
  • 关于我
首页 › 技术 › Python定时发送信息到微信

Python定时发送信息到微信

坚果大叔
2018-08-30 14:32:47技术阅读 3,310

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()
python 微信 微信机器人
赞赏 赞(0)
本文系作者 @坚果大叔 原创发布在 卖坚果的怪叔叔。未经许可,禁止转载。
夏天夏天悄悄过去
上一篇
CSS实现网格背景!
下一篇
在小程序中查看

这是个😊,挣点服务器费用😜

热门文章
Nuxt中服务端请求无法获取LocalStorage和Cookie的解决办法!
常用的JS 时间转换相关代码!
Vue改变数组值,页面视图为何不刷新?
又是周六的一天。
核酸 N+1
假期最后一天
专题标签
CSS (15) dom (1) Es6入门系列 (14) Git (3) html (1) iview (1) JavaScript (9) js (4) Lif (1) Node (4) pyecharts (1) Python (10) ref (1) scriptable (1) Skill (1) vsCode (1) vue (4) wordpress (2) 三月 (1) 上海 (1) 其他分享 (3) 前端两三问 (15) 古镇 (1) 外滩 (1) 对象 (1) 小程序 (5) 年度总结 (6) 年终总结 (1) 微信机器人 (4) 微信相关技巧 (1) 打字机 (1) 技术 (1) 日常问题 (8) 日常问题记录 (1) 春天 (2) 服务器 (2) 油菜花 (1) 海族馆 (1) 生活 (8) 网上国网 (1) 记录 (3) 通勤 (1) 重学JavaScript (11) 面试题 (10) 🌸 (1)
什么是 Skill?
2026-08-12 21:32:42
156 1 0
失业在家,我给小朋友做了一个练字小程序!
2026-08-07 16:21:52
386 8 1
上线8年,15万用户的小程序,一共赚了多少钱?
2026-05-30 18:01:24
4,557 4 0
WordPress评论留言通知推送插件!
2025-12-13 17:22:36
3,664 3
  • 0
博主

一位佛系的前端开发者,略通摄影,乐于尝试新事物,热衷于美食。

友链
故事胶片
公众号
坚果大叔 执行上下文 卖坚果的怪叔叔 Dacking
Copyright © 2017-2026 卖坚果的怪叔叔

开往-友链接力

萌ICP备20230818号

苏ICP备18048410号-3
  • 首页
  • 生活
  • 技术
  • 记录
  • 工具箱
  • 关于我
# CSS # # JavaScript # # vue # # 微信 # # 生活 #
坚果大叔
344
文章
170
评论
430
喜欢