qqbot的github页面:https://github.com/pandolia/qqbot

原理就是通过爬虫爬取天气信息,然后通过onQQMessage相应函数相应请求

qqbot的安装 :在cmd里输入pip install qqbot即可

启动qqbot:在cmd里直接输入qqbot

使用插件:在另一个cmd里键入 qq plug sample 

卸载插件: 在第二个cmd里键入  qq unplug sample

PS:sample就是你脚本的名字

写一个相应脚本 sample.py  (叫别的名字也行),放到 C:\Users\junk beat\.qqbot-tmp\plugins 这个目录下

脚本里面包含了查天气的爬虫,api说明页面 



爬虫代码如下:

def get_weather(city):
    ##返回一个今天信息的列表和未来4天信息的列表
    import requests
    import json
    r = city
    #天津是的id是101030100
    #https://www.sojson.com/blog/305.html
    url = "http://t.weather.sojson.com/api/weather/city/101030100"
    result = requests.get(url).json()  #将字符串转换为字典
    if result.get('status') != 200:
        print("请求出错,错误代码%d\n" % result.get('status'))
        return -1
    time = result["time"]   #系统时间
    update_time = result.get("cityInfo").get("updateTime")  #城市天气预报更新时间
    humidness = result.get("data").get("shidu")              #获得当前湿度
    pm25 = result.get("data").get("pm25")                    #pm2.5
    pm10 = result.get("data").get("pm10")
    quality = result.get("data").get("quality")              #空气质量
    temperature = result.get("data").get("wendu")            #气温
    today = []                   #记录今天信息的列表
    today.append(time)
    today.append(update_time)
    today.append(humidness)
    today.append(pm25)
    today.append(pm10)
    today.append(quality)
    today.append(temperature)
    print(today)
    data = [None]*4
    sunrise = [None]*4
    high = [None]*4
    low = [None]*4
    sunset = [None]*4
    aqi = [None]*4
    fx = [None]*4
    fl = [None]*4
    type = [None]*4
    notice = [None]*4

    """
    forcast[]消息样例
     "date": "22日星期六",
                "sunrise": "05:57",
                "high": "高温 26.0℃",
                "low": "低温 15.0℃",
                "sunset": "18:10",
                "aqi": 55.0,
                "fx": "西北风",
                "fl": "4-5级",
                "type": "晴",
                "notice": "愿你拥有比阳光明媚的心情"
    """
    result_data = result["data"]["forecast"]
    dict = {}
    for i in range(0, 4):
        dict[i] = result_data[i + 1]
        data[i] = dict[i].get("data")
        sunrise[i] = dict[i].get("sunrise")
        high[i] = dict[i].get("high")
        low[i] = dict[i].get("low")
        sunset[i] = dict[i].get("sunset")
        aqi[i] = dict[i].get("aqi")
        fx[i] = dict[i].get("fx")
        fl[i] = dict[i].get("fl")
        type[i] = dict[i].get("type")
        notice[i] = dict[i].get("notice")
    info = []                      #记录未来4天信息的列表
    info.append(data)
    info.append(sunrise)
    info.append(high)
    info.append(low)
    info.append(sunset)
    info.append(aqi)
    info.append(fx)
    info.append(fl)
    info.append(type)
    info.append(notice)
    print(info)
    return today,info

if __name__ == '__main__':
    today , info = get_weather("天津")
    print(today)
    print(info)

正常情况下结果是这样的:

['2018-11-19 13:17:38', '13:05', '51%', 115.0, 137.0, '轻度污染', '10']
[[None, None, None, None], ['06:58', '06:59', '07:00', '07:01'], ['高温 11.0℃', '高温 9.0℃', '高温 10.0℃', '高温 12.0℃'], ['低温 1.0℃', '低温 0.0℃', '低温 2.0℃', '低温 2.0℃'], ['16:54', '16:54', '16:53', '16:53'], [122.0, 63.0, 56.0, 108.0], ['东北风', '西南风', '南风', '南风'], ['<3级', '<3级', '<3级', '<3级'], ['阴', '晴', '晴', '多云'], ['不要被阴云遮挡住好心情', '愿你拥有比阳光明媚的心情', '愿你拥有比阳光明媚的心情', '阴晴之间,谨防紫外线侵扰']]
['2018-11-19 13:17:38', '13:05', '51%', 115.0, 137.0, '轻度污染', '10']
[[None, None, None, None], ['06:58', '06:59', '07:00', '07:01'], ['高温 11.0℃', '高温 9.0℃', '高温 10.0℃', '高温 12.0℃'], ['低温 1.0℃', '低温 0.0℃', '低温 2.0℃', '低温 2.0℃'], ['16:54', '16:54', '16:53', '16:53'], [122.0, 63.0, 56.0, 108.0], ['东北风', '西南风', '南风', '南风'], ['<3级', '<3级', '<3级', '<3级'], ['阴', '晴', '晴', '多云'], ['不要被阴云遮挡住好心情', '愿你拥有比阳光明媚的心情', '愿你拥有比阳光明媚的心情', '阴晴之间,谨防紫外线侵扰']]

 

完整的脚本代码如下

#coding:utf-8

"""
bot     : QQBot 对象,提供 List/SendTo/Stop/Restart 等接口,详见本文档第五节
contact : QContact 对象,消息的发送者,具有 ctype/qq/uin/nick/mark/card/name 等属性
member  : QContact 对象,仅当本消息为 群消息或讨论组消息 时有效,代表实际发消息的成员
content : str 对象,消息内容
"""
def get_weather(city):
    ##返回一个今天信息的列表和未来4天信息的列表
    import requests
    import json
    r = city
    #天津是的id是101030100
    #https://www.sojson.com/blog/305.html
    url = "http://t.weather.sojson.com/api/weather/city/101030100"
    result = requests.get(url).json()  #将字符串转换为字典
    if result.get('status') != 200:
        print("请求出错,错误代码%d\n" % result.get('status'))
        return -1
    time = result["time"]   #系统时间
    update_time = result.get("cityInfo").get("updateTime")  #城市天气预报更新时间
    humidness = result.get("data").get("shidu")              #获得当前湿度
    pm25 = result.get("data").get("pm25")                    #pm2.5
    pm10 = result.get("data").get("pm10")
    quality = result.get("data").get("quality")              #空气质量
    temperature = result.get("data").get("wendu")            #气温
    today = []                   #记录今天信息的列表
    today.append(time)
    today.append(update_time)
    today.append(humidness)
    today.append(pm25)
    today.append(pm10)
    today.append(quality)
    today.append(temperature)
    print(today)
    data = [None]*4
    sunrise = [None]*4
    high = [None]*4
    low = [None]*4
    sunset = [None]*4
    aqi = [None]*4
    fx = [None]*4
    fl = [None]*4
    type = [None]*4
    notice = [None]*4

    """
    forcast[]消息样例
     "date": "22日星期六",
                "sunrise": "05:57",
                "high": "高温 26.0℃",
                "low": "低温 15.0℃",
                "sunset": "18:10",
                "aqi": 55.0,
                "fx": "西北风",
                "fl": "4-5级",
                "type": "晴",
                "notice": "愿你拥有比阳光明媚的心情"
    """
    result_data = result["data"]["forecast"]
    dict = {}
    for i in range(0, 4):
        dict[i] = result_data[i + 1]
        data[i] = dict[i].get("data")
        sunrise[i] = dict[i].get("sunrise")
        high[i] = dict[i].get("high")
        low[i] = dict[i].get("low")
        sunset[i] = dict[i].get("sunset")
        aqi[i] = dict[i].get("aqi")
        fx[i] = dict[i].get("fx")
        fl[i] = dict[i].get("fl")
        type[i] = dict[i].get("type")
        notice[i] = dict[i].get("notice")
    info = []                      #记录未来4天信息的列表
    info.append(data)
    info.append(sunrise)
    info.append(high)
    info.append(low)
    info.append(sunset)
    info.append(aqi)
    info.append(fx)
    info.append(fl)
    info.append(type)
    info.append(notice)
    print(info)
    return today,info



def onQQMessage(bot, contact, member, content):
      if content == "-hello":
           bot.SendTo(contact, "你好,我是QQ机器人")
      elif content == "-help":
           str_help = "我是QQ机器人,查询天气晴发送-天气\n目前只支持天津的天气查询\n" \
                  "后续可能会更新其他城市天气查询以及其他的查询功能\n" \
                  "powered by python3.6 and qqbot\n" \
                  "github页面:https://github.com/pandolia/qqbot"
           bot.SendTo(contact, str_help)
      elif content == "-stop":
           bot.SendTo(contact, "QQ机器人关闭")
           bot.Stop()
      elif content == "-天气":
          today, info = get_weather("天津")
          import time
          now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + "\n"
          import os
          is_Exists = os.path.exists("C:/Users/junk beat/.qqbot-tmp/plugins/weather")
          if not is_Exists:
              os.makedirs("C:/Users/junk beat/.qqbot-tmp/plugins/weather")
          st = ""
          with open("C:/Users/junk beat/.qqbot-tmp/plugins/weather/天气查询记录.log", "a") as file:
              name = contact.name
              file.write("########################\n")
              file.write(now)
              file.write("来自" + str(name) + "的查询\n")
              file.write("查询地点:天津\n")
              st = st + "城市:天津\n"
              file.write("今天的天气:\n")
              file.write("天气预报更新时间:" + today[1] + "\n")
              st = st + "天气预报更新时间:" + today[1] + "\n"
              file.write("湿度:" + today[2] + "\n")
              st = st + "湿度:" + today[2] + "\n"
              file.write("pm2.5:" + str(today[3]) + "\n")
              st = st + "pm2.5:" + str(today[3]) + "\n"
              file.write("pm10:" + str(today[4]) + "\n")
              st = st + "pm10:" + str(today[4]) + "\n"
              file.write("空气质量:" + today[5] + "\n")
              st = st + "空气质量:" + today[5] + "\n"
              file.write("气温:" + today[6])
              st = st + "气温:" + today[6] + "\n"
              file.write("\n")
              #bot.SendTo(contact, st)
          string = [None]*4
          for i in range(4):
              string[i] = ""
              with open("C:/Users/junk beat/.qqbot-tmp/plugins/weather/天气查询记录.log", "a") as file:
                  file.write("未来" + str(i+1) + "天的预测:\n")
                  string[i] = string[i] + "未来" + str(i+1) + "天的预测:\n"
                  #file.write("日期:" + str(info[0][i]) + "\n")
                  #string[i] = string[i] + "日期:" + str(info[0][i]) + "\n"
                  file.write("日出时间:" + str(info[1][i]) + "\n")
                  string[i] = string[i] + "日出时间:" + str(info[1][i]) + "\n"
                  file.write("最高温度:" + str(info[2][i]) + "\n")
                  string[i] = string[i] + "最高温度:" + str(info[2][i]) + "\n"
                  file.write("最低温度:" + str(info[3][i]) + "\n")
                  string[i] = string[i] + "最低温度:" + str(info[3][i]) + "\n"
                  file.write("日落时间:" + str(info[4][i]) + "\n")
                  string[i] = string[i] + "日落时间:" + str(info[4][i]) + "\n"
                  file.write("空气质量直属(aqi):" + str(info[5][i]) + "\n")
                  string[i] = string[i] + "空气质量直属(aqi):" + str(info[5][i]) + "\n"
                  file.write("风向:" + str(info[6][i]) + "\n")
                  string[i] = string[i] + "风向:" + str(info[6][i]) + "\n"
                  file.write("风力等级:" + str(info[7][i]) + "\n")
                  string[i] = string[i] + "风力等级:" + str(info[7][i]) + "\n"
                  file.write("天气状况:" + str(info[8][i]) + "\n")
                  string[i] = string[i] + "天气状况:" + str(info[8][i]) + "\n"
                  file.write("小贴士:" + str(info[9][i]) + "\n")
                  string[i] = string[i] +  str(info[9][i]) + "\n"
                  file.write("\n-----------------------")
          spl = "------------------------------------"
          s = st + "\n" + spl + "\n" + string[0] + "\n"+ spl + "\n"+ string[1] + "\n" + \
              spl + "\n"+ string[2]  +"\n" + spl + "\n" + string[3]
          bot.SendTo(contact, s)
      import os
      import time
      now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + "\n"
      type = contact.ctype
      if(type == "buddy"):
          qq_num = contact.uin
          nic = contact.nick      #昵称
          if(contact.mark != None):
            mark = contact.mark
          real_name = contact.name#自己的备注
          is_Exists = os.path.exists("C:/Users/junk beat/.qqbot-tmp/plugins/buddy")
          if not is_Exists:
              os.makedirs("C:/Users/junk beat/.qqbot-tmp/plugins/buddy")
          path = "C:/Users/junk beat/.qqbot-tmp/plugins/buddy/" + real_name + ".txt"
          with open(path, "a") as file:
              file.write(now)
              file.write("qq号:" + qq_num + "\n")
              file.write("昵称:" + nic + "\n")
              file.write("群备注:" + mark + "\n")
              file.write("自己的备注:" + real_name + "\n")
              file.write("接收的消息:" + content + "\n")
              file.write("\n")
      elif(type == "group"):
          real_name = contact.name
          qq_num = member.uin #qq号
          nick = member.nick  #昵称
          card = member.card  #群名片
          name = member.name  #备注
          is_Exists = os.path.exists("C:/Users/junk beat/.qqbot-tmp/plugins/group")
          if not is_Exists:
              os.makedirs("C:/Users/junk beat/.qqbot-tmp/plugins/group")
          path = "C:/Users/junk beat/.qqbot-tmp/plugins/group/" + real_name + ".txt"
          with open(path, "a") as file:
              file.write(now)
              file.write("发送消息的qq号:" + qq_num + "\n")
              file.write("发送信息者昵称:" + nick + "\n")
              file.write("自己的备注:" + name + "\n")
              file.write("消息发送者群备注:" + card + "\n")
              file.write("qq群名:" + real_name + "\n")
              file.write("接收的消息:" + content + "\n")
              file.write("\n")
      else:
          real_name = contact.name
          qq_num = member.uin #qq号
          nick = member.nick  #昵称
          card = member.card  #群名片
          name = member.name  #备注
          is_Exists = op.path.exists("C:/Users/junk beat/.qqbot-tmp/plugins/discuss")
          if not is_Exists:
              os.makedirs("C:/Users/junk beat/.qqbot-tmp/plugins/discuss")
          path = "C:/Users/junk beat/.qqbot-tmp/plugins/discuss/" + real_name + ".txt"
          with open(path, "a") as file:
              file.write(now)
              file.write("发送消息的qq号:" + qq_num + "\n")
              file.write("发送信息者昵称:" + nick + "\n")
              file.write("自己的备注:" + name + "\n")
              file.write("消息发送者群备注:" + card + "\n")
              file.write("讨论组名:" + real_name + "\n")
              file.write("接收的消息:" + content + "\n")
              file.write("\n")

这个代码会收到的消息记录下来(包括天气查询记录):

目录结构如下:

机器学习 天气作为参数 天气机器人_ci

以group为例,记录的内容如下:

机器学习 天气作为参数 天气机器人_qqbot_02

qq里运行效果:

机器学习 天气作为参数 天气机器人_python_03

需要注意的地方:

1.修改了sample之后,需要卸载插件在重新安装插件

2.当输入qq plug sample不管用的时候(unplug同理),需要在qqbot那个cmd里敲回车

补充:

那个天气api的网站提供了很多个城市的天气信息,可以根据用户的输入来进行特定的查询,

方法是先通过输入的城市查到城市ID号(_city.json文件里,网站可以下载),然后再用这个ID号取爬取天气信息