当前位置 : 主页 > 编程语言 > 其它开发 >

不要给我发土味情话啦!🐷

来源:互联网 收集:自由互联 发布时间:2022-05-18
不要给我发土味情话啦! 不要天天给我说土味情话啦! 目录 不要天天给我说土味情话啦! API调用 土味情话返回示例 Python代码 发送邮件 过年时要跟女朋友分开一周,因为疫情,2021春
不要给我发土味情话啦!🐷 不要给我发土味情话啦! 不要天天给我说土味情话啦!

目录
  • 不要天天给我说土味情话啦!
    • API调用
      • 土味情话返回示例
      • Python代码
    • 发送邮件

过年时要跟女朋友分开一周,因为疫情,2021春节没有回家,这次还是第一次分开这么久,要怎么表达我的思念呢?image-20220221212911127过年回家女朋友还把电脑拿回去工作,那就怪不得我了。image-20220221213529991我要天天发情话邮件骚扰你~

API调用

首先,找到API调用的接口,这里用的是土味情话API接口 - 天行数据TianAPI

image-20220221213809063

土味情话返回示例
{
  "code": 200,
  "msg": "success",
  "newslist": [
    {
      "content": "你有打火机吗?没有啊,那你是怎么点燃我的心的?"
    }
  ]
}
Python代码

开始用requests写接口请求,这里创建TIANXING_API作为父类,调用接口的使用直接继承这个父类就可以了,里面定义了一个get_content方法,如果只是单纯的返回如“土味情话”这段话,那就可以直接继承父类的get_content方法,如果有接口返回更多的信息,重写这个方法就行。

如全网热搜榜API:

{
  "code": 200,
  "msg": "success",
  "newslist": [
    {
      "title": "浙江新增本土确诊44例",
      "hotnum": 3491764,
      "digest": "12月13日0-24时,浙江新增确诊病例45例,其中杭州市2例、宁波市4例、绍兴市38例、境外输入1例(刚果金输入)。"
    }
  ]
}

另外,由于请求参数中有的只需传如api_key即可,有的接口还需要指定参数,因此,__init__接口时以字典的形式传入相关参数即可。如天气API:

{
  "code": 200,
  "msg": "success",
  "newslist": [
    {
      "area": "上海市",
      "date": "2020-03-23",
      "week": "星期二",
      "weather": "晴转多云",
      "weatherimg": "yun.png",
      "real": "18℃",
		.....
    }
  ]
}

api_base.py代码如下:

注意:由于是部署在Linux上,所以在开头指定了调用的python解释器的路径

#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests


class TIANXING_API(object):

    def __init__(self):
        self.api_url = 'https://api.tianapi.com'
        self.api_key = {'key': '71243da018e621f49178d6eab11d1ce9'}
        self.data = {}
        self.data.update(self.api_key)
        self.url = ''

    def get_content(self):
        r = requests.get(self.url, params=self.data)
        rj = r.json()
        return rj['newslist'][0]['content']


class Zaoan(TIANXING_API):

    def __init__(self, data=None):
        TIANXING_API.__init__(self)
        self.path = '/zaoan/index'
        self.url = self.api_url + self.path
        if data:
            self.data.update(data)
    # def get_content(self):
    	# pass


class Saylove(TIANXING_API):

    def __init__(self, data=None):
        TIANXING_API.__init__(self)
        self.path = '/saylove/index'
        self.url = self.api_url + self.path
        if data:
            self.data.update(data)
            
   # def get_content(self):
    	# pass


发送邮件

新建mail_base.py,使用smtplib和email这两个库,定义了一个MailSender类作为管理员对象,这里写的很差,应该重新定义一个Message类,当时只是因为一时心血来潮,写的时候比较仓促,后面也没啥继续扩展的想法了,就没有重新修改。


import smtplib
from email.header import Header
from email.mime.text import MIMEText


# 设置服务器所需信息
# 163邮箱服务器地址

class MailSender(object):

    def __init__(self,receivers={}):
        self.mail_host = 'smtp.qq.com'
        self.mail_user = '57431xxxx@qq.com'
        self.mail_pass = 'xxxxxxx'
        self.sender = '57431xxxx@qq.com'
        self.receivers_dict = {}
        self.receivers_dict.update(receivers)
        self.receivers = [i for i in self.receivers_dict.values()]
        self.sign = {'xin': '\n\n爱你的飞飞', 'others': '\n\nYIFEI ZHANG'}
        self.mail_header = {'xin': 'Baby:\n\n\t', 'others': 'Hi:\n\n\t'}

    def init_smtp(self):

        self._smtpObj = smtplib.SMTP()
        try:
            # 连接服务器
            self.smtpObj.connect(self.mail_host, 25)

        except smtplib.SMTPException as e:
            print ('error', e)

    @property
    def smtpObj(self):
        if not hasattr(self, '_smtpObj'):
            self.init_smtp()
            return self._smtpObj
        else:
            return self._smtpObj

    def _set_subject(self, subject=None):
        if not subject:
            self.message['Subject'] = 'Title'
        else:
            self.message['Subject'] = Header(subject, 'utf-8')

    def _set_from(self, mfrom=None):
        if not mfrom:
            self.message['From'] = self.sender
        else:
            self.message['From'] = mfrom

    def _set_to(self, mto=None, rev=0):
        if not mto:
            self.message['To'] = ''
            for i in self.receivers:
                self.message['To'] += i + ','
            self.message['To'].rstrip(',')
        else:
            self.message['To'] = mto

    def _set_message(self, text='', subject=None, mfrom=None, mto=None):
        try:
            self.message = MIMEText(text, 'plain', 'utf-8')
            self._set_subject(subject=subject)
            self._set_to(mto=mto)
            self._set_from(mfrom=mfrom)

        except Exception:
            print (Exception)

    def send(self, text='', subject=None, mfrom=None, mto=None):

        try:
            self._set_message(text=text, subject=subject, mfrom=mfrom, mto=mto)
            self.smtpObj.login(self.mail_user, self.mail_pass)
            self.smtpObj.sendmail(
                self.sender, self.receivers, self.message.as_string())
            self.smtpObj.quit()
            print('successful.')
        except smtplib.SMTPException as e:
            print ('error', e)

然后,在main.py中对基类进行实例化和调用方法即可。定义了一个收件人列表,早上八点给女朋友和我自己发早安心语,晚上九点给女朋友发土味情话

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time

import apibase
from mailbase import MailSender

MAIL_RECEIVERS = {
    'yifei': 'ee_zyf@163.com',
    'myself_qq': '57431xxxx@qq.com',
    'jiaxin': 'jiaxixxxx@163.com'
}

now_localtime = time.strftime("%H:%M:%S", time.localtime())
if "08:00:00" < now_localtime < "09:00:00":
    ms = MailSender(MAIL_RECEIVERS)
    ms.send(text=ms.mail_header['xin'] + apibase.Zaoan().get_content() + ms.sign['xin'], subject='早安心语')
elif "21:00:00" < now_localtime < "23:00:00":
    del MAIL_RECEIVERS['yifei']
    ms = MailSender(MAIL_RECEIVERS)
    ms.send(text=ms.mail_header['xin']+ apibase.Saylove().get_content() +ms.sign['xin'], subject='悄悄话')

然后在我买的Linux服务器中使用crontab定时执行该脚本。

Linux中也需要对邮件相应的服务进行部署,在这里就不展开了,度娘谷歌啥都有。

zyf@VM-8-17-ubuntu:~/MailRegular$ crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
1 8,21 * * * python /home/zyf/MailRegular/main.py

看了一下发件箱,已经发了这么多封土味情话了image-20220221222812030

image-20220221222526027

今天发的:

image-20220221223110386

确实够土味

上一篇:分布式系统中的一些问题
下一篇:没有了
网友评论