Python+ITchart to realize wechat robot's automatic reply to specified friends and groups

Here I mainly use three robots, which can be switched.

1. Turing robot

    http://www.tuling123.com

2. The Turing robot on showapi (feels the most intelligent, can recognize wechat expressions, English, Chinese, etc., but because I am an ordinary member, I call it 1000 times a day)

    https://www.showapi.com/api/lookPoint/60

3. Molly robot (rich in functions, but only recognize Chinese, not English, wechat expression)

    http://www.itpk.cn/robot.php

The code is as follows:

from itchat.content import *
import itchat
import json
import requests
from ShowapiRequest import ShowapiRequest
import os
import  time
import  datetime
import urllib
import urllib.request


# Call Turing's api,Reply content according to chat message
def tuLing(info):
    appkey="************"    #Self registration
    url="http://www.tuling123.com/openapi/api?key=%s&;info=%s"%(appkey,info)
    req=requests.get(url)
    content=req.text
    data=json.loads(content)
    answer=data['text']
    return answer

# call showApi Turing robot of,Reply content according to chat message
def showRobot(info="",nickName="",imgDir=""):
    my_appId='****'     #Self registration
    my_appSecret='******************'    #Self registration
    r = ShowapiRequest("http://route.showapi.com/60-27", my_appId, my_appSecret)
    r.addBodyPara("userid", nickName)
    if info !="":
        r.addBodyPara("info", info)
    else:
        r.addBodyPara("info", "Hello")
    if imgDir !="" :
        r.addFilePara("img", imgDir)
    res = r.post()
    data=json.loads(res.text)
    return data['showapi_res_body']['text']

# Call the Molly robot yes,Reply content according to chat message
# Directive:
# Regional weather    Shanghai weather    Query weather forecast of Shanghai (city level or county level area)
# weather    weather    Visit according to IP Automatic weather forecast
# @tq Your ip address    @tq8.8.8.8    query IP The address is 8..8.8.8 Weather forecast for
# @ip Your ip address    @ip8.8.8.8    query IP The address is 8..8.8.8 Location and latitude and longitude of
# ip    ip    Query visitor's IP Address Details
# @qq Enquiry QQ number    @qq123456    query QQ Information for number 123456
# @lol Hero League region--Role name    @lol Ionia--I want to be super God.    Look up Ionia. I want to know what I'm up to
# @sfz ID card No.    @sfz111111111111111111    Find ID number, location, birthday and gender of citizen
# @sjh Phone number    @sjh18888888888    Query mobile phone number, city code and card type
# @cy Four character idioms    @cy Take the lead    The idiom "take the lead"
# joke    joke    Random return to a joke
# Guanyin soul sign    Guanyin soul sign    Random selection of Guanyin holy stick
# Veteran sign    Veteran sign    Random selection of old moonstick
# God of wealth    God of wealth    Random selection of God of wealth

def moLi_Robot(question):
    Key='***************'   #Self registration
    Secret='*******'         #Self registration
    url='http://i.itpk.cn/api.php?question=%s&api_key=%s&api_secret=%s'%(question,Key,Secret)
    req=requests.get(url)
    content=req.text
    if question in ['joke','Guanyin soul sign','Veteran sign','God of wealth']:
        if content.startswith(u'\ufeff'):
            content = content.encode('utf8')[3:].decode('utf8')
        jsondata=json.loads(content)

        # Handle'joke','Guanyin soul sign','Veteran sign','God of wealth'data
        if question=='joke':
            data='%s\n%s'%(jsondata['title'],jsondata['content'])
        elif question=='Guanyin soul sign':
            data='Sign number:%s\n win a lottery:%s\n doggerel foretelling one's fortune:%s\n Solution signature:%s\n Vernacular interpretation:%s\n'%(jsondata['number1'],jsondata['haohua'],jsondata['qianyu'],jsondata['shiyi'],jsondata['jieqian'],)
        elif question=='Veteran sign':
            data='Sign number:%s\n win a lottery:%s\n Poetic flavour:%s\n Solution signature:%s\n Notes:%s\n Vernacular interpretation:%s\n'%(jsondata['number1'],jsondata['haohua'],jsondata['shiyi'],jsondata['jieqian'],jsondata['zhushi'],jsondata['baihua'])
        else:  # God of wealth
            data='Sign number:%s\n doggerel foretelling one's fortune:%s\n Notes:%s\n Solution signature:%s\n commentary:%s\n Meaning:%s\n Marriage:%s\n Cause:%s\n Fame and fortune:%s\n Lost article:%s\n Emigrate from abroad:%s\n Liu Jia:%s\n Seek wealth:%s\n transaction:%s\n disease:%s\n litigation:%s\n Transportation route:%s\n Plan affairs:%s\n business:%s\n'%(
                jsondata['number1'],jsondata['qianyu'],jsondata['zhushi'],jsondata['jieqian'],jsondata['jieshuo'],jsondata['jieguo'],jsondata['hunyin'],jsondata['shiye'],jsondata['gongming'],jsondata['shiwu'],jsondata['cwyj'],jsondata['liujia'],jsondata['qiucai'],jsondata['jiaoyi'],jsondata['jibin'],jsondata['susong'],jsondata['yuntu'],jsondata['moushi'],jsondata['hhzsy'],
            )
    elif question=='instructions':
        data="""Directive:
//Regional weather \ tshanghai weather \ Tquery the weather forecast of Shanghai (city level or county level region) \ n
//Weather \ tclimate \ tautomatically obtain weather forecast according to access IP \ n
@tq Your ip address\t@tq8.8.8.8\t query IP The address is 8..8.8.8 Weather forecast for\n
@ip Your ip address\t@ip8.8.8.8\t query IP The address is 8..8.8.8 Location and latitude and longitude of\n
ip\tip\t Query visitor's IP Address Details\n
@qq Enquiry QQ number\t@qq123456\t query QQ Information for number 123456\n
@lol Hero League region--Role name\t    @lol Ionia--I want to be super God.\t Look up Ionia. I want to know what I'm up to\n
@sfz ID card No.\t@sfz111111111111111111\t Find ID number, location, birthday and gender of citizen\n
@sjh Phone number    \t@sjh18888888888\t Query mobile phone number, city code and card type\n
@cy Four character idioms\t@cy Take the lead\t[Take the lead\n
//Joke \ Ttrack a joke at random \ n
//Avalokitesvara \ tDesign Avalokitesvara at random \ n
//Old moonstick \ t old moonstick \ t randomly select old moonstick \ n
//God of wealth smart signer \ tDesign of God of wealth smart signer \ tDesign of God of wealth smart signer at random \ n
"""
    else:
        data=content
    # return jsondata
    return data

# according to NickName[]lookup UserName[]
def findUserName(toNickName):
    u = []
    for i in toNickName:
        try:
            u1 = itchat.search_friends(i)[0]['UserName']
            u.append(u1)
            print('Contacts have been added\t',i,'\t Objects with chat robots')
        except Exception as E:
            print(i,"You don't have this contact")
    print('------------------------------------')
    return u

# Group based NickName[]lookup UserName[]
def findQunUserName(toQunNickName):
    u = []
    for i in toQunNickName:
        try:
            u1 = itchat.search_chatrooms(i)[0]['UserName']
            u.append(u1)
            print('Group already\t',i,'\t Objects with chat robots')
        except Exception as E:
            print(i,"You don't have this group")
    print('------------------------------------')
    return u

if __name__ == '__main__':
    # Login send
    itchat.auto_login(hotReload=True,statusStorageDir='itchat.pkl')
    myUserName=itchat.get_friends(update=True)[0]['UserName']
    myNickName=itchat.get_friends(update=True)[0]['NickName']



    # Be a robot to a designated person
    toSendUserNickName = ['sssss', 'ttttt', 'mmmmm','sssssssssssssssss']
    toRobotUserName = findUserName(toSendUserNickName)

    # Be a robot to a specified group
    toSendQunNickName = ['test','test2']
    toRobotQunUserName = findQunUserName(toSendQunNickName)


    # Robots used
    RobotName=['tuLing','showRobot','moLi_Robot']
    usingRobot=RobotName[2]

    #Swarm Robots
    @itchat.msg_register(TEXT,isGroupChat=True)
    def reply(msg):
        answer=""
        for i in toRobotQunUserName:
            if msg['FromUserName'] == i and msg['ActualUserName'] != myUserName :
                if usingRobot=='tuLing':
                    answer = tuLing(msg['Text'])
                elif usingRobot=='showRobot':
                    answer = showRobot(msg['Text'])
                else:
                    answer = moLi_Robot(msg['Text'])
                # print(answer)
                itchat.send_msg(answer, msg['FromUserName'])
        return


    @itchat.msg_register([TEXT,PICTURE],isFriendChat=True)
    def replyText(msg):
        fromNum=0 #toSendUserNickName[fromNum]Send me a message
        toNum=0 #Judge me toSendUserNickName[toNum]Send message

        for i in toRobotUserName:
            # Judge that the person sending the message is the one you choose
            if msg['FromUserName']==i :
                # Transferred file type is photo
                if msg['Type']=='Picture':
                    # Judge which robot to use
                    if usingRobot=='showRobot':
                        # Download photos
                        path =r'.\Info\Picture'
                        try:
                            os.makedirs(path)
                            print("%s Folder created successfully" % path)
                        except Exception as e:
                            print("%s Folder creation failed, this folder may already exist" % path)

                        path += r'\%s' % msg['FileName']
                        msg['Text'](path)

                        # Print information
                        an = showRobot(imgDir=msg['Text']())
                        print(datetime.datetime.now(), '\n', toSendUserNickName[fromNum], 'Give me:\n\t', msg['FileName'], '\t store in', path)
                    elif usingRobot=='tuLing':
                        an = tuLing('Photo')
                    else:
                        an = moLi_Robot('Photo')

                # It's text
                else:
                    # Judge which robot to use
                    if usingRobot=='tuLing':
                        an = tuLing(msg['Text'])
                    elif usingRobot=='showRobot':
                        an = showRobot(msg['Text'])
                    else:
                        an= moLi_Robot(msg['Text'])

                print(datetime.datetime.now(),'\n',toSendUserNickName[fromNum],'Give me:\n\t',msg['Text'],'\n')
                print(datetime.datetime.now(),'\n','I give', toSendUserNickName[fromNum], ':\n\t', an,'\n')
                itchat.send_msg(an,i)
                break
            else:
                fromNum += 1

        # I'm sending messages to the people named above, not robots
        for j in toRobotUserName:
            if msg['ToUserName']==j:
                break
            else:
                toNum += 1

        if msg['FromUserName']==myUserName:
            # Transferred file type is photo
            if msg['Type'] == 'Picture':
                print(datetime.datetime.now(),'\n','I give',toSendUserNickName[toNum],':\n\t',msg['FileName'],'\n')
            else:
                print(datetime.datetime.now(), '\n', 'I give', toSendUserNickName[toNum], ':\n\t', msg['Text'], '\n')

        return

    itchat.run()

Robots to register:

  

  

  

 

Modify robot:

  

Modify the use of robots for those friends (here is your wechat comment on them):

  

Modify to use robots for those groups (here is the name of the group on your wechat):

   

   

If you chat with a designated friend, the chat message will be reflected on the debugging platform, and if it is a group reply, it will not.

  

Keywords: Python JSON PHP Mobile

Added by iBlizz on Fri, 06 Dec 2019 00:26:08 +0200