One, foreword
As a result of the automatic chat of wechat robot on Douyin, I realized the automatic reply of wechat, monitoring messages and anti-withdrawal of messages by using ItChat and Turing robot. Weekend mood bad engaged in a wechat chat robot chat with me.
Note:
1, Turing robot update, for the newly registered number is not authenticated each number only 2 requests, please complete the identity authentication as soon as possible after registration.
2, use some knowledge of Python (not and not important), can install.
3, there are a lot of people want to use their own WeChat playing the trumpet, but unfortunately, WeChat authorities have banned this behavior, actually auto reply robot essence is implemented on the basis of the principle of WeChat web version, that is to say a lot of WeChat trumpet, even by limiting the WeChat web version can’t log in, then the robot will not succeed. So, first make sure wechat can be on the web version.
4. Regarding security issues, since Itchat is an open source library developed by others, there is no security risk. Make sure you are aware of the risks before you start testing.
The itchat library
Itchat’s warehouse address: github.com/littlecoder…
Itchat is an open source wechat id interface, and using Python to call wechat has never been easier
With less than 30 lines of code, you can build a wechat robot that can process all the information.
.
Download and install Python
Download address: www.python.org/downloads/w… Download the latest version 3.7.3
Click download Windows x86-64 Executable Installer to download Windows 64 bit executable file
For details, see blog.csdn.net/mingzhuo_12…
After downloading, press Win and type Python to see Python3.7 and IDLE Python
Download itchat library
Open CMD or Python3.7
pip install itchat
Copy the code
Check whether the download is successful
python -c "import itchat"
Copy the code
If no error message is displayed, you have installed the experimental environment.
5. Simple examples
Through a simple example to let readers experience how simple it is to write a wechat robot through ItChat, the code function: scan the code after logging in to send a message to the file assistant, monitor the received file information, print out, the specific code is as follows.
Note: the rest of the code runs on the Python3.7 client
import itchat
import time
@itchat.msg_register(itchat.content.TEXT)
def reply_msg(msg):
print("Received a message:",msg.text)
if __name__ == '__main__':
itchat.auto_login()
time.sleep(5)
itchat.send("Hello, file assistant.", toUserName="filehelper")
itchat.run()
Copy the code
Code execution results
First, a two-dimensional code picture will pop up, and after scanning, it will log in to wechat on the webpage. After a short interval, the file assistant will receive the relevant information
Hello file assistant
A message is then sent to that account using another account, and the console prints out the received message
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
TERM environment variable not set.
Login successfully asRobot Pig Start auto replying. Received a message: HelloCopy the code
Through the above 8 lines of effective code to achieve a simple skill, cool or not cool, with this idea, we can expand, for example, add an automatic reply function, such as when busy, others send you a message, automatic reply: “busy, I will reply to you later” and so on.
Six, group chat
After the revision of wechat webpage, the interfaces of creating group chats, pulling people into groups and deleting group chats are no longer used. Now itChat can be used to search group chats, send messages to group chats, and monitor group chats. The code examples are as follows:
import itchat
import time
@itchat.msg_register(itchat.content.TEXT, isGroupChat=True)
def reply_msg(msg):
print("Received a group message:", msg['ActualNickName'], msg['Content'])
def after_login(a):
# Get the full group chat list
print("The full list of group chats is as follows:")
print(itchat.get_chatrooms())
# Find specific group chats
time.sleep(10)
# Search by group name
chat_rooms = itchat.search_chatrooms(name='Piggy Python Learning Exchange Group')
if len(chat_rooms) > 0:
itchat.send_msg('test', chat_rooms[0] ['UserName'])
if __name__ == '__main__':
itchat.auto_login(loginCallback=after_login)
itchat.run()
Copy the code
The code execution result is as follows:
The full group chat list is as follows: [<Chatroom: {'MemberList': <ContactList: []>, 'Uin': 0.'UserName': '@@60dc5027bbbb83d532aa633b8d126szcf497a98ceea5c098d2c65f0932139b88'.'NickName': 'Hubei people born in shenzhen in the 1990s'.'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgetheadimg? seq=625714901&username=@@60dc502769a783d532aa633b8d126190f497a98ceea5c098d2c65f0932139b88&skey=@crypt_2d4a1972_ea00536c8 ac4e35fae1c2a1c48dfe40d'.'ContactFlag': 3.'MemberCount': 82.'RemarkName': ' '.'HideInputBarFlag': 0.'Sex': 0.'Signature': ' '.'VerifyFlag': 0.'OwnerUin': 0.'PYInitial': 'HBRZSZ90H'.'PYQuanPin': 'hubeirenzaishenzhen90hou'.'RemarkPYInitial': ' '.'RemarkPYQuanPin': ' '.'StarFriend': 0.'AppAccountFlag': 0.'Statues': 0.'AttrStatus': 0.'Province': ' '.'City': ' '.'Alias': ' '.'SnsFlag': 0.'UniFriend': 0.'DisplayName': ' '.'ChatRoomId': 0.'KeyWord': ' '.'EncryChatRoomId': ' '.'IsOwner': 0.'IsAdmin': None.'Self': <User: {'MemberList': <ContactList: []>, 'UserName': '@29b9cb6386352503319f411754e7424e383ae09e50a224feca754a4516db6a13'.'City': ' '.'DisplayName': ' '.'PYQuanPin': ' '.'RemarkPYInitial': ' '.'Province': ' '.'KeyWord': ' '.'RemarkName': ' '.'PYInitial': ' '.'EncryChatRoomId': ' '.'Alias': ' '.'Signature': '(` o ´ v) ♡'.'NickName': 'Robot Pig'.'RemarkPYQuanPin': ' '.'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon? seq=275167114&username=@29b9cb6386352503319f411754e7424e383ae09e50a224feca754a4516db6a13&skey=@crypt_2d4a1972_ea00536c8a c4e35fae1c2a1c48dfe40d'.'UniFriend': 0.'Sex': 2.'AppAccountFlag': 0.'VerifyFlag': 0.'ChatRoomId': 0.'HideInputBarFlag': 0.'AttrStatus': 0.'SnsFlag': 1.'MemberCount': 0.'OwnerUin': 0.'ContactFlag': 0.'Uin': 3454488193.'StarFriend': 0.'Statues': 0.'WebWxPluginSwitch': 0.'HeadImgFlag': 1}>}> Too much omission... ] Received a group message: Pei Jie123Received a group message: Hello, Pei JieCopy the code
In addition, group chat can be searched by username in addition to the group name, or a combination of the two. There is an isAt field in MSG that can be used to determine whether the user is @
The use method is very similar to group chat, search public number method search_mps, listen to public number information to add isMpChat=True element, the following code example:
import itchat
@itchat.msg_register(itchat.content.TEXT, isMpChat=True)
def reply_msg(msg):
print("Received a message from an official account:", msg['User'] ['NickName'], msg['Content'])
def login_after(a):
mps = itchat.search_mps(name='CoderPig')
if len(mps) > 0:
print(mps)
itchat.send_msg('Life is short', toUserName=mps[0] ['UserName'])
if __name__ == '__main__':
itchat.auto_login(loginCallback=login_after)
itchat.run()
Copy the code
The code execution result is as follows:
[<MassivePlatform: {'MemberList': <ContactList: []>, 'Uin': 0.'UserName': '@07585e92f75be7320e49627cf0c3ad43'.'NickName': 'CoderPig'.'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon? seq=610904174&username=@07585e92f75be7320e49627cf0c3ad43&skey=@crypt_2d4a1972_bc443bf966f94fa11f2db8f812e456cf'.'ContactFlag': 3.'MemberCount': 0.'RemarkName': ' '.'HideInputBarFlag': 0.'Sex': 0.'Signature': 'A salty fish Android development, can point Python, share some learning experience, summary, chicken soup, reading notes, life skills'.'VerifyFlag': 8.'OwnerUin': 0.'PYInitial': 'CODERPIG'.'PYQuanPin': 'CoderPig'.'RemarkPYInitial': ' '.'RemarkPYQuanPin': ' '.'StarFriend': 0.'AppAccountFlag': 0.'Statues': 0.'AttrStatus': 0.'Province': 'in guangdong'.'City': 'shenzhen'.'Alias': ' '.'SnsFlag': 0.'UniFriend': 0.'DisplayName': ' '.'ChatRoomId': 0.'KeyWord': 'gh_'.'EncryChatRoomId': ' '.'IsOwner': 0}>] received a public id message: CoderPig I use PythonCopy the code
Seven, send messages regularly
The operation of sending regular messages is very practical in daily life. For example, sending new day or festival wishes to others at 12 o ‘clock at night. If you have the habit of going to bed early, it will be very uncomfortable to stay up until 12 o ‘clock. Here we use an apscheduler scheduled task module. To complete the installation, type PIP install apscheduler on the command line. Will not be detailed here, interested can go the official document to consult: apscheduler. Readthedocs. IO/en/latest/u…
import itchat
from apscheduler.schedulers.blocking import BlockingScheduler
import time
# Send a message
def send_msg(a):
user_info = itchat.search_friends(name='PeiJie')
if len(user_info) > 0:
user_name = user_info[0] ['UserName']
itchat.send_msg('Happy birthday! ', toUserName=user_name)
def after_login(a):
sched.add_job(send_msg, 'cron', year=2018, month=7, day=28, hour=16, minute=5, second=30)
sched.start()
def after_logout(a):
sched.shutdown()
if __name__ == '__main__':
sched = BlockingScheduler()
itchat.auto_login(loginCallback=after_login, exitCallback=after_login)
itchat.run()
Copy the code
This can be used to flirt with younger sister the most good, every day the timing of good morning and good night, absolutely a second will not fall
8. Make chatbot by integrating Turing API
Turing robot’s official website: www.tuling123.com/member/robo…
After registering an account, click Create robot. Due to recent rectification, it can only be called after real name authentication
Before calling you can test the magic of the robot in Postman. For testing, please refer to the official documentation:
www.kancloud.cn/turing/www-…
After registering an account, click Create Robot, the panel as shown in the picture will pop up, and you can configure it as required.
Note here the secret key used by the ApiKey to call the interface.
The specific code is as follows:
import itchat
import requests
def get_response(_info):
print(_info) # Messages from friends
api_url = 'http://www.tuling123.com/openapi/api' # Turing Robot website
data = {
'key': 'apiKey'.If the apiKey doesn't work, register it once
'info': _info, # This is the message we received from our friends and forwarded to the Turing bot
'userid': 'wechat-robot'.You can change anything you want here
}
r = requests.post(api_url, data=data).json() # Send data
print(r.get('text')) # Bots reply to messages from friends
return r
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
return "【 I am a genius ^_^】" + get_response(msg["Text"[])"text"]
if __name__ == '__main__':
itchat.auto_login(hotReload=True,enableCmdQR=2) # hotReload =True, stay online, next time run code can automatically log in, you can add enableCmdQR=True parameter, let the TWO-DIMENSIONAL code display on the command line, other parts of the system may be different character width, can be adjusted by enableCmdQR assigned to a specific multiple. For example, set the value to 2
itchat.run()
Copy the code
Monitor the received data
First, we monitor the messages, which are divided into friend chats and group chats, and we write code to monitor the incoming data.
import itchat
from itchat.content import *
# Friend information monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True)
def handle_friend_msg(msg):
print("Friend info:", msg)
# Group chat monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)
def information(msg):
print("Group message:", msg)
if __name__ == '__main__':
itchat.auto_login()
itchat.run()
Copy the code
Send a message to the robot, send a message to the group chat, look at the printed message, first friend information
Friend information: {'MsgId': '5500935424291030814'.'FromUserName': '@8fd8b5b2bd0862ed5d0d573bc6c08362'.'ToUserName': '@913c3124d973db6ae25924bd0598b48a0028e0c2d01e18d8095cc6fd58db116b'.'MsgType': 1.'Content': '123'.'Status': 3.'ImgStatus': 1.'CreateTime': 1533010285.'VoiceLength': 0.'PlayLength': 0.'FileName': ' '.'FileSize': ' '.'MediaId': ' '.'Url': ' '.'AppMsgType': 0.'StatusNotifyCode': 0.'StatusNotifyUserName': ' '.'RecommendInfo': {'UserName': ' '.'NickName': ' '.'QQNum': 0.'Province': ' '.'City': ' '.'Content': ' '.'Signature': ' '.'Alias': ' '.'Scene': 0.'VerifyFlag': 0.'AttrStatus': 0.'Sex': 0.'Ticket': ' '.'OpCode': 0}, 'ForwardFlag': 0.'AppInfo': {'AppID': ' '.'Type': 0}, 'HasProductId': 0.'Ticket': ' '.'ImgHeight': 0.'ImgWidth': 0.'SubMsgType': 0.'NewMsgId': 5500935424291030814.'OriContent': ' '.'EncryFileName': ' '.'User': <User: {'MemberList': <ContactList: []>, 'Uin': 0.'UserName': '@8fd8b5b2bd0862ed5d0d573bc6c08362'.'NickName': 'CoderPig'.'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon? seq=625711027&username=@8fd8b5b2bd0862ed5d0d573bc6c08362&skey=@crypt_2d4a1972_26dc3be99a177455b82518b3ca6e6cc5'.'ContactFlag': 3.'MemberCount': 0.'RemarkName': ' '.'HideInputBarFlag': 0.'Sex': 1.'Signature': 'Unconvinced, prove it with action, say less and do more... 2018.7.29 '.'VerifyFlag': 0.'OwnerUin': 0.'PYInitial': 'CODERPIG'.'PYQuanPin': 'CoderPig'.'RemarkPYInitial': ' '.'RemarkPYQuanPin': ' '.'StarFriend': 0.'AppAccountFlag': 0.'Statues': 0.'AttrStatus': 33783847.'Province': 'in guangdong'.'City': 'jiangmen'.'Alias': ' '.'SnsFlag': 17.'UniFriend': 0.'DisplayName': ' '.'ChatRoomId': 0.'KeyWord': 'zpj'.'EncryChatRoomId': ' '.'IsOwner': 0} >.'Type': 'Text'.'Text': '123'}
Copy the code
Analyze the data to be collected, MsgId (wechat id, used as the key), NickName (sender user name), Content (information Content), CreateTime (creation time), Type (information Type). Followed by group chat messages:
Group chat information: {'MsgId': '3177606925001563512'.'FromUserName': '@@16521484d35b2fe9c953282d98ec4f11456607924b3a7cc6d7fb671fe7e3081c'.'ToUserName': '@913c3124d973db6ae25924bd0598b48a0028e0c2d01e18d8095cc6fd58db116b'.'MsgType': 1.'Content': 'hey'.'Status': 3.'ImgStatus': 1.'CreateTime': 1533010298.'VoiceLength': 0.'PlayLength': 0.'FileName': ' '.'FileSize': ' '.'MediaId': ' '.'Url': ' '.'AppMsgType': 0.'StatusNotifyCode': 0.'StatusNotifyUserName': ' '.'RecommendInfo': {'UserName': ' '.'NickName': ' '.'QQNum': 0.'Province': ' '.'City': ' '.'Content': ' '.'Signature': ' '.'Alias': ' '.'Scene': 0.'VerifyFlag': 0.'AttrStatus': 0.'Sex': 0.'Ticket': ' '.'OpCode': 0}, 'ForwardFlag': 0.'AppInfo': {'AppID': ' '.'Type': 0}, 'HasProductId': 0.'Ticket': ' '.'ImgHeight': 0.'ImgWidth': 0.'SubMsgType': 0.'NewMsgId': 3177606925001563512.'OriContent': ' '.'EncryFileName': ' '.'ActualNickName': 'Easy to come and build and lian'.'IsAt': False.'ActualUserName': '@8fd8b5b2bd0862ed5d0d573bc6c08362'.'User':
Copy the code
Also analyze the data to be collected, MsgId (wechat message identifier), ActualNickName (sender group name), Content (message Content), CreateTime (creation time), Type (message Type). Change our program, extract and print all of this.
import itchat
from itchat.content import *
# Friend information monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True)
def handle_friend_msg(msg):
msg_id = msg['MsgId']
msg_from_user = msg['User'] ['NickName']
msg_content = msg['Content']
msg_create_time = msg['CreateTime']
msg_type = msg['Type']
print("Received message:", msg_id, msg_from_user, msg_content, msg_create_time,msg_type)
# Group chat monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)
def information(msg):
msg_id = msg['MsgId']
msg_from_user = msg['ActualNickName']
msg_content = msg['Content']
msg_create_time = msg['CreateTime']
msg_type = msg['Type']
print("Group message:",msg_id, msg_from_user, msg_content, msg_create_time,msg_type)
if __name__ == '__main__':
itchat.auto_login()
itchat.run()
Copy the code
The code execution result is as follows:
Group chat information: 2254622820807367335 Hu Xiaotao Rival Company 1533023277 Text Group chat information: 1765614482944449471 Xia_ang And Ziganwu 1533023285 Text friend information: 615083621872361432 CoderPig ha 1533023293 Text buddy info: 7292909308782687092 CoderPig hello oh 1533023302 TextCopy the code
Verify different information types and corresponding processing methods
Well, information extraction is successful, the next step is to verify a different types of information and the corresponding processing mode, Text, images (expression), audio, video, documents five, behind four needs to be downloaded to the local, itchat method provides a download file in MSG ‘Text’, call this method can complete the file download, the modified code is as follows:
import itchat
from itchat.content import *
import os
import time
File temporary storage page
rec_tmp_dir = os.path.join(os.getcwd(), 'tmp/')
# dictionary for storing data
rec_msg_dict = {}
# Friend information monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True)
def handle_friend_msg(msg):
msg_id = msg['MsgId']
msg_from_user = msg['User'] ['NickName']
msg_content = ' '
# The time the message was received
msg_time_rec = time.strftime("%Y-%m-%d %H:%M%S", time.localtime())
msg_create_time = msg['CreateTime']
msg_type = msg['Type']
if msg['Type'] = ='Text':
msg_content = msg['Content']
elif msg['Type'] = ='Picture' \
or msg['Type'] = ='Recording' \
or msg['Type'] = ='Video' \
or msg['Type'] = ='Attachment':
msg_content = r"" + msg['FileName']
msg['Text'](rec_tmp_dir + msg['FileName'])
rec_msg_dict.update({
msg_id: {
'msg_from_user': msg_from_user,
'msg_time_rec': msg_time_rec,
'msg_create_time': msg_create_time,
'msg_type': msg_type,
'msg_content': msg_content
}
})
print(msg)
# Group chat monitoring
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)
def information(msg):
msg_id = msg['MsgId']
msg_from_user = msg['ActualNickName']
msg_content = ' '
# The time the message was received
msg_time_rec = time.strftime("%Y-%m-%d %H:%M%S", time.localtime())
msg_create_time = msg['CreateTime']
msg_type = msg['Type']
if msg['Type'] = ='Text':
msg_content = msg['Content']
elif msg['Type'] = ='Picture' \
or msg['Type'] = ='Recording' \
or msg['Type'] = ='Video' \
or msg['Type'] = ='Attachment':
msg_content = r"" + msg['FileName']
msg['Text'](rec_tmp_dir + msg['FileName'])
rec_msg_dict.update({
msg_id: {
'msg_from_user': msg_from_user,
'msg_time_rec': msg_time_rec,
'msg_create_time': msg_create_time,
'msg_type': msg_type,
'msg_content': msg_content
}
})
print(msg)
if __name__ == '__main__':
if not os.path.exists(rec_tmp_dir):
os.mkdir(rec_tmp_dir)
itchat.auto_login()
itchat.run()
Copy the code
Monitoring withdrawal information and data extraction
Then to the monitoring of the withdrawn information, the type of the withdrawn information is NOTE. Let’s monitor and see the specific content of the withdrawn information.
{'MsgId': '7399110162640182490'.'FromUserName': '@9c1a8bf4e28771a6b3ab635991dea2a1'.'ToUserName': '@49d1d90b90371099297a08da1009f3cdd042f21194239ef47b60e8f0b52e4553'.'MsgType': 10002.'Content': '
zpj779878443
1625723544
3154925139554625499
'.'Status': 4.'ImgStatus': 1.'CreateTime': 1533103679.'VoiceLength': 0.'PlayLength': 0.'FileName': ' '.'FileSize': ' '.'MediaId': ' '.'Url': ' '.'AppMsgType': 0.'StatusNotifyCode': 0.'StatusNotifyUserName': ' '.'RecommendInfo': {'UserName': ' '.'NickName': ' '.'QQNum': 0.'Province': ' '.'City': ' '.'Content': ' '.'Signature': ' '.'Alias': ' '.'Scene': 0.'VerifyFlag': 0.'AttrStatus': 0.'Sex': 0.'Ticket': ' '.'OpCode': 0}, 'ForwardFlag': 0.'AppInfo': {'AppID': ' '.'Type': 0}, 'HasProductId': 0.'Ticket': ' '.'ImgHeight': 0.'ImgWidth': 0.'SubMsgType': 0.'NewMsgId': 7399110162640182490.'OriContent': ' '.'EncryFileName': ' '.'User': <User: {'MemberList': <ContactList: []>, 'Uin': 0.'UserName': '@9c1a8bf4e28771a6b3ab635991dea2a1'.'NickName': 'CoderPig'.'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon? seq=625711027&username=@9c1a8bf4e28771a6b3ab635991dea2a1&skey=@crypt_2d4a1972_e0963a9b961045c2e06293043f1c98a8'.'ContactFlag': 3.'MemberCount': 0.'RemarkName': ' '.'HideInputBarFlag': 0.'Sex': 1.'Signature': 'Unconvinced, prove it with action, say less and do more... 2018.7.29 '.'VerifyFlag': 0.'OwnerUin': 0.'PYInitial': 'CODERPIG'.'PYQuanPin': 'CoderPig'.'RemarkPYInitial': ' '.'RemarkPYQuanPin': ' '.'StarFriend': 0.'AppAccountFlag': 0.'Statues': 0.'AttrStatus': 33783847.'Province': 'in guangdong'.'City': 'jiangmen'.'Alias': ' '.'SnsFlag': 17.'UniFriend': 0.'DisplayName': ' '.'ChatRoomId': 0.'KeyWord': 'zpj'.'EncryChatRoomId': ' '.'IsOwner': 0} >.'Type': 'Note'.'Text': 'CoderPig has retracted a message'}
Copy the code
The first is to determine whether the system information is withdrawn by default, and the content is:
MsgId = 3154925139554625499; MsgId = 3154925139554625499; MsgId = 3154925139554625499 The next thing to do is take the MsgId and look up the dictionary that holds the message, concatenate the text or text plus file based on the message type, and send it to the file transfer assistant. The specific code is as follows:
@itchat.msg_register([NOTE], isFriendChat=True, isGroupChat=True)
def revoke_msg(msg):
if revoke_msg_compile.search(msg['Content']) is not None:
old_msg_id = extract_msgid_compile.search(msg['Content']).group(1)
old_msg = rec_msg_dict.get(old_msg_id, {})
Send a text message first
itchat.send_msg(str(old_msg.get('msg_from_user') + "Retracted a message:"
+ old_msg.get('msg_content')), toUserName="filehelper")
Check whether msg_content exists
if os.path.exists(os.path.join(rec_tmp_dir, old_msg.get('msg_content'))) :if old_msg.get('msg_type') = ='Picture':
itchat.send_image(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
toUserName="filehelper")
elif old_msg.get('msg_type') = ='Video':
itchat.send_video(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
toUserName="filehelper")
elif old_msg.get('msg_type') = ='Attachment' \
or old_msg.get('msg_type') = ='Recording':
itchat.send_file(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
toUserName="filehelper")
Copy the code
12. Clear the cache periodically
In addition, all our information is stored in a dictionary. As time goes by, there will be a lot of data and image files will accumulate more and more. We can add a regular task, such as cleaning up the information and corresponding files that take more than 2 minutes to create every five minutes. The relevant codes are as follows:
Perform cleanup every five minutes
def clear_cache(a):
# current time
cur_time = time.time()
If there is a record that took more than 2 minutes (120s) to create, delete it. If there is no text, delete the file
for key in list(rec_msg_dict.keys()):
if int(cur_time) - int(rec_msg_dict.get(key).get('msg_create_time')) > 120:
if not rec_msg_dict.get(key).get('msg_type') = ='Text':
file_path = os.path.join(rec_tmp_dir, rec_msg_dict.get(key).get('msg_content'))
print(file_path)
if os.path.exists(file_path):
os.remove(file_path)
rec_msg_dict.pop(key)
# Start polling task
def start_schedule(a):
sched.add_job(clear_cache, 'interval', minutes=2)
sched.start()
Stop all tasks and clear the cache folder
def after_logout(a):
sched.shutdown()
shutil.rmtree(rec_tmp_dir)
if __name__ == '__main__':
sched = BlockingScheduler()
if not os.path.exists(rec_tmp_dir):
os.mkdir(rec_tmp_dir)
itchat.auto_login(exitCallback=after_logout)
itchat.run(blockThread=False)
start_schedule()
Copy the code
Thanks to:
Blog.csdn.net/fxbin123/ar…
www.kancloud.cn/turing/www-…
www.cnblogs.com/sunshine-lo…
www.shiyanlou.com/courses/684…
Github.com/littlecoder…
Blog.csdn.net/coder_pig/a…
Deploy to the cloud server to achieve 24-hour online chat
All of the above tests are conducted locally, and computers cannot be left on 24 hours a day, wasting electricity and money. Therefore, this script is on the cloud. Namely, log in to the cloud server. 1. Baidu Cloud server I purchased is Baidu Cloud server, with a newly registered account and discounts. It takes three months and fifty years to configure 1 core 1G, which is fully sufficient. Just because I wanted to download the latest version of Python, the server was broken. I called baidu Cloud customer service, and the engineer quickly solved the problem. After reinstalling the system, I decided to use the python version of the system, which was easy to do in a few steps.
PIP is not installed on the server by default, so install PIP first
$ wget https://bootstrap.pypa.io/get-pip.py $ python get-pip.py $ pip -V   # Check PIP version
Copy the code
Install ITChat by following the steps above. At login, you can add enableCmdQR=True to display the QR code on the command line. Other systems may have different character width. This can be adjusted by assigning enableCmdQR to a specific multiple (I set it to 2).
3, save the script as.py file download resources: leave a comment “I want resources”, you can, I will send you or directly click: download resources PS: resources can be directly run in theory, if you can not run the situation welcome to consult me.
15. Achievement Display
About me
——
# This post has been synced to my GitHub repository:JavastudyLook forward to your participation.
# This article has been synchronized toCang ho’s personal blogAnd leave a comment directly on your blog. Blush: