吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3402|回复: 33
收起左侧

[Python 转载] 定制云函数天气推送-魔改版

[复制链接]
g1201314 发表于 2022-2-5 15:49
本帖最后由 g1201314 于 2022-3-9 14:14 编辑

sansui-Weather v1.0魔改版

介绍:
魔改@sansui6用户的天气预报消息推送(已获得用户同意
在寒冷的冬日给你爱的人暖暖的提示
(可增加情话api,每天推送情话及其他定制化的推送)
Python脚本实现天气查询应用,提醒她注意保暖!

功能介绍:
  • 天气信息获取推送
  • 当天天气信息提示推送
  • 第二天天气信息提示推送
  • 网易云热评信息获取推送
  • 舔狗日记信息获取推送
  • 疫情信息数据获取推送
  • 可根据个人需要,添加定制的信息提示


使用说明:
  以下信息换为自己的,具体根据API地址申请key后进行替换
  SendKey server酱
  Weather_key 和风天气API
  Tianapi_key 网易云热评API
  Storeapi_key 疫情数据API
  ApiKey 疫情数据API
  userid 接收消息的用户,存在多个以 | 隔开
  adminUserId 管理员用户,错误信息要推送的用户

程序运行截图:
QQ图片20220205155417.png



下载地址:
   蓝奏云:https://wwb.lanzouw.com/iwk7vzmd75c       密码:d0bz

云函数搭建教程:
  https://support.qq.com/products/130099/blog/546919

代码修改教程:
下面自行下载

最后:
如果下载了用不了啊或者有啥问题的,跟帖回复一下,收集一下大家的问题和意见!!
你们的免费评分就是我的动力!!

搭建教程.txt

1.98 KB, 下载次数: 100, 下载积分: 吾爱币 -1 CB

魔改教程

免费评分

参与人数 3吾爱币 +3 热心值 +1 收起 理由
xnink + 1 谢谢@Thanks!
zxl1993 + 1 + 1 大佬,来个推送企微机器人的呗,我不懂啊。。
JIEKE279 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

loa123 发表于 2022-2-8 08:33
本帖最后由 loa123 于 2022-2-8 08:35 编辑

附上成功的代码@夕尘幽兰 仅供参考
[Python] 纯文本查看 复制代码
# -*- coding: utf8 -*-
# [url=home.php?mod=space&uid=238618]@Time[/url]    : 2021/7/19 13:16
# [url=home.php?mod=space&uid=686208]@AuThor[/url]  : Sansui
# @FileName: index.py
# @Software: PyCharm
# @Blog    :https://www.cnblogs.com/sansui6/


import requests
import datetime
import time
import json
import pytz
import ssl,hashlib,string
from urllib import request,parse,error;
from urllib.parse import quote

SendKey = '';#pushplus申请的KEY或者server酱的KEY,这里我自己改了
Weather_key = ''
Tianapi_key = ''
Storeapi_key = ''
ApiKey = ''
# 接收消息的用户,存在多个以 | 隔开
userid = ''

adminUserId = '';

def get_time():
    nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime());  # 获取当前时间
    # 由于腾讯云时间不准确,暂时使用年月日
    nowTime_1 = time.strftime("%Y-%m-%d", time.localtime());  # 获取当前时间
    # print(nowTime_1)
    return nowTime_1;


#获取网易云评论
def get_wyy():
    list = []  ## 空列表
    wyy_url = "http://api.tianapi.com/txapi/hotreview/index?key=" + Tianapi_key + "";
    wyy_json = requests.post(wyy_url).json();
    wyy_code = wyy_json["code"]
    if wyy_code.__eq__(200):
        #获取评论内容
        wyy_content = wyy_json["newslist"][0]["content"]
        #获取歌名
        wyy_source = wyy_json["newslist"][0]["source"]
        #把评论、歌名放进数组
        list.append(wyy_content)
        list.append(wyy_source)
        return list;
    else:
        list.append('获取失败!')
        return list;

