带你玩转群聊机器人从0到1

1,385 阅读3分钟

一. 背景

在工作中,我们可能需要轮流值班,轮流发日报周报之类的。很多时候由于工作的繁忙,对于这些琐碎的事情我们一般不会特别的去记住,这个时候就可能导致一个问题:团队成员经常忘记这周轮到谁值班了?
类似这种问题,最简单的解决方案就是交给机器人帮我们来记忆。不仅可以减轻大家的记忆负担,同时机器人不会出现记忆混淆的情况。

二. 脚本(python)

1.实现向群聊中发送“早安问候”

需要安装的一些库:time,requests,schedule,arrow

pip install xxx

直接上代码:

# -*- coding:utf-8 -*-
import time, requests, json
import schedule
import arrow


# 获取词霸每日一句的信息
def get_news():
    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    contents = r.json()['content']
    note = r.json()['note']
    # translation = r.json()['translation']
    return contents, note


# 定义你要周期运行的函数
# 发送文本消息
def send_news():
    text1 = get_news()[0]
    text2 = get_news()[1]
    # 按照自己喜欢随意拼接一下信息
    send_text = '每日一句:\n' + text1 + '\n' + text2  
    # 群聊提供的独特的webhook,以及需要配置的headers和data
    url = "xxxxxxxxxxxxxxxxx"
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "tag": "text",
        "text": {
            "content": send_text
        }
    }
    # 将Python对象编码成JSON字符串
    post_data = json.dumps(data)
    response = requests.request("POST", url, headers=headers, data=post_data)
    print(response.text.encode('utf8'))
    print("job end time:%s" % arrow.get().format())


def run():
    response = requests.post(url=url, headers=headers, cookies=cookies, data=data, verify=False)
    # Prints the time formatted according to the specified format
    current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    f = open('log.txt', 'a')
    f.write(str(current_time) + '\n')
    f.close()
    

# 每天在09:30时间点运行send_news函数
schedule.every().day.at("09:30").do(send_news)         

# Execute the task every 15 minutes
schedule.every(15).minutes.do(run)

# 运行一个死循环
while True:
    schedule.run_pending()   # 运行所有可以运行的任务
    time.sleep(1)

想要深入了解schedule和定时任务的,可以参考知乎的一篇文章:Python 定时任务最佳实践

三. 服务器上运行(Linux)

首先,你得有一台服务器。
我用的是CentOS7,现在Linux机器系统默认安装的是python2。
但是我用的是python3,所以需要升级一下。

1.CentOS7升级python2到python3

安装依赖:

yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc libffi-devel

下载,解压:

cd /usr/local/
mkdir python3
cd python3/
wget https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tgz
tar -zxf Python-3.8.2.tgz
cd Python-3.8.2

编译:

./configure
make
make install

备份python2:

mv /usr/bin/python /usr/bin/python.bak

创建新的软连接:

ln -s /usr/local/bin/python3.8 /usr/bin/python

更改yum配置,因为yum要使用python2:

vim /usr/bin/yum
vim /usr/libexec/urlgrabber-ext-down

将这两个文件头的 #!/usr/bin/python 改为 #!/usr/bin/python2。

2.安装需要的库

参考本地安装方法

3.把脚本上传到服务器

命令:scp -r local_dir username@servername:remote_dir
例子:把当前目录下的test目录上传到服务器的/var/www/ 目录

scp -r test root@192.168.0.101:/var/www/

如果只需要上传某个文件,可以执行:

scp /path/filename username@servername:/path/
4.实现后台运行

因为我们远程服务器的终端不可能一直打开着,当终端关闭后,普通开启的进程就会自动关闭。所以我们需要使用nohup(not hang up)命令,实现脚本后台运行。
1.简单使用:

nohup python test.py &
nohup python eating_bot.py > nohup.out 2>&1 &

查看后台运行的jobs和进程PID:

jobs -l

image.png 将python test.py任务放到后台,但是依然可以使用标准输入,终端能够接收任何输入,重定向标准输出和标准错误到当前目录下的nohup.out文件,即使关闭xshell退出当前session依然继续运行。
详细可以参考:linux 下后台运行python脚本

2.查看后台的python进程:

ps aux | grep python | grep -v grep 

image.png