#!/usr/bin/python# coding=utf-8import jsonimport urllibimport datetimefrom urllib import urlencode#------------------ ----------------# {# "Reason": "Successful Return", # "Result":/* Depending on the code value, the returned field is different */# {# "code": 100000, /* Data type returned, please check the data type API according to the code value */# "text": "Hello" #},# "Error_code": 0#}#--------------------------- -------def main (): Print TM () Appkey = "****************************" # Appkey print ' Your name: ' user = Raw_ Input (') print ' Where is: ' loc = Raw_input () print '----> OK, you can ask me question <----' Whil E 1:print TM (), ', User, ': \n\t ', q = raw_input () if q = = ' exit ': Break # 1. Questions and Answers res = request1 (user, loc, Q, Appkey, "GET") print TM (), ' Robot: \n\t ', result (RES) def result (RES): if res : Error_code = res["Error_code"] if Error_code = = 0: # Successful request return res["result" [' Text '] Else:rEturn "%s:%s"% (res["Error_code"], res["Reason"]) Else:return "Request API Error" DEF TM (): now = DATETIME.D Atetime.now () return Now.strftime ('%m-%d%h:%m:%s ') # Q/A def request1 (user, loc, que, appkey, m= "GET"): url = "/http" Op.juhe.cn/robot/index "params = {" Key ": Appkey, # Appkey" info ": que, # content to be sent to the bot, no more than 30 characters" Dtype ":", # Returns the format of the data, JSON or XML, the default is JSON "LOC": Loc, # location, such as Beijing Zhongguancun "lon": "", # Longitude, latitude 116.234632 (6 digits after the decimal point), need Written as 116234632 "lat": "", # Latitude, latitude 40.234632 (6 digits after the decimal point), need to write as 40234632 "userid": User, # 1~32 bit, this userid for each of your own users, Association for context} params = UrlEncode (params) if m = = "GET": F = Urllib.urlopen ("%s?%s"% (URL, params)) Else: f = urllib.urlopen (URL, params) content = F.read () res = json.loads (content) return res# data type Def request2 ( Appkey, m= "GET"): url = "Http://op.juhe.cn/robot/code" params = {"Dtype": "", # Returns the data format, JSON or XML, default JSON "Key": Appkey, # you ShenPlease use the Appkey of this interface in the Application Detail page query} params = UrlEncode (params) if m = = "GET": F = Urllib.urlopen ("%s?%s"% (URL, param s)) Else:f = Urllib.urlopen (URL, params) content = F.read () res = json.loads (content) if res:e Rror_code = res["Error_code"] if Error_code = = 0: # Successfully requested print res["result"] else: Print "%s:%s"% (res["Error_code"], res["Reason"]) else:print "Request API Error" if __name__ = = ' __main __ ': Main ()
Python chat Bots