pual_bot 天氣外掛編寫

weixin_34377065發表於2014-06-25

最近在玩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}\n今天:{1},{2},{3}\n明天:{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"\n {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)

 

就是沒怎麼弄異常,有時間誰新增吧。

相關文章