This article is participating in Python Theme Month. See the link to the event for more details
⭐ Tool Recommendation
- Want source code remember to pay attention to me oh!
- First, let me tell you a fun wechat robot project: WechatPCAPI github project address
- What exactly does it do, according to md, is described as follows:
Function list Currently supported: Wechat open to get friends, groups, public account list to receive messages (including friends, groups, public account messages) to send messages (support text, pictures, sharing links, files, business cards and other formats) to be completed: Public account focus group control function (build a group, pull people into the group, withdraw from the group, kick people, @ someone, publish group announcement and other functions) add friends, delete friends, anti-message withdrawal, etcCopy the code
Request from ⭐
I do not know whether users really have a need, really need the wechat robot to do something? What, for a girlfriend? Using a wechat robot to do such a thing? . Tell jokes? Make your girlfriend laugh? And you can put a robot on a robot and turn it into an intelligent chatbot!Copy the code
⭐ Background
Search wechat automatic reply < robot > on the Internet, and get mostly robot, itchart and other libraries; But because of the control of wechat Web, can not through the Web scan code login wechat Web end; This leads to the creation of the client.Copy the code
⭐ Environment Preparation
- Python3 environment, support 3.6
- Download the lower version of wechat on THE PC
Download slow with baidu network location sharing: link: https://pan.baidu.com/s/1yADEwqht8hcTTjxpkW8DXw extracted code: rneoCopy the code
⭐ Start coding
- To make robots smarter, develop a gadget: Ask about the weather
# First read the file, read out the address information
with open("pcc.json"."r", encoding="utf-8") as pf:
dic = json.load(pf)
"" "" 110000 ", "Beijing", "110101" : "the dongcheng district", "110102" : "xicheng district", "110105", "fengtai district, chaoyang district", "110106" : ""," 110107 ":" the shijingshan district ", "110108", "" haidian district, "110109", "mentougou district", "110111" : "fangshan district", "110112", "qu", "110113", "space", "110114" : "changping district", "110115" : "daxing district", "110116" : "huairou district", "110117":" Pinggu District ","
# https://api.ip138.com/status/?token=e1ec8efa42dac111351ce06ecc06adb16f query remaining weather query times
def get_werther(city) :
for key, value in dic.items():
if city in value:
params = urlencode({'code':"{}".format(key), 'type':'1'})
url = 'https://api.ip138.com/weather/?' + params
headers = {"token":"e1ec8efa42dac111351ce06ecc06adb16f"} # token is an example
content = requests.get(url=url, headers=headers).json()
text = "Location:" + content.get("province") + ", time:" + content.get("data").get("time") + \
"Daytime weather:" + content.get("data").get("dayWeather") + \
", temperature:" + content.get("data").get("dayTemp") + \
", daytime wind:" + content.get("data").get("dayWind") + \
", night weather:" + content.get("data").get("nightWeather") + \
", night temperature:" + content.get("data").get("nightTemp") + \
", night wind:" + content.get("data").get("wind") + \
", night wind:" + content.get("data").get("nightWind") + \
", real-time weather:" + content.get("data").get("weather") + \
", real-time temperature: + content.get("data").get("temp") + \
", real-time wind:" + content.get("data").get("wind") + \
", real-time humidity: + content.get("data").get("humidity") + \
", PM2.5:" + content.get("data").get("pm25")
return text
Copy the code
⭐ core code
If you want the source code, remember to pay attention to me oh ~
logging.basicConfig(level=logging.INFO)
queue_recved_message = Queue()
# message-to-column
def on_message(message) :
queue_recved_message.put(message)
# Message processing example for reference only
def thread_handle_message(wx_inst) :
i = 0
while True:
message = queue_recved_message.get()
Print all friends list information
# print(message)
if 'msg' in message.get('type') :If the response is a message and not something else
# Get who received messages
msg_content = message.get('data').get('msg')
# rep_message=getmessage(msg_content)
rep_message = get_werther(msg_content)
from_who = message.get('data').get('from_wxid')
# Get the message received from the group
from_chatroom_wxid = message.get('data').get('from_chatroom_wxid')
from_member_wxid = message.get('data').get('from_member_wxid')
# from_chatroom_nickname = message.get('data', {}).get('from_chatroom_nickname', '')
# Only respond to incoming messages
send_or_recv = message.get('data').get('send_or_recv')
if from_who and send_or_recv[0] = ='0': # 0 is the message received and # 1 is the message sent. For # 1, do not reply or it will be an infinite loop
print("The {} sentence :{}".format(i, msg_content))
wx_inst.send_text(from_who, rep_message)
i += 1
# Received @me message from group chat, I @ reply to her
if from_chatroom_wxid and send_or_recv[0] = ='0' and "@ A is me" in msg_content:
wx_inst.send_text(to_user=from_chatroom_wxid, msg=rep_message, at_someone=from_member_wxid)
# Execute program entry
def main() :
wx_inst = WechatPCAPI(on_message=on_message, log=logging)
wx_inst.start_wechat(block=True)
while not wx_inst.get_myself():
time.sleep(5)
# print(wx_inst.get_myself())
threading.Thread(target=thread_handle_message, args=(wx_inst,)).start()
time.sleep(10)
Copy the code
- Originally, I received a smart chat from Tencent, but it may not be used for a period of time, so it will be invalid:
# Tencent smart Chat interface
# Link to API interface
url_preffix = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat'
# Because the interface parameters are required, initially = I encapsulated in the module, but for everyone's convenience, integrated together
def setParams(array, key, value) :
array[key] = value
# generated interface sign signature information method, interface parameters need to refer to: https://ai.qq.com/doc/auth.shtml
def genSignString(parser) :
uri_str = ' '
for key in sorted(parser.keys()):
if key == 'app_key':
continue
uri_str += "%s=%s&" % (key, parse.quote(str(parser[key]), safe=' '))
sign_str = uri_str + 'app_key=' + parser['app_key']
hash_md5 = hashlib.md5(sign_str.encode('utf-8'))
return hash_md5.hexdigest().upper()
# need to https://ai.qq.com/product/nlpchat.shtml intelligent chatting, obtain app_id and app_key, and access
def getmessage(messageall) :
try:
# Encapsulates the smart chatbot
Message = AiPlat('216027104725'.'reXx7zTmLy2ZxBOv0C')
response = Message.Messagela(messageall)
return response.get('data').get('answer')
except Exception as e :
pass
Copy the code
- Is it cool to ask the weather effect below?
- If you want more intelligent robots, add them all.
⭐ Summary
There is no road in the world, many people walk, there is a road, so the road is blocked, another way, to open up a road, wechat ah, you can not stop IT forward steps!Copy the code
- Intelligent chat, interested to take to play!