#2021/8/4 因疫情较为严重,新增加疫情提示
def ncov():
    api_url = 'https://yupn.api.storeapi.net/api/94/221';
    appid = 13948;
    secret = Storeapi_key;
    data = {
        'appid': appid,
        'city_name': '苏州',
        'format': 'json',
        'time': '1644207719',
    };
    data['appid'] = appid;
    data['time'] = round(time.time());  # 当前服务器时间
    keysArr = list(data.keys())  # 取出字典key
    keysArr.sort()  # 对字典key进行排序
    md5String = '';
    params = []
    for key in keysArr:
        if data[key]:
            val = str(data[key])
            md5String += key + val
            params.append(key + "=" + val)
    md5String += secret;
    m = hashlib.md5()
    b = md5String.encode(encoding='utf-8')
    m.update(b)
    sign = m.hexdigest()

    params.append('sign=' + sign)  # 加入计算后的sign值去请求
    params = '&'.join(tuple(params));  # 把列表转成元组后用&分隔,最终转换成字符串 a=b&c=d&e=f

    ssl._create_default_https_context = ssl._create_unverified_context
    url = api_url + '?' + params;
    url = quote(url, safe=string.printable)
    req = requests.get(url).json()
    #city 所选城市
    #confirm 确诊病例数量
    #curConfirm 当前确诊数量
    #died  死亡数量
    #heal  治愈数量
    #asymptomatic 无症状感染数量
    #print(req["retdata"])
    return req["retdata"]

#获取实时疫情资讯,如分风险地区、疫情概况、疫情新闻等
def nCoV_news(num):
    url="http://api.tianapi.com/txapi/ncov/index?key="+Tianapi_key;
    nCoV_news_json = requests.get(url).json()
    nCoV_news_code = nCoV_news_json["code"]
    print(nCoV_news_json)
    nCoV_news_newslist = nCoV_news_json["newslist"]
    i=0;
    if(nCoV_news_code.__eq__(200)):
        if (num.__eq__(1)):
            # 获取当前数据信息
            return nCoV_news_newslist[0]["desc"]
        elif(num.__eq__(2)):
            #返回全国风险地区,high高风险、mid中风险
            riskarea_high_text = "| -------- | 高风险地区 | --------: |";
            for riskarea_high in nCoV_news_newslist[0]["riskarea"]["high"]:
                if("江苏省" in riskarea_high):
                    # 因为高风险地区逐渐增多,消息已经存放不下,现调整通知格式为具体数量,不再是具体地区。
                    i=i+1;
            return "\n江苏省高风险地区共:" + str(i) + "个。\n"
        elif(num.__eq__(0)):
            riskarea_mid_text = "| -------- | 中风险地区 | --------: |";
            for riskarea_mid in nCoV_news_newslist[0]["riskarea"]["mid"]:
                # print(riskarea_high)
                if ("江苏省" in riskarea_mid):
                    #因为中风险地区逐渐增多,消息已经存放不下,现调整通知格式为具体数量,不再是具体地区。
                    #riskarea_mid_text +="\n" + riskarea_mid;
                    # riskarea_high_text=riskarea_high;
                    i=i+1;
            # return nCoV_news_newslist[0]["riskarea"]
            #print(riskarea_mid_text)
            #return riskarea_mid_text;
            return "\n江苏省中风险地区共:"+str(i)+"个。"


#获取当天天气,不过没有最高温度,最低温度
def get_Weather():
    city_id = get_location();
    Weather_url = f'https://devapi.qweather.com/v7/weather/now?key={Weather_key}&location={city_id}'
    Weather_json = requests.get(Weather_url).json()
    #print(Weather_url)
    Weather_code = Weather_json["code"]
    Weather_now = Weather_json["now"]
    if(Weather_code.__eq__("200")):
      #print(Weather_now)
      return Weather_now;

#获取包括今天在内的未来三天天气
def get_3d_Weather(num):
    date = get_time();
    date_tomorrow = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d");
    city_id = get_location();
    Weather_url = f'https://devapi.qweather.com/v7/weather/3d?key={Weather_key}&location={city_id}';
    #print(Weather_url)
    Weather_json = requests.get(Weather_url).json();
    Weather_3d = Weather_json["daily"]
    for weather in Weather_3d:
        #print("6666666"+weather)
        if(num.__eq__(1)):
            if(weather["fxDate"].__eq__(date)):
                #print("当天天气获取成功")
                return weather;
            else:
                print("查询的不是今天日期的天气")
                return "查询的不是今天日期的天气"
                break;
        elif(num.__eq__(0)):
            if (weather["fxDate"].__eq__(date_tomorrow)):
                #print(weather);
                return weather;
        else:
            print("非法参数!")
            return "非法参数!"

