【コード】微信自動返信ロボット

2641 ワード

apiaiロボットリファレンスゼロから微信ロボット(二):図霊ロボットとapi.ai関連インタフェースを使用する
import requests
import apiai
from wxpy import Bot
import json
import time

def apiai_reply(msg_content, user_id):
    print("try APIAI reply...")
    #    client TOCKEN,
    APIAI_TOKEN = 'e737462200a64c3fb29f204358e407fb'
    # APIAI_TOKEN = 'fa5303d038e34077ae992c60d9aff90c'
    ai = apiai.ApiAI(APIAI_TOKEN)
    request = ai.text_request()
    request.lang = 'zh-CN'
    request.session_id = user_id
    request.query = msg_content
    print('-----------')
    response = request.getresponse()
    print(response)
    s = json.loads(response.read().decode('utf-8'))
    print(s)
    if s['result']['action'] == 'input.unknown':
        raise Exception('api.ai cannot reply this message')
    if s['status']['code'] == 200:
        print("use APIAI reply")
        print('return code: ' + str(s['status']['code']))
        return s['result']['fulfillment']['speech']


bot = Bot()
#   puid
bot.enable_puid('wxpy_puid.pkl')
my_friend = bot.friends().search('appium')[0]


@bot.register(my_friend)
def reply(msg):
    print(msg.text)
    print(my_friend.puid)
    if msg.text == '1':
        return 'I\'m Still Alive!! ' + time.strftime('%y/%m/%d-%H:%M:%S', time.localtime())
    else:
        return apiai_reply(msg.text, my_friend.puid)


bot.join()

プログラムがrequest = ai.text_request()にブロックされた原因は不明で、何の間違いも報告しないで、お母さん、図霊に変えるのは簡単です.
from wxpy import Bot, embed
import requests


TULING_TOKEN = '540fcc683f664962998f8b3cb92eb721'

#   
bot = Bot(cache_path=True)
#   uid,     uid
bot.enable_puid('wxpy_puid.pkl')
me = bot.friends().search('    ')[0]
print(me.puid)


# wxpy        Tuling   ,tuling.do_reply(msg)
#         ,            
@bot.register(bot.self, except_self=False)
def rely_self(msg):
    if msg.text:
        url_api = 'http://www.tuling123.com/openapi/api'
        data = {
            'key': TULING_TOKEN,
            'info': msg.text,  #          
            'userid': me.puid  #          
        }
        s = requests.post(url_api, data=data).json()
        if s['code'] == 100000:
            print(s['text'])  #          
            # msg.reply(s['text'])  #         ,  return
            return 'tuling reply'+s['text']
        else:
            #      
            print(s['code'])


embed()