kumufengchun

最近,同学搞了个微信自动回复,只要再群里说话,就会回复,感觉挺好玩,现把代码分享下如下,先看看效果,如下图

左边的是机器人,右边的是我和它聊的。

 

现在开始把!

首先需要去图灵申请个apikey,图灵官网http://www.turingapi.com/

 

配置文件Wxpy.ini如下

[tuling]
#此处是从图灵申请的apikey
apikey="*****"

[wechat]
#utf-8 gbk
charset="utf-8"

#好友昵称,目前仅支持一个,不需要则留空
friend=""

#群组昵称,目前仅支持一个,不需要则留空
group=""

#自动回复消息前缀
prefix=" "

#自动回复消息后缀
subfix=" "

 

代码文件Wxpy.py如下:

#coding:utf-8
__author__ = \'***\'
import time
import sys
import os
import ctypes
import Tkinter
import tkMessageBox
import json
import requests
import re
import subprocess
import datetime
import ConfigParser
import wxpy


def msgBox(title, info):
    newTitle = title.decode(\'utf-8\')
    newInfo = info.decode(\'utf-8\')
    print newTitle, newInfo
    top = Tkinter.Tk()
    top.withdraw()
    tkMessageBox.showinfo(title, info)
    #tkMessageBox.askyesno(title, info)
    #ctypes.windll.user32.MessageBoxA(0, newInfo, newTitle, 0)
    #os.system(\'msg %username% /TIME:2 \'+info)


def test():
    print "%s."%sys._getframe().f_code.co_name
    try :
        time.sleep(0.3)
    except Exception,e:
        print e
        return
        
def chatbot_init():
    bot = ChatBot("Terminal", 
    storage_adapter = "chatterbot.storage.JsonFileStorageAdapter", 
    logic_adapters = [ 
                    "chatterbot.logic.MathematicalEvaluation", 
                    "chatterbot.logic.TimeLogicAdapter", 
                    "chatterbot.logic.BestMatch" 
                    ], 
    input_adapter = "chatterbot.input.TerminalAdapter", 
    output_adapter = "chatterbot.output.TerminalAdapter", 
    database = "./database.db" 
    ) 
 

def tuling_api(api_key, info):
    url = \'http://www.tuling123.com/openapi/api?key=\'+api_key+\'&info=\'+info
    print url
    res = requests.get(url)
    res.encoding = \'utf-8\'
    jsonRes = json.loads(res.text)#str to dict
    #print(\'tuling_api: \' + jsonRes[\'text\'])
    return jsonRes[\'text\']
    
if "__main__" == __name__:
    # if(len(sys.argv) < 4):
        # msgBox("error", "para error!")
    # deviceName=sys.argv[1]
    try:
        reload(sys)
        sys.setdefaultencoding(\'utf-8\')
        
        #api_key=\'302dbb3ed3f845e5863c9ca7210acc2a\'
        api_key = \'\'
        targetFriend = \'\'
        targetGroup = \'\'
        strPrefix = \'\'
        strSubfix = \'\'
        charset = \'\'
        cf = ConfigParser.ConfigParser()
        cf.read(\'Wxpy.ini\')
        api_key = cf.get(\'tuling\',\'apikey\').strip(\'"\').strip()
        targetFriend = cf.get(\'wechat\',\'friend\').strip(\'"\').strip()
        targetGroup = cf.get(\'wechat\',\'group\').strip(\'"\').strip()
        strPrefix = cf.get(\'wechat\',\'prefix\').strip(\'"\')
        strSubfix = cf.get(\'wechat\',\'subfix\').strip(\'"\')
        charset = cf.get(\'wechat\',\'charset\').strip(\'"\').strip()
        targetAutoReply = []
        
        print len(api_key), api_key
        print len(targetFriend), targetFriend.decode(charset)
        print len(targetGroup), targetGroup.decode(charset)
        print len(charset), charset
        if(len(api_key) == 0 or ( len(targetFriend) == 0 and len(targetGroup) == 0) ):
            msgBox(\'参数错误\', \'请参照使用说明 然后重新打开软件\')
            sys.exit(1)
        #tuling = wxpy.Tuling(api_key=\'302dbb3ed3f845e5863c9ca7210acc2a\')
        bot = wxpy.Bot(cache_path=True)
        friends_stat = bot.friends().stats()
        #print friends_stat
        for province, count in friends_stat["province"].iteritems():
            #print "province \'%s\', count %s"%(province, count)
            pass
        for city, count in friends_stat["city"].iteritems():
            #print "city \'%s\', count %s"%(city, count)
            pass
        for sex, count in friends_stat["sex"].iteritems():
            #print "sex \'%s\', count %s"%(sex, count)
            pass
        
        myGroup = None
        groups = bot.groups()
        count=0
        for group in groups:
            #print group.user_name
            if group.nick_name!=None:
                #print group.nick_name
                if len(targetGroup) != 0 and group.nick_name.find(targetGroup.decode(charset)) != -1:
                    print \'Got it in groups.++++++++++++++++++++++++++++++++++++++\'
                    myGroup = group
                    targetAutoReply.append(myGroup)
            count+=1
        print "groupCnt=%d."%count
        
        myFriend = None
        friends = bot.friends()
        count=0
        for friend in friends:
            #print friend.user_name
            if friend.nick_name!=None:
                #print friend.nick_name
                if len(targetFriend) != 0 and friend.nick_name.find(targetFriend.decode(charset)) != -1:
                    print \'Got it in friends.------------------------------------\'
                    myFriend = friend
                    targetAutoReply.append(myFriend)
                pass
            count+=1
        print "friendCnt=%d."%count
        
        tmpStr = strPrefix + \'Hi.\' + strSubfix# + str(datetime.datetime.now())
        if myGroup != None:
            myGroup.send(tmpStr.decode(\'utf-8\',\'ignore\'))
        if myFriend != None:
            myFriend.send(tmpStr.decode(\'utf-8\',\'ignore\'))
        #bot.file_helper.send(tmpStr.decode(\'utf-8\',\'ignore\'))
        
        
        print \'-----------------------------------\'
        
        # 打印来自其他好友、群聊和公众号的消息
        @bot.register()
        def print_others(msg):
            print \'From others: \'
            #print msg
            print msg.sender.name,msg.text,msg.type

        # # 回复 groups 的消息 (优先匹配后注册的函数!)
        # @bot.register(myGroup)
        # def auto_reply_groups(msg):
            # print \'From auto_reply_groups:\'
            # #print msg
            # print msg.sender.name,msg.text,msg.type
            # #msg.sender.mark_as_read()
            # if msg.type == \'Text\': #如果是文字,就利用图灵机器人api回复,return和msg.reply_msg效果一样
                # print \'Text.\'
                # #replyText = tuling.do_reply(msg)
                # #replyText = tuling.reply_text(msg)
                # replyText = tuling_api(api_key, msg.text)
                # replyText = strPrefix + replyText + strSubfix
                # print \'===<\', replyText
                # #msg.sender.send(replyText)
                # msg.reply_msg(replyText)
                # #return replyText
            # elif msg.type == \'Picture\': #如果接受到图片,就自动回复同样的图片
                # print (\'this is Picture:{}\'.format(msg.file_name))
                # savaPath = msg.file_name
                # msg.get_file(savaPath)
                # msg.reply_image(savaPath)
            # else:#其它的就转发回给发送人
                # msg.forward(msg.sender)
            
        # 回复 friends 的消息 (优先匹配后注册的函数!)
        @bot.register(targetAutoReply)
        def auto_reply(msg):
            if len(targetAutoReply) == 0:
                return
            print \'From auto_reply:\'
            #print msg
            print msg.sender.name,msg.text,msg.type
            #msg.sender.mark_as_read()
            if msg.type == \'Text\': #如果是文字,就利用图灵机器人api回复,return和msg.reply_msg效果一样
                print \'Text..\'
                if msg.text.startswith(strPrefix) and msg.text.endswith(strSubfix):
                    return
                #replyText = tuling.do_reply(msg)
                replyText = tuling_api(api_key, msg.text)
                replyText = strPrefix + replyText + strSubfix
                print \'===<\', replyText
                #msg.sender.send(replyText)
                msg.reply_msg(replyText)
                #return replyText
            elif msg.type == \'Picture\': #如果接受到图片,就自动回复同样的图片
                print (\'this is Picture:{}\'.format(msg.file_name))
                savaPath = msg.file_name
                msg.get_file(savaPath)
                msg.reply_image(savaPath)
            else:#其它的就转发回给发送人
                msg.forward(msg.sender)
            
        # # 自动接受新的好友请求
        @bot.register(msg_types=wxpy.FRIENDS)
        def auto_accept_friends(msg):
            print \'From auto_accept_friends:\'
            #print msg
            print msg.sender.name,msg.text,msg.type
            # # 接受好友请求
            # #new_friend = msg.card.accept()
            # # 向新的好友发送消息
            # #new_friend.send(\'哈哈,我自动接受了你的好友请求\')
        
        wxpy.embed()
        # # 进入Python命令行,让程序保持运行
        while(1):
            pass
    except Exception,e:
        print e
    finally:
        sys.exit(1)

有兴趣的可以玩玩,感觉挺好玩。 

分类:

技术点:

相关文章: