分享

给女朋友做个聊天机器人,这样就能安心写代码了

 静知行 2020-03-09

这是第 404 次女友因为我没有及时回微信而和我生气了

惹祸的是我,受伤的确是钱包……

但是,我并不后悔

那一局王者荣耀,因为没有回微信,我完成了五杀 carry 全场

那一局刺激战场,因为没有回微信,我绝地反杀成功吃鸡

那一场球赛,因为没有回微信,我看到了极限投篮压哨三分

最重要的是,因为没有回微信,我终于可以安心写代码

两耳不闻窗外事,一心只想写代码,这才是一名程序员的内心独白

作为程序员中的佼佼者,深知有个女友不容易,于是,为了更及时的陪女友聊天回复微信,活学活用的程序员用 Python + itchat 写一个爬虫脚本每天定时给女友发给微信高阶土味情话。
在这里插入图片描述
再也不怕没能及时回复女友的微信了,女友甚至喜欢上了那个陪她聊天的机器人
在这里插入图片描述

核心代码

1. 定时任务

每天 9:30 给女朋友们开始给女朋友发送内容。

# 定时任务
scheduler = BlockingScheduler()
# 每天9:30给女朋友发送每日一句
# scheduler.add_job(start_today_info, 'cron', hour=9, minute=30)
scheduler.start()

start_today_info 是方法处理类。

2. 获取每日一句

数据来源 1: ONE●一个

def get_dictum_info(self):
 '''
 获取格言信息(从『一个。one』获取信息 http:///)
 :return: str 一句格言或者短语
 '''
 print('获取格言信息..')
 user_url = 'http:///'
 resp = requests.get(user_url, headers=self.headers)
 soup_texts = BeautifulSoup(resp.text, 'lxml')
 # 『one -个』 中的每日一句
 every_msg = soup_texts.find_all('div', class_='fp-one-cita')[0].find('a').text
 return every_msg

数据来源 2: 金山词霸 ● 每日一句

有英文和中文翻译,例如:

When you finally get your own happiness, you will understand the previous sadness is a kind of treasure, which makes you better to hold and cherish the people you love.

等你获得真正属于你的幸福之后,你就会明白一起的伤痛其实是一种财富,它让你学会更好地去把握和珍惜你爱的人。

代码实现 :

def get_ciba_info(self):
 '''
 从词霸中获取每日一句,带英文。
 :return:
 '''
 resp = requests.get('http://open.iciba.com/dsapi')
 if resp.status_code == 200 and self.isJson(resp):
 conentJson = resp.json()
 content = conentJson.get('content')
 note = conentJson.get('note')
 # print(f"{content}
{note}")
 return f"{content}
{note}
"
 else:
 print("没有获取到数据")
 return None

数据来源 3: 土味情话(感谢 tomatoF、QSCTech-Sange)

def get_lovelive_info(self):
 '''
 从土味情话中获取每日一句。
 '''
 resp = requests.get("https://api.ols/api/SweetNothings")
 if resp.status_code == 200:
 return resp.text + "
"
 else:
 print('每日一句获取失败')
 return None

3. 获取今日天气

天气数据来源:SOJSON

def get_weather_info(self, city_code=''):
 weather_url = f'http://t.weather./api/weather/city/{city_code}'
 resp = requests.get(url=weather_url)
 if resp.status_code == 200 and resp.json().get('status') == 200:
 weatherJson = resp.json()
 # 今日天气
 today_weather = weatherJson.get('data').get('forecast')[1]

city_code 城市对应 id。 http://cdn./_city.json

4. 登录微信并发送内容

itchat.auto_login()
itchat.send(today_msg, toUserName=name_uuid)

就是这么简单,女友再也不会打扰我写代码、玩游戏了!

不会 Python 怎么办?

还有个 Node+ wechaty 的,小编能帮你的只能到这里了

Python + itchat GitHub 地址:https://github.com/sfyc23/EverydayWechat

Node+ wechaty GitHub 地址:https://github.com/gengchen528/wechatBot

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多