This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.
1 background
See a lot of friend with WeChat bot to play, can automatically reply, looking at still pretty decent, itching, also thinking about doing a bot to play, the preliminary idea is to regularly to his girlfriend every day “good morning” message, push the weather that day, and introduced the Turing robot girlfriend can auto reply messages, as far as possible have a point.
2 Scheme Implementation
2.1 tools
- Two wechat signals for testing
- Call the Wxpy Pthon library
- Python3.5 or later
- Register a Turing robot
2.2 Principle
The principle is very simple, wXpy is based on itChat, some interface optimization, and improve the ease of module calls, while some functions are also expanded. Itchat is known as an open source wechat user interface. Here are some things that Wxpy can do:
- Control routers, smart homes and other gadgets with open interfaces
- Automatically send logs to your wechat when running the script
- Add a group owner as a friend, automatically pulled into the group
- Forwarding messages across numbers or groups
- Automatically chat with others
- kicks
- .
Attach wXpy’s Github: github.com/youfou/wxpy
The principle is also very simple. Wxpy uses the wechat API to realize contact search and message sending in wechat, and wXPY supports the Turing robot interface, so it can send the automatic reply of the robot. Note here, if your wechat does not support the web version of the login, the whole is also unable to run.
2.3 Implementation Procedure
Install wxpy
sudo pip3 install -U wxpy
Copy the code
Turing Robot registration
Check out this link for a one-month demo: www.turingapi.com/
code
# -*- coding: UTF-8 -*- #
from wxpy import * Call the wxpy package
bot = Bot() # Initialize the robot, scan the web code to log in
friend = bot.friends().search('we_test') [0] # Search for friends with the nickname Test
friend1 = bot.friends().search('Big Smart') [0] # Search for friends with the nickname Big Smart
group = bot.groups().search('test') [0] # search for groups as test
tuling = Tuling(api_key='58e4c4c.......... ') # Call the Turing robot API
# Send active messages
friend.send('hello world') # Send 'Hello world' to test friends
group.send('for test') Send a message to the test group
# Auto reply
@bot.register(friend)
def reply_my_friend(msg) :
tuling.do_reply(msg) # Turing robot auto reply
@bot.register(friend1)
def reply_my_friend1(msg) :
tuling.do_reply(msg) # Turing robot auto reply
@bot.register(group)
def reply_my_group(msg) :
if isinstance(msg.chat, Group) and not msg.is_at: Msg. chat and msg.is_at refer to the documentation type description. Group of news,
# If @ my reply
return
else:
tuling.do_reply(msg)
bot.join() # stay logged in
Copy the code
Inside the code contains various scenarios, you can intercept according to their own requirements, directly ptyhon3 Demo. py run, and then scan code can be.
2.4 Improved Version
There’s no point in just playing auto-reply, but the improved version adds “Good morning” and “good night” messages at the same time every morning and evening, with hourly reminders to drink water and move around, as well as weather updates. The idea is to add a timed thread, keep running, and then call wXpy’s interface to send notification messages when the time is fixed. To push the weather information, I used Goole’s weather API interface, which was also pulled to parse out the required information and send messages. Let me post the code:
# Regularly push good morning and good night
def run_thread() :
list = [11.12.13.14.15.16.17] # These are The Times to send water notifications
while True:
now = datetime.now()
if now.hour == 6 and now.minute == 00 and now.second == 00:
friend.send('Good morning.')
Get the weather for the day
temp,sky = get_weather() # encapsulates a function, call
friend.send('Weather today :'+ temp + ' ' + sky)
elif(now.hour in list) and now.minute == 00 and now.second == 00:
friend.send('Drink some water and walk around.')
elif now.hour == 18 and now.minute == 30 and now.second == 00:
friend.send('It's been a hard day at work')elif now.hour == 23 and now.minute == 00 and now.second == 00:
friend.send('It's too late. Let's go to bed.')
time.sleep(1)
Copy the code
Interface to get weather
Call the Google Weather API to get weather information
def get_weather() :
city = "hubei" # modifiable city
url = "https://www.google.com/search?q="+"weather"+city
html = requests.get(url).content
soup = BeautifulSoup(html, 'html.parser')
# get the temperature
temp = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
# this contains time and sky description
str = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text
# format the data
data = str.split('\n')
time = data[0]
sky = data[1]
# list having all div tags having particular clas sname
listdiv = soup.findAll('div', attrs={'class': 'BNeawe s3v9rd AP7Wnd'})
# particular list with required data
strd = listdiv[5].text
# formatting the string
pos = strd.find('Wind')
other_data = strd[pos:]
# printing all the data
print("Temperature is", temp)
#print("Time: ", time)
#print("Sky Description: ", sky)
#print(other_data)
return temp,sky
Copy the code
Simply, the whole thing is done.
2.5 Project Source Code
Some libraries that need to be installed during operation can be directly installed in PIP3.
# -*- coding: UTF-8 -*-
from wxpy import *
from datetime import datetime
import threading
import time
import requests
from bs4 import BeautifulSoup
def get_weather() :
city = "hubei"
url = "https://www.google.com/search?q="+"weather"+city
html = requests.get(url).content
soup = BeautifulSoup(html, 'html.parser')
# get the temperature
temp = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
# this contains time and sky description
str = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text
# format the data
data = str.split('\n')
time = data[0]
sky = data[1]
# list having all div tags having particular clas sname
listdiv = soup.findAll('div', attrs={'class': 'BNeawe s3v9rd AP7Wnd'})
# particular list with required data
strd = listdiv[5].text
# formatting the string
pos = strd.find('Wind')
other_data = strd[pos:]
# printing all the data
print("Temperature is", temp)
#print("Time: ", time)
#print("Sky Description: ", sky)
#print(other_data)
return temp,sky
# Regularly push good morning and good night
def run_thread() :
list = [11.12.13.14.15.16.17] # These are The Times to send water notifications
while True:
now = datetime.now()
if now.hour == 6 and now.minute == 00 and now.second == 00:
friend.send('Good morning.')
Get the weather for the day
temp,sky = get_weather() # encapsulates a function, call
friend.send('Weather today :'+ temp + ' ' + sky)
elif(now.hour in list) and now.minute == 00 and now.second == 00:
friend.send('Drink some water and walk around.')
elif now.hour == 18 and now.minute == 30 and now.second == 00:
friend.send('It's been a hard day at work')elif now.hour == 23 and now.minute == 00 and now.second == 00:
friend.send('It's too late. Let's go to bed.')
time.sleep(1)
if __name__=="__main__":
Start a thread to run the scheduled task
bot = Bot()
friend = bot.friends().search('we_test') [0]
friend1 = bot.friends().search('Big Smart') [0]
group = bot.groups().search('test') [0]
tuling = Tuling(api_key='58e4c4c.................. ')
@bot.register(friend)
def reply_my_friend(msg) :
tuling.do_reply(msg) # Turing robot auto reply
@bot.register(friend1)
def reply_my_friend1(msg) :
tuling.do_reply(msg) # Turing robot auto reply
@bot.register(group)
def reply_my_group(msg) :
if isinstance(msg.chat, Group) and not msg.is_at:
return
else:
tuling.do_reply(msg)
t = threading.Thread(target=run_thread, name='push_msg')
t.start()
bot.join() # stay logged in
Copy the code