#获取当前天气地区id
def get_location():
    # 调整所在的区域
    location='苏州'
    Weather_city_url = f'https://geoapi.qweather.com/v2/city/lookup?key={Weather_key}&location={location}'
    city_json =requests.get(Weather_city_url).json();
    city_code = city_json["code"]
    if city_code.__eq__("200"):
     #print(Weather_city_url)
     for Weather_city in city_json["location"]:
         Weather_city_name = Weather_city["name"]
         if Weather_city_name.__eq__("苏州"):
             #print(Weather_city)
             city_id = Weather_city["id"]
             #print(city_id)
             return city_id;

    else:
      print("访问获取地区接口失败!")
      return "访问获取地区接口失败!";

def get_tiangou():
    url="http://api.tianapi.com/tiangou/index?key="+Tianapi_key;
    tiangou_json = requests.get(url).json()
    tiangou = tiangou_json["newslist"][0]["content"]
    return tiangou

#拼接消息
def get_desp():

    wyy_content = get_wyy()[0];  # 评论内容
    wyy_source = get_wyy()[1];  # 歌名
    date_tomorrow = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d");

    Weather = get_Weather() #获取当天天气信息
    Weather_text = Weather["text"] #获取当天天气文字
    Weather_temp = Weather["temp"] #实时获取当前温度
    Weather_feelsLike = Weather["feelsLike"] #获取当前体感温度

    Weather_3d_day = get_3d_Weather(1)  # 获取当天的预报天气
    Weather_3d_day_tempMax = Weather_3d_day["tempMax"] #获取当天预报最高温度
    Weather_3d_day_tempMin = Weather_3d_day["tempMin"] #获取当天预报最低温度
    Weather_3d_day_uvIndex = Weather_3d_day["uvIndex"] #获取当天紫外线强度

    Weather_3d_tomorrow = get_3d_Weather(0)  # 获取明天天气
    Weather_3d_tomorrow_textDay = Weather_3d_day["textDay"]  # 获取第二天天气文字
    Weather_3d_tomorrow_tempMax = Weather_3d_day["tempMax"]  # 获取第二天预报最高温度
    Weather_3d_tomorrow_tempMin = Weather_3d_day["tempMin"]  # 获取第二天预报最低温度
    Weather_3d_tomorrow_uvIndex = Weather_3d_day["uvIndex"]  # 获取第二天紫外线强度
    # 获取舔狗日记

    tiangou = get_tiangou();

    cur_time = time.time()
    #print(cur_time)
    local_tz = pytz.timezone("Asia/Shanghai")
    local_time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).hour
    # print(local_time)

    Ncov_zz = ncov();    
    Ncov_city = Ncov_zz["city"];
    # confirm 确诊病例数量
    Ncov_confirm = Ncov_zz["confirm"];
    # curConfirm 当前确诊数量
    Ncov_curConfirm = Ncov_zz["curConfirm"];
    # died  死亡数量
    # heal  治愈数量
    Ncov_heal = Ncov_zz["heal"];
    # asymptomatic 无症状感染数量
    # nCoV_news_mid = nCoV_news(0);  # 获取疫情中风险地区
    # time.sleep(1000)
    nCoV_news_num = nCoV_news(1);#获取全国疫情数据
    # time.sleep(1000)
    # nCoV_news_high = nCoV_news(2);  # 获取疫情高风险地区
    currentConfirmedCount  = nCoV_news_num["currentConfirmedCount"]#现存确诊人数
    seriousCount = nCoV_news_num["seriousCount"] #现存无症状
    beijing_Time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).strftime("%Y-%m-%d %H:%M:%S");

    Ncov_desp = ("\n| -------- |全国疫情实时播报|----------------: |\n"+
    "截至北京时间 "+beijing_Time+"\n"+
    "全国现存确诊病例:" + str(currentConfirmedCount)+"\n"+
    "全国现存无症状病例:" + str(seriousCount) + "\n" +
    Ncov_city +"现存确诊病例:" + str(Ncov_curConfirm)  + ""
                 )


    desp_Weather_temp_text = "";
    desp_Weather_text = "";
    desp_Weather_3d_tomorrow_textDay_text = "";
    desp_Weather_3d_day_tempMax_text = "";
    desp_Weather_3d_tomorrow_tempMax_text = "";
    desp_day = "";
    desp_tomorrow = "";
    desp_Weather_3d_day_uvIndex = "";

    # 晚上八点 查询第二天天气情况,然后根据当前时间,定制化推送当前提醒
    if (local_time >= 20 and local_time <= 23):
        # 如果有雨,不校验最高温度
        # 判断天气
        if ("雨" in Weather_3d_tomorrow_textDay):
            if Weather_3d_tomorrow_textDay.__eq__("大雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天"+ Weather_3d_tomorrow_textDay + ",傻瓜,记得带伞,记得早点出门,晚上早点睡\n"
            elif Weather_3d_tomorrow_textDay.__eq__("中雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",傻瓜,记得带伞,记得早点出门,晚上早点睡\n"
            elif Weather_3d_tomorrow_textDay.__eq__("雷阵雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",小心打雷,抱抱傻瓜,不怕不怕\n"
            else:
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",记得带伞,请注意天气\n"
        # 没雨的情况下,根据温度提醒明天天气
        else:
            desp_Weather_3d_tomorrow_textDay_text = "\n";
            if (int(Weather_3d_tomorrow_tempMax) >= 33):
                desp_Weather_3d_tomorrow_tempMax_text = "\n明天天气较热,注意防晒!\n"
            else:
                desp_Weather_3d_tomorrow_tempMax_text = "\n";

        desp_tomorrow = (
                    "明天 " + date_tomorrow + "\n天气:" + Weather_3d_tomorrow_textDay + desp_Weather_3d_tomorrow_textDay_text +
                    "明天最高温度:" + Weather_3d_tomorrow_tempMax + "℃。" + desp_Weather_3d_tomorrow_tempMax_text +
                    "明天最低温度:" + Weather_3d_tomorrow_tempMin + "℃。"
                    );
    elif (local_time >= 0 and local_time < 20):
        # desp_Weather_3d_tomorrow_textDay_text = "\n";
        # desp_Weather_3d_tomorrow_tempMax_text = "\n";
        # 判断当前温度
        if (int(Weather_temp) >= 33):
            if (8 < local_time < 16):
                desp_Weather_temp_text = ",天气有点热喔!\n"
            else:
                desp_Weather_temp_text = "。\n";
        else:
            desp_Weather_temp_text = "。\n";

        # 判断紫外线等级
        if (8 <= local_time < 16):
            if (4 < int(Weather_3d_day_uvIndex) <= 6):
                desp_Weather_3d_day_uvIndex = "\n今天紫外线等级" + Weather_3d_day_uvIndex + ",适合户外运动。\n"
            elif (6 < int(Weather_3d_day_uvIndex) <= 9):
                desp_Weather_3d_day_uvIndex = "\n今天紫外线等级" + Weather_3d_day_uvIndex + ",请注意防晒。\n"
            elif (9 < int(Weather_3d_day_uvIndex)):
                desp_Weather_3d_day_uvIndex = "\n今天紫外线等级" + Weather_3d_day_uvIndex + ",宝,外边太晒了,能不出去就不要出去了。\n"
            else:
                desp_Weather_3d_day_uvIndex = "\n";
        else:
            desp_Weather_3d_day_uvIndex = "\n";

            # 判断当天是否有雨,有雨不判断当天最高温度
            Weather_text = "晴"
        if ("雨" in Weather_text):
            if Weather_text.__eq__("大雨"):
                desp_Weather_3d_day_tempMax_text = "\n";
                desp_Weather_text = "\n当前有" + Weather_text + ",傻瓜,赶紧避雨,不要再外出啦\n"
            elif Weather_text.__eq__("中雨"):
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n当前有" + Weather_text + ",傻瓜,赶紧避雨,不要再外出啦\n"
            elif Weather_text.__eq__("雷阵雨"):
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n当前有" + Weather_text + ",小心打雷,抱抱傻瓜,不怕不怕\n"
            else:
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n当前有" + Weather_text + ",请注意天气\n"
        else:
            desp_Weather_text = "\n";
            # 判断当天最高温度
            if (int(Weather_3d_day_tempMax) >= 33):
                # 下午16点以后不用提示
                if (local_time > 16):
                    desp_Weather_3d_day_tempMax_text = "\n";
                else:
                    desp_Weather_3d_day_tempMax_text = "\n今天天气较热,注意防晒!\n"
            else:
                desp_Weather_3d_day_tempMax_text = "\n";

        desp_day = (
                "当前天气:" + Weather_text + desp_Weather_text +
                "当前温度:" + Weather_temp + "℃" + desp_Weather_temp_text +
                "今天最高温度:" + Weather_3d_day_tempMax + "℃。" + desp_Weather_3d_day_tempMax_text +
                "最低温度:" + Weather_3d_day_tempMin + "℃。" + desp_Weather_3d_day_uvIndex # 紫外线 16点后不提示
            + "\n" +wyy_content + "\n来自:网易云音乐《" + wyy_source + "》" +
                "\n| -----------------舔狗日记-----------------: |\n" +
                tiangou + "\n来自:舔狗日记\n"

        );
    ##以下是通知内容!
    desp = "苏州\n" + desp_day + desp_tomorrow + Ncov_desp;
    return desp;


# 程序入口,消息推送
def main():
    title = '每日推送';
    desp = get_desp();
    #url = f"https://sctapi.ftqq.com/{SendKey}.send?title={title}&desp={desp}&openid={userid}";    
    token = SendKey #在pushpush网站中可以找到    
    content = desp #改成你要的正文内容
    pushurl = 'http://www.pushplus.plus/send'
    data = {
    "token":token,
    "title":title,
    "content":content
    }
    body=json.dumps(data).encode(encoding='utf-8')
    headers = {'Content-Type':'application/json'}
    requests.post(pushurl,data=body,headers=headers)
    res = requests.post(pushurl);
    if res.status_code == 200:
        print("成功!")
    else:
       title = "天气推送失败!"
       ##desp = "尊敬的管理员,消息推送失败\n推送日志"+res.json();
       print(res.status_code)
       #url = f"https://sctapi.ftqq.com/{SendKey}.send?title={title}&desp={desp}&openid={adminUserId}";
       #res = requests.post(url);
       print("错误日志推送成功 !")




def main_handler(event, context):
   main()

if __name__ == '__main__':
   main()

夕尘幽兰 发表于 2022-2-5 23:53
START RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114

Init Report RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114 Coldstart: 270ms (PullCode: 69ms InitRuntime: 4ms InitFunction: 197ms) Memory: 128MB MemUsage: 7.89MB

ERROR RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114 Result: {"errorCode": -1, "errorMessage": "Traceback (most recent call last):   File "/var/runtime/python37/bootstrap.py", line 133, in init_handler     func_handler = get_func_handler(file.rsplit(".", 1)[0], func)   File "/var/runtime/python37/bootstrap.py", line 159, in get_func_handler     mod = imp.load_module(mname, *imp.find_module(mname))   File "/var/lang/python37/lib/python3.7/imp.py", line 234, in load_module     return load_source(name, filename, file)   File "/var/lang/python37/lib/python3.7/imp.py", line 171, in load_source     module = _load(spec)   File "<frozen importlib._bootstrap>", line 696, in _load   File "<frozen importlib._bootstrap>", line 677, in _load_unlocked   File "<frozen importlib._bootstrap_external>", line 728, in exec_module   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed   File "/var/user/index.py", line 9, in <module>     import requests ModuleNotFoundError: No module named 'requests'", "statusCode": 443}

END RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114

Report RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114 Duration: 0ms Memory: 128MB MemUsage: 7.89MB

START RequestId:7f946364-06ce-4065-92ce-66ab8a4a4114

ERROR RequestId:7f946364-06ce-4065-92ce-66ab8a4a4114 Result:{"errorCode":-1,"errorMessage":"Traceback (most recent call last):\n  File \"/var/runtime/python37/bootstrap.py\", line 133, in init_handler\n    func_handler = get_func_handler(file.rsplit(\".\", 1)[0], func)\n  File \"/var/runtime/python37/bootstrap.py\", line 159, in get_func_handler\n    mod = imp.load_module(mname, *imp.find_module(mname))\n  File \"/var/lang/python37/lib/python3.7/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n  File \"/var/lang/python37/lib/python3.7/imp.py\", line 171, in load_source\n    module = _load(spec)\n  File \"\u003cfrozen importlib._bootstrap\u003e\", line 696, in _load\n  File \"\u003cfrozen importlib._bootstrap\u003e\", line 677, in _load_unlocked\n  File \"\u003cfrozen importlib._bootstrap_external\u003e\", line 728, in exec_module\n  File \"\u003cfrozen importlib._bootstrap\u003e\", line 219, in _call_with_frames_removed\n  File \"/var/user/index.py\", line 9, in \u003cmodule\u003e\n    import requests\nModuleNotFoundError: No module named 'requests'","statusCode":443}

END RequestId:7f946364-06ce-4065-92ce-66ab8a4a4114

Report RequestId:7f946364-06ce-4065-92ce-66ab8a4a4114 Duration:0ms Memory:128MB MemUsage:0.000000MB

所有的需要改自己KEY的地方,都改了,腾讯云函数报错如上,
Pycharm本地测试报错:
Traceback (most recent call last):
  File "D:/pythonProject/Weather01.py", line 390, in <module>
    main()
  File "D:/pythonProject/Weather01.py", line 369, in main
    desp = get_desp();
  File "D:/pythonProject/Weather01.py", line 224, in get_desp
    tiangou = get_tiangou();
  File "D:/pythonProject/Weather01.py", line 197, in get_tiangou
    tiangou = tiangou_json["newslist"][0]["content"]
KeyError: 'newslist'

进程已结束,退出代码1

@g1201314
zhang176 发表于 2022-2-6 16:17
 楼主| g1201314 发表于 2022-2-6 20:05
本帖最后由 g1201314 于 2022-2-6 20:09 编辑
夕尘幽兰 发表于 2022-2-5 23:53
START RequestId: 7f946364-06ce-4065-92ce-66ab8a4a4114

Init Report RequestId: 7f946364-06ce-4065-9 ...

这个错是腾讯云环境部署的问题,部署的时候将py版本调整为3.6
本地调试报错,你如果不会改的话,就重新复制下载地址的,你函数还是用的原来的代码调试的
夕尘幽兰 发表于 2022-2-6 21:31
本帖最后由 夕尘幽兰 于 2022-2-6 21:42 编辑
g1201314 发表于 2022-2-6 20:05
这个错是腾讯云环境部署的问题,部署的时候将py版本调整为3.6
本地调试报错,你如果不会改的话,就重新 ...

@g1201314
已经重新复制代码,换成PY3.6版本了,还是不行
START RequestId: bb5a21e0-0346-4d64-a00c-a967dc304a26

Init Report RequestId: bb5a21e0-0346-4d64-a00c-a967dc304a26 Coldstart: 992ms (PullCode: 206ms InitRuntime: 20ms InitFunction: 766ms) Memory: 128MB MemUsage: 16.35MB

Starting new HTTP connection (1): api.tianapi.com:80

http://api.tianapi.com:80 "POST /hotreview/index?key=2544447a9b80975a515417f45e35bfcf HTTP/1.1" 200 None

Starting new HTTP connection (1): api.tianapi.com:80

http://api.tianapi.com:80 "POST /hotreview/index?key=2544447a9b80975a515417f45e35bfcf HTTP/1.1" 200 None

Starting new HTTPS connection (1): geoapi.qweather.com:443

https://geoapi.qweather.com:443 "GET /v2/city/lookup?key=53583b9e76b64998a3c0489d7741cf8d&location=%E8%AE%B8%E6%98%8C HTTP/1.1" 200 457

Starting new HTTPS connection (1): devapi.qweather.com:443

https://devapi.qweather.com:443 "GET /v7/weather/now?key=53583b9e76b64998a3c0489d7741cf8d&location=101180403 HTTP/1.1" 200 296

Starting new HTTPS connection (1): geoapi.qweather.com:443

https://geoapi.qweather.com:443 "GET /v2/city/lookup?key=53583b9e76b64998a3c0489d7741cf8d&location=%E8%AE%B8%E6%98%8C HTTP/1.1" 200 457

Starting new HTTPS connection (1): devapi.qweather.com:443

https://devapi.qweather.com:443 "GET /v7/weather/3d?key=53583b9e76b64998a3c0489d7741cf8d&location=101180403 HTTP/1.1" 200 596

Starting new HTTPS connection (1): geoapi.qweather.com:443

https://geoapi.qweather.com:443 "GET /v2/city/lookup?key=53583b9e76b64998a3c0489d7741cf8d&location=%E8%AE%B8%E6%98%8C HTTP/1.1" 200 457

Starting new HTTPS connection (1): devapi.qweather.com:443

https://devapi.qweather.com:443 "GET /v7/weather/3d?key=53583b9e76b64998a3c0489d7741cf8d&location=101180403 HTTP/1.1" 200 596

Starting new HTTP connection (1): api.tianapi.com:80

http://api.tianapi.com:80 "GET /tiangou/index?key=2544447a9b80975a515417f45e35bfcf HTTP/1.1" 200 None

ERROR RequestId:bb5a21e0-0346-4d64-a00c-a967dc304a26 Result:{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"Traceback (most recent call last):\n  File \"/var/user/index.py\", line 387, in main_handler\n    main()\n  File \"/var/user/index.py\", line 369, in main\n    desp = get_desp();\n  File \"/var/user/index.py\", line 224, in get_desp\n    tiangou = get_tiangou();\n  File \"/var/user/index.py\", line 197, in get_tiangou\n    tiangou = tiangou_json[\"newslist\"][0][\"content\"]\nKeyError: 'newslist'","statusCode":430}

END RequestId:bb5a21e0-0346-4d64-a00c-a967dc304a26

Report RequestId:bb5a21e0-0346-4d64-a00c-a967dc304a26 Duration:1702ms Memory:128MB MemUsage:16.733078MB
loa123 发表于 2022-2-7 11:21
[JavaScript] 纯文本查看 复制代码
{
	"errorCode": -1,
	"errorMessage": "user code exception caught",
	"requestId": "11f1fba3-e127-4b51-b9ce-90b8be2e4722",
	"stackTrace": "Traceback (most recent call last):\n  File \"/var/user/index.py\", line 387, in main_handler\n    main()\n  File \"/var/user/index.py\", line 369, in main\n    desp = get_desp();\n  File \"/var/user/index.py\", line 234, in get_desp\n    Ncov_city = Ncov_zz[\"city\"];\nKeyError: 'city'",
	"statusCode": 430
}
loa123 发表于 2022-2-7 13:28
终于部署成功了,需要把里面涉及的所有应用API都申请一遍
另外我修改了发送到Pushplus
369行替换下就行
[Python] 纯文本查看 复制代码
    #url = f"https://sctapi.ftqq.com/{SendKey}.send?title={title}&desp={desp}&openid={userid}";    
    token = SendKey #在pushpush网站中可以找到    
    content = desp #改成你要的正文内容
    pushurl = 'http://www.pushplus.plus/send'
    data = {
    "token":token,
    "title":title,
    "content":content
    }
    body=json.dumps(data).encode(encoding='utf-8')
    headers = {'Content-Type':'application/json'}
    requests.post(pushurl,data=body,headers=headers)
    res = requests.post(pushurl);


360截图20220207132641964.jpg
夕尘幽兰 发表于 2022-2-8 11:12
loa123 发表于 2022-2-8 08:33
附上成功的代码@夕尘幽兰 仅供参考
[mw_shl_code=python,true]# -*- coding: utf8 -*-
# @Time    : 2021 ...

感谢分享,谢谢啦
c8289463 发表于 2022-2-22 09:48
a = datetime.datetime.now()  # 实时时间
    y = str(a.year)
    m = str(a.month)
    d = str(a.day)  # 转换为字符串,便于打印
    time = y + '年' + m + '月' + d + '日' + '\n'
    b = datetime.datetime(2022, 3, 10)  # 自己设置的方案时间
    zhuangji = (b - a).days  # 倒计时
    zhuangji = '距离示范区桩基施工图完成还剩{}天!'.format(zhuangji)

    cc = datetime.datetime(2022, 3, 10)  # 自己设置的方案时间
    tujian = (cc - a).days  # 倒计时
    tujian = '距离示范区土建施工图完成还剩{}天!'.format(tujian)

    dd = datetime.datetime(2022, 3, 10)  # 自己设置的方案时间
    linshi = (dd - a).days  # 倒计时
    linshi = '距离示范区临时样板施工图完成还剩{}天!'.format(linshi)
    desp = zhuangji + tujian + linshi
servertalk = 'https://sctapi.ftqq.com/SCT65263TNRj1e3hz4KlF2ozJcAUcpj5x.send?title='+ desp + '&desp='
    requests.post(servertalk)


输出:距离示范区桩基施工图完成还剩15天!距离示范区土建施工图完成还剩
  为什么只显示半截  哪里错了?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-8 08:27

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表