Created
March 28, 2013 13:59
-
-
Save ragnraok/5263327 to your computer and use it in GitHub Desktop.
WeiTranslator.py 利用微信平台的开放接口写的一个通过调用google翻译的API进行翻译的小工具,还有一些彩蛋神码的。。。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from flask import Flask, request, make_response | |
from translator import google_translate | |
from moe_pic import get_pict | |
from douban_music import get_music | |
from logging.handlers import RotatingFileHandler | |
import libxml2 | |
import time | |
import logging | |
import os | |
import hashlib | |
app = Flask(__name__) | |
def make_text_res(to_user, from_user, create_time, content): | |
text_res = """ | |
<xml> | |
<ToUserName><![CDATA[%s]]></ToUserName> | |
<FromUserName><![CDATA[%s]]></FromUserName> | |
<CreateTime>%s</CreateTime> | |
<MsgType><![CDATA[text]]></MsgType> | |
<Content><![CDATA[%s]]></Content> | |
<FuncFlag>0</FuncFlag> | |
</xml> | |
""" % (to_user, from_user, create_time, content) | |
return text_res | |
def make_music_res(to_user, from_user, create_time, title, music_url): | |
music_res = u""" | |
<xml> | |
<ToUserName><![CDATA[%s]]></ToUserName> | |
<FromUserName><![CDATA[%s]]></FromUserName> | |
<CreateTime>%s</CreateTime> | |
<MsgType><![CDATA[music]]></MsgType> | |
<Music> | |
<Title><![CDATA[%s]]></Title> | |
<Description><![CDATA[]]></Description> | |
<MusicUrl><![CDATA[%s]]></MusicUrl> | |
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl> | |
</Music> | |
<FuncFlag>0</FuncFlag> | |
</xml> | |
""" % (to_user, from_user, create_time, title, music_url, music_url) | |
return music_res | |
def make_pic_res(to_user, from_user, create_time, pict_url): | |
pic_res = u""" | |
<xml> | |
<ToUserName><![CDATA[%s]]></ToUserName> | |
<FromUserName><![CDATA[%s]]></FromUserName> | |
<CreateTime>%s</CreateTime> | |
<MsgType><![CDATA[news]]></MsgType> | |
<ArticleCount>1</ArticleCount> | |
<Articles> | |
<item> | |
<Title><![CDATA[Moe~喵]]></Title> | |
<Description><![CDATA[]]></Description> | |
<PicUrl><![CDATA[%s]]></PicUrl> | |
<Url><![CDATA[]]></Url> | |
</item> | |
</Articles> | |
<FuncFlag>1</FuncFlag> | |
</xml> | |
""" % (to_user, from_user, create_time, pict_url) | |
return pic_res | |
@app.route("/", methods=("POST", "GET")) | |
def index(): | |
if request.method == "POST": | |
app.logger.info("user post data") | |
xmldata = request.data | |
doc = libxml2.parseDoc(xmldata) | |
from_user = doc.xpathEval("//FromUserName")[0].content | |
to_user = doc.xpathEval("//ToUserName")[0].content | |
msg_type = doc.xpathEval("//MsgType")[0].content | |
now = str(time.time()) | |
app.logger.info("from_user: %s, to_user: %s, msg_type: %s" % | |
(from_user, to_user, msg_type)) | |
if msg_type.strip().lower() == 'text': | |
content = doc.xpathEval("//Content")[0].content | |
app.logger.info("content: %s" % content) | |
if content.strip().lower() == "music": | |
""" | |
play a music | |
""" | |
music_title, music_url = get_music() | |
app.logger.info("music_title: %s, music_url: %s" % | |
(music_title, music_title)) | |
return make_response(make_music_res(from_user, to_user, now, | |
music_title, music_url)) | |
elif content.strip().lower() == "moe": | |
pict_url = get_pict() | |
app.logger.info("pict_url: %s" % pict_url) | |
return make_response(make_pic_res(from_user, to_user, now, | |
pict_url)) | |
else: | |
translated_text = google_translate(content) | |
app.logger.info("translated_text: %s" % translated_text) | |
return make_response(make_text_res(from_user, to_user, now, | |
translated_text)) | |
else: | |
return make_response(make_text_res(from_user, to_user, now, | |
u"一支穿云箭,千万绅士来相见")) | |
elif request.method == "GET": | |
app.logger.info("an authentication") | |
token = "RagnarokStack" | |
signature = request.args.get('signature', None) | |
timestamp = request.args.get('timestamp', None) | |
nonce = request.args.get('nonce', None) | |
echostr = request.args.get('echostr', None) | |
tmpList = [token, timestamp, nonce] | |
tmpList.sort() | |
tmpstr = "%s%s%s" % tuple(tmpList) | |
hashstr = hashlib.sha1(tmpstr).hexdigest() | |
if hashstr == signature: | |
return make_response(echostr) | |
else: | |
return make_response(u"别往这里看啊,笨蛋!") | |
def init_app(): | |
app.config.from_pyfile("config.py") | |
init_logger() | |
def init_logger(): | |
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' | |
'[in %(pathname)s:%(lineno)d]') | |
stream_handler = logging.StreamHandler() | |
stream_handler.setLevel(logging.DEBUG) | |
stream_handler.setFormatter(formatter) | |
app.logger.addHandler(stream_handler) | |
file_handler = RotatingFileHandler(app.config['LOG_FILE'], maxBytes=100000, | |
backupCount=10) | |
file_handler.setLevel(logging.DEBUG) | |
file_handler.setFormatter(formatter) | |
app.logger.addHandler(file_handler) | |
app.logger.setLevel(logging.DEBUG) | |
if __name__ == '__main__': | |
init_app() | |
# Bind to PORT if defined, otherwise default to 5000. | |
port = int(os.environ.get('PORT', 5000)) | |
app.run(host="0.0.0.0", port=port) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SECRET_KEY = "LItXhDi4nVAj0f5H27u9" | |
LOG_FILE = "WeiGoogleTranslator.log" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf8 -*- | |
import urllib2, json, random | |
def get_music(): | |
""" | |
get a random music from douban FM, | |
return the url of music | |
""" | |
url = "http://douban.fm/j/mine/playlist" | |
response = urllib2.urlopen(url) | |
response_s = response.read() | |
response_json = json.loads(response_s) | |
songs = response_json["song"] | |
index = random.randint(0, len(songs) - 1) | |
print index, len(songs) | |
return (songs[index]["title"], songs[index]["url"]) | |
if __name__ == '__main__': | |
result = get_music() | |
print result | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf8 -*- | |
from HTMLParser import HTMLParser | |
import urllib2, json, random | |
def get_html(): | |
url = "http://tu.duowan.com/tag/6204.html?offset=0&order=created&math=0.1" | |
res = urllib2.urlopen(url) | |
res_s = res.read() | |
res_json = json.loads(res_s) | |
return res_json["html"] | |
class ImgParser(HTMLParser): | |
def __init__(self, *args, **kwargs): | |
HTMLParser.__init__(self, *args, **kwargs) | |
self.img_list = [] | |
def handle_starttag(self, tag, attrs): | |
if tag == 'img': | |
self.img_list.append(attrs[0][1]) | |
def get_pict(): | |
html = get_html() | |
parser = ImgParser() | |
parser.feed(html) | |
index = random.randint(0, len(parser.img_list) - 2) | |
print index, len(parser.img_list) | |
return parser.img_list[index] | |
if __name__ == '__main__': | |
print get_pict() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib, urllib2, json | |
def is_cn_or_en(i): | |
""" | |
return True if i is chinese | |
""" | |
o = ord(i) | |
return not (o < 128 or 0x4e00 <= o < 0x9fa6) | |
def if_zh(_str): | |
for i in _str: | |
if is_cn_or_en(i): | |
return True | |
return False | |
def google_translate(text): | |
url = 'http://translate.google.cn/translate_a/t' | |
has_zh = if_zh(text) | |
source_language = None | |
target_language = None | |
if has_zh: | |
source_language = 'zh-CN' | |
target_language = "en" | |
else: | |
source_language = "en" | |
target_language = "zh-CN" | |
values = {"client": "t", "text": text, "hl": "zh-CN", | |
"sl": source_language, "tl": target_language, "ie": "UTF-8", | |
"oe": "UTF-8"} | |
data = urllib.urlencode(values) | |
request = urllib2.Request(url, data) | |
request.add_header('User-Agent', | |
"Mozilla/4.0 (compatible; MSIE 6.0;Windows NT 5.1; SV1; .NET CLR 2.0.50727)") | |
response = urllib2.urlopen(request) | |
response_str = response.read() | |
result = response_str[4:response_str.index(",") - 1] | |
return result | |
if __name__ == "__main__": | |
while True: | |
s = raw_input("Please input something: ") | |
google_translate(s) |
Author
ragnraok
commented
Mar 28, 2013
整个应用搭建在heroku上,偶尔微信服务器会发送不了消息到应用上。。估计是由于服务器是在美帝的原因把。。。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment