wechat_autoreply
Introduction to the
Accidentally saw the GitHub big guy to his girlfriend wrote a daily regular wechat message program, thought that I often do not see the message of my girlfriend because of various things, resulting in their own kneel washboard, so I want to learn how to achieve a wechat automatic reply function, incidentally learn to learn. The function of this program is relatively simple. Run the program, input the wechat remarks name of the object to be automatically replied and the content to be automatically replied, and then log in wechat to realize the automatic reply to the message of the specified object. Itchat is mainly used in the program, which is an interface wechat library based on wechat web page version, which can realize various operations on wechat.
Realize the function
Query date; Query the weather; Robot chat.
Configure the environment and dependencies
Language:
Python 3.5 and aboveCopy the code
Dependent libraries:
itchat
datetime
requests
Copy the code
Weather Query API:
http://t.weather.sojson.com/api/weather/city/{city_code}
Copy the code
Chatbot:
Turing Robot http://www.turingapi.comCopy the code
Programming instructions
Get weather information
Here mainly refer to the great god, the method of https://github.com/sfyc23/EverydayWechat with a list of entities corresponding code, cities in China, according to the city code query corresponding to the weather conditions in the interface.
def isJson(resp):
try:
resp.json()
return True
except:
return False
# Get weather information
def get_weather_info(city_code):
weather_url = f'http://t.weather.sojson.com/api/weather/city/{city_code}'
resp = requests.get(url=weather_url)
if resp.status_code == 200 and isJson(resp) and resp.json().get('status') = =200:
weatherJson = resp.json()
# Today's weather
today_weather = weatherJson.get('data').get('forecast') [1]
# temperature
high = today_weather.get('high')
high_c = high[high.find(' ') + 1:]
low = today_weather.get('low')
low_c = low[low.find(' ') + 1:]
temperature = F "temperature:{low_c}/{high_c}"
# Air index
aqi = today_weather.get('aqi')
aqi = F "Air quality:{aqi}"
# the weather
tianqi = today_weather.get('type')
tianqi = F "weather:{tianqi}"
today_msg = f'{tianqi}\n{temperature}\n{aqi}\n'
return today_msg
Copy the code
Turing robot interface
This is the Turing robot here at http://www.turingapi.com. All you need to do is register and create a robot on the website, get a “userId” unique to each user and a “apiKey” unique to each robot. According to the request parameters required by the robot, To its interface http://openapi.tuling123.com/openapi/api/v2 request data.
Example:
# Turing Robot Interface
def robot(info):
#info = msg['Content'].encode('utf8')
Turing API
api_url = 'http://openapi.tuling123.com/openapi/api/v2'
The interface requests data
data = {
"reqType": 0."perception": {
"inputText": {
"text": str(info)
}
},
"userInfo": {
"apiKey": "XXX... XXX".# apiKey unique to each robot
"userId": "XXXXXX" A unique userId for each user
}
}
headers = {
'Content-Type': 'application/json'.'Host': 'openapi.tuling123.com'.'User-Agent': 'the Mozilla / 5.0 (Wi ` ndows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3486.0 '
'Safari / 537.36'
}
# request interface
result = requests.post(api_url, headers=headers, json=data).json()
Extract the text and send it to the sender
return result['results'] [0] ['values'] ['text']
Copy the code
The above program type info to return the robot’s response through the interface.
Itchat wechat interface
Itchat.readthedocs. IO itchatGitHub: github.com/littlecoder… It uses a decorator to monitor wechat messages:
@itchat.msg_register(itchat.content.TEXT)
Copy the code
Parentheses indicate the message type that ItChat listens to, and TEXT indicates the message type that ItChat listens to. In addition, ItChat supports various message types, such as: Share the MAP location of CARD business CARD information SHARING links to share PICTURE expression or photos RECORDING voice ATTACHMENT ATTACHMENT A friend request is a special message sent by the SYSTEM. For example, the system pushes a message or a group member changes, etc. NOTE notification text, such as a message is withdrawn, etc.
itchat.send(text, toUserName=userName)
Copy the code
Replies a message to the specified object. UserName is not a wechat name, it is a string of alphanumeric code, so we can get the userName of the object that sent us the message from the message we just listened to obtain, that is:
userName = msg['User']['UserName']
Copy the code
Then we can use:
msg['User']['RemarkName']
Copy the code
To judge whether it is a girlfriend or the object we want to reply to by comparing the name of the object’s wechat remarks. I can only have one object here, of course, some people may have more than one girlfriend, let me offer my knees…
Sample code for replying:
@itchat.msg_register([itchat.content.TEXT,itchat.content.PICTURE])
def reply_msg(msg):
global t, name, rtext
userName = msg['User'] ['UserName']
if t == 2:
if msg['User'] ['RemarkName'] == name:
if msg['Content'] = ="Quit":
itchat.send("The robot has been withdrawn.", toUserName=userName)
t = 0
else:
text = msg['Content']
rep = robot(text)
itchat.send(rep+"\n reply "quit", quit the bot chat", toUserName=userName)
elif t == 1:
if msg['User'] ['RemarkName'] == name:
ctn = msg['Content']
if ctn in city_dict.city_dict:
city_code = city_dict.city_dict[ctn]
wheather = get_weather_info(city_code)
itchat.send(wheather, toUserName=userName)
else:
itchat.send("Unable to obtain the city information you entered", toUserName=userName)
t = 0
else:
if msg['User'] ['RemarkName'] == name:
if msg['Content'] = ='hello':
itchat.send('hello', toUserName=userName)
elif msg['Content'] = ='the weather':
itchat.send('Please enter the name of the city you are looking for', toUserName=userName)
t = 1
elif msg['Content'] = ='date':
itchat.send(nowdate, toUserName=userName)
elif msg['Content'] = ='chat':
itchat.send('Hello, I'm artificially retarded.', toUserName=userName)
t = 2
else:
itchat.send(rtext + ', automatic message \n reply 'date', get date \ N reply 'weather', get weather \n reply 'chat', start chatting with robot ', toUserName=userName)
Copy the code
This allows us to automatically reply to a given object and simply get the date, weather, and bot chat. I am also new to itChat, so I don’t have any details. For more details, please refer to the official documents and GitHub link above.
The project address
Github.com/hh997y/wech…
summary
Very simple small project, almost no technical content, can be used to practice, but also enrich other interesting things on this, but also learn a little bit of progress every day, improve their posture level.
reference
https://github.com/sfyc23/EverydayWechat
https://blog.csdn.net/coder_pig/article/details/81357810
https://blog.csdn.net/Lynn_coder/article/details/79436539
Copy the code