这是一年前写的程序了,今天被我拿出来炒冷饭水文章了๑乛◡乛๑
Setp1.导入模块并创建机器人对象
首先用pip安装wxpy模块,安装完成后编写登录代码
from wxpy import *
#登录网页微信并保持在线
bot = Bot(console_qr = 2,cache_path="cache.wx")from wxpy import *
#登录网页微信并保持在线
bot = Bot(console_qr = 2,cache_path="cache.wx")
- console_qr控制登录时二维码的格式,如果出现二维码错位,请将后边的值在1-2更改,canche_path是存放登录的缓存文件
- 新创建没多久的微信号,腾讯是不允许登录web微信的,可以先去手动登录下web微信,看看自己的号可不可以
这里就是创建了一个名为bot的机器人对象。
运行,扫码登录。

登录成功会显示:Login successfully as 你的微信名
Setp2.编写发送消息函数
def sendMgs(user,content):
my_friend = bot.friends().search(user)[0]
my_friend.send(content)
- user就是发送的对象的名字,可以是备注。
- content是发送的内容
比如:

测试一下,可以看到发送成功。

Setp3.获取天气数据
天气数据可以去中国天气网手动爬取,为了方便,我直接用别人提供的天气接口。
PS:中国天气网晚上六点后天气数据会变化,需要注意。
访问 http://t.weather.sojson.com/api/weather/city/城市ID ,便能返回该城市天气的json数据
比如杭州:http://t.weather.sojson.com/api/weather/city/101210101

这里我写的是获取第二天的最高、低温、天气、风向和提示。
import json
import requests
hangzhou = "http://t.weather.sojson.com/api/weather/city/101210101"#杭州
def get_html(url):
headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'ContentType':
'text/html; charset=utf-8',
'Accept-Encoding':
'gzip, deflate, sdch',
'Accept-Language':
'zh-CN,zh;q=0.8',
'Connection':
'keep-alive',
}
try:
response = requests.get(url, headers = headers, timeout = 100)
response.raise_for_status()
response.encoding = 'utf-8'
return response.text
except:
return " 请求失败 "
def get_weather(response):
if(response == " 请求失败 "):
print("请求失败")
else:
# 明日信息
data = json.loads(response)
city = data['cityInfo']['city']
today = data['data']['forecast'][0]['ymd']
tomorrow_hightem = data['data']['forecast'][1]['high']
tomorrow_lowtem = data['data']['forecast'][1]['low']
tomorrow_win = data['data']['forecast'][1]['fx']+' '+data['data']['forecast'][0]['fl']
tomorrow_wea = data['data']['forecast'][1]['type']
notice = data['data']['forecast'][1]['notice']
forecast_data = '[ '+ today +' ]' + '\n' + city +"明日天气:"+ '\n' + tomorrow_hightem + '/' + tomorrow_lowtem + '\n' + '天气:' + tomorrow_wea + '\n' + '风力:' + tomorrow_win + '\n'
info = [forecast_data, notice]
return info
print(get_weather(get_html(hangzhou)))
- info[0]存放最高温、最低温、天气、风力,info[1]存放提示

接着调用sendMgs(user,content)函数发送出去便可以了。

可以看到,效果很不错,成功调动女神情绪。
我还准备了每日一句和计算天数这两个函数,其他的大家可以根据需求自己编写。
# 获取金山词霸每日一句,英文和翻译
def get_news():
url = "http://open.iciba.com/dsapi/"
r = requests.get(url)
onewords = r.json()['content']
note = r.json()['note']
return onewords, note
# 计算天数
def get_days():
#time1是开始的时间
time1 = "2018-08-10"
time2 = datetime.datetime.now().strftime('%Y-%m-%d')
day1 = time.strptime(str(time1), '%Y-%m-%d')
day2 = time.strptime(str(time2), '%Y-%m-%d')
days = (int(time.mktime(day2)) - int(time.mktime(day1))) / (24 * 60 * 60)
return abs(int(days))
想要每天定时发送只要再编写一个计划任务然后用nohup命令挂在服务器上便可。
def run():
获取发送数据
sendMgs("发送对象",发送数据)
# 自行更改发送时间
schedule.every().day.at("发送时间").do(run)
while True:
schedule.run_pending()
time.sleep(1)
bot.join()
完整的程序可见:https://github.com/YuLiu-lab/WechatWeather
这个模块还有更多好玩、强大的功能,比如发送图片,根据收到的消息回复内容。可以看他们提供的文档:https://wxpy.readthedocs.io/zh/latest/
注:强烈建议仅使用小号运行机器人!
最后一次更新于2021-04-19
大佬!带我
By Q at March 5th, 2020 at 07:46 pm.