zoukankan      html  css  js  c++  java
  • pual_bot 天气插件编写

    最近在玩pual_bot,感觉很不错,最近天气插件失效了,就结合百度api重新写了一个,也提交了。

    https://github.com/coldnight/pual_bot

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 #
     4 #   Author  :   recall
     5 #   E-mail  :   tk86935367@vip.qq.com
     6 #   Date    :   14/06/25 15:59:20
     7 #   Desc    :   天气
     8 #   
     9 """ 替换原有的weather.py,并删除weather.pyc
    10 """
    11 
    12 import json
    13 import urllib,requests
    14 import sys
    15 from plugins import BasePlugin
    16 
    17 
    18 # 使用百度API获取天气预报
    19 class BaiduWeather():
    20     """docstring for BaiduWeather"""
    21     def __init__(self):
    22         self.url = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=8a47b6b4cfee5e398e63df510980697e&location="
    23 
    24     def search(self,city,callback):
    25     url = self.url +  city.encode('utf-8')                  #urllib.quote(city.decode(sys.stdin.encoding).encode('utf-8','replace'))
    26     res = requests.get(url)
    27     html = res.text
    28     json_data = json.loads(html)
    29     error = json_data.get('error')
    30     if error != 0:
    31         body = u'不支持该城市'
    32     else:
    33         result = json_data.get('results',u'没有结果')
    34         weather = result[0]
    35         c_city = weather.get('currentCity',None)
    36         weather_data = weather.get('weather_data',None)
    37         #print weather_data[0]
    38         body = u'{0}
    今天:{1},{2},{3}
    明天:{4},{5},{6}'.format(c_city,weather_data[0].get('temperature'),weather_data[0].get('weather'),weather_data[0].get('wind'), 
    39                                                     weather_data[1].get('temperature'),weather_data[1].get('weather'),weather_data[1].get('wind'))
    40     callback(body)
    41 
    42 
    43 
    44 class WeatherPlugin(BasePlugin):
    45     bdweather = None
    46     def is_match(self, from_uin, content, type):
    47         if content.startswith("-w"):
    48             self.city = content.split(" ")[1]
    49             self._format = u"
     {0}" if type == "g" else u"{0}"
    50         if self.bdweather is None:
    51         self.bdweather = BaiduWeather()
    52             return True
    53         return False
    54 
    55 
    56     def handle_message(self, callback):
    57         self.bdweather.search(self.city, callback)

    就是没怎么弄异常,有时间谁添加吧。

  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/tk091/p/3808193.html
Copyright © 2011-2022 走看看