使用systemd定时给wechat好友每天发送天气预报信息

目的

  1. 使用自己熟悉的任何一门编程语言,比如C语言,C++语言,Java语言,Kotlin语言,Python语言,golang语言,利用 systemd来实现一个自己的Linux service。

  2. 我自己选择 Python编程语言来进行实践。

  3. 学习Python下的wxpy库。它可以作为微信机器人来和微信好友聊天,或者定时发送微信信息。这里是定时每天早上8:30给微信好友发送天气预报的一个案例。


术语解释

systemd

定义
  1. systemd即为system daemon,是linux下的一种init软件。
  2. 采用Socket激活式与总线激活式服务,以提高相互依赖的各服务的并行运行性能。
  3. 用Cgroups代替PID来追踪进程,以此即使是两次fork之后生成的守护进程也不会脱离systemd的控制。
起源
  1. ystemd这一名字源于Unix中的一个惯例:在Unix中常以“d”作为系统守护进程(英语:daemon,亦称后台进程)的后缀标识。除此以外,systemd亦是借代英文术语D体系,而这一术语即是用于描述一个人具有快速地适应环境并解决困难的能力。

Bot

  1. wxpy下的一个库文件,wxpy学习文档。路径:site-packages/wxpy/api/bot.py,其中这个site-packages是pip安装库的一个目录。

注意事项

  1. 实践环境是Centos7,它默认的Python版本是2.7,升级到3.6.0这个版本。
  2. 本地windows10的python版本是3.7的。
  3. 在Python升级过程中会有很多问题。
    升级流程:
    A,wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
    B, tar -zxvf Python-3.6.0.tgz
    C, cd Python-3.6.0
    D, ./configure
    F, make
    G, make install
    H, mv /usr/bin/python /usr/bin/python.bak
    I, ln -s /usr/local/bin/python3 /usr/bin/python
    J, ldconfig


    问题:
    A,此时yum命令已经无法使用了,需要将其配置的python依然指向2.x版本。
    vim /usr/bin/yum
    修改:!/usr/bin/python --> !/usr/bin/python2.7
    vim /usr/libexec/usrlgrabber-ext-down
    修改:!/usr/bin/python --> !/usr/bin/python2.7


    B,有可能没有pip这个指令。
    安装pip过程:
    wget https://bootstrap.pypa.io/get-pip.py
    python get-pip.py
    pip -V
    注意这个V是大写的。


    C, 有可能pip install module的时候,需要ssl。
    安装:
    yum install openssl-devel-y
    需要重新编译python
    进入到Python3.6.0的下载目录下:
    ./configure
    make
    make install

centos7 + Python3.6代码

#!/usr/bin/python
#coding:utf-8
from urllib.request import urlopen
from bs4 import BeautifulSoup
from wxpy import *
import schedule
import time

bot = Bot(console_qr=True)

def send_blog_msg(content):
    # 搜索自己的好友,注意中文字符前需要添加 u
    my_friend = bot.friends().search(u'容儿姐')[0]
    my_friend.send(content)


def job():
    resp = urlopen('http://www.weather.com.cn/weather/101010100.shtml')
    soup = BeautifulSoup(resp, 'html.parser')
    # 第一个包含class="tem"的p标签即为存放今天天气数据的标签
    tag_today = soup.find('p', class_="tem")
    try:
        # 有时候这个最高温度是不显示的,此时利用第二天最高温度代替
        temperature_high = tag_today.span.string

    except AttributeError as e:
        temperature_high = tag_today.find_next('p', class_="tem").span.string

    # 获取最低温度
    temperature_low = tag_today.i.string
    # 获取天气
    weather = soup.find('p', class_="wea").string
    contents = time.strftime('%Y.%m.%d', time.localtime(time.time())) + '\n' + '北京' + '\n' + '最高温度:' + temperature_high + '\n' + '最低温度:' + temperature_low + '\n' + '天气' + weather
    send_blog_msg(contents)


# 定时任务
schedule.every().day.at("16:32").do(job)
while True:
    # 确保schedule一直运行
    schedule.run_pending()
    time.sleep(1)
# 保证上述代码持续运行
bot.join()

说明

  1. #!/usr/bin/python
  2. #coding:utf-8 解决编码问题
  3. bot = Bot(console_qr=True),如果是windows的话则是bot = Bot(cache_path=True)。说明参数说明
  4. 启动的时候,可以直接执行 python xx.py
  5. 或者后台执行, nohup python xx.py & ,其中二维码的生成在nohup.out中,手机微信扫描即可登陆。
  6. 即可实现定时给指定好友发送微信消息

win10 + Python3.7代码

from urllib.request import urlopen
from bs4 import BeautifulSoup
from wxpy import *
import schedule
import time

bot = Bot(cache_path=True)


def send_blog_msg(content):
    # 搜索自己的好友,注意中文字符前需要添加 u
    my_friend = bot.friends().search(u'容儿姐')[0]
    my_friend.send(content)


def job():
    resp = urlopen('http://www.weather.com.cn/weather/101010100.shtml')
    soup = BeautifulSoup(resp, 'html.parser')
    # 第一个包含class="tem"的p标签即为存放今天天气数据的标签
    tag_today = soup.find('p', class_="tem")
    try:
        # 有时候这个最高温度是不显示的,此时利用第二天最高温度代替
        temperature_high = tag_today.span.string

    except AttributeError as e:
        temperature_high = tag_today.find_next('p', class_="tem").span.string

    # 获取最低温度
    temperature_low = tag_today.i.string
    # 获取天气
    weather = soup.find('p', class_="wea").string
    contents = time.strftime('%Y.%m.%d', time.localtime(time.time())) + '\n' + '北京' + '\n' + '最高温度:' + temperature_high + '\n' + '最低温度:' + temperature_low + '\n' + '天气' + weather
    send_blog_msg(contents)


# 定时任务
schedule.every().day.at("16:32").do(job)
while True:
    # 确保schedule一直运行
    schedule.run_pending()
    time.sleep(1)
# 保证上述代码持续运行
bot.join()

说明

  1. 编写过程中需要的库,都需要安装好,需要什么安装什么即可。指令:pip install modules
  2. 101010100 是北京城市的唯一标识,每个城市都有。
  3. bot = Bot(cache_path=True)这句可以生成一个二维码,需要手机微信端扫描二维码进行登陆。

把这段代码变成Linux service

流程

  1. 创建文件
    vim /etc/systemd/system/wechat-forecast.service

  2. 文件内容如下:
    [Unit]
    Description=wechat-forecast-service
    After=network.target
    StartLimitIntervalSec=0
    [Service]
    Type=simple
    Restart=always
    RestartSec=1
    User=root
    ExecStart=/usr/bin/python /home/service/wechat-forecat.py
    [Install]
    WantedBy=multi-user.target

  3. User需要自己设置,ExecStart需要自己设置。

  4. 关键点就是一定要记录日志,这里是**/usr/bin/python /home/service/wechat-forecat.py >> /home/service/logs/wechat-forecast.log**,采用Python的打印函数print来做的日志输出。在linux下crontab是可以这样实现的,但是service需要两个绝对路径。

  5. 启动方式:
    systemctl start wechat-forecast

  6. 添加开机自启动
    systemctl enable wechat-forecast

  7. 查看生成的二维码
    systemctl status wechat-forecast.service

  8. 查看进程
    ps -ef | grep py

小结

  1. Centos7自带Python是2.7版本的,Centos6自带Python是2.6版本的。需要升级python版本。
  2. 实现Linux下Python代码逻辑。实现windows下的Python代码逻辑。
  3. 执行过程中一定要打印日志。这里是Python的print函数输出到日志文件中。但是这里没有实现。
  4. 理解任何一门编程语言都可以实现成为Linux的service过程。
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值