python定时发送qq消息(QQBot实现)

前言

因为生活中老是忘记各种事情,刚好又在学Python,便突发奇想通过python实现提醒任务的功能(尽管TIM有定时功能),也可定时给好友、群、讨论组发送qq消息。其工作流程是:访问数据库提取最近计划——>根据数据内容(提醒时间、提醒对象、提醒内容)设置定时任务——>给特定qq好友发送消息。


更新说明: 目前因为webqq已经关闭, 导致qqbot无法使用, 以下代码已失效. 至于博友推荐的qqbot替代方案js-bot, 本人尚未学习尝试.

软件版本

软件 版本
python 3.6.4
pip 18.0
qqbot 2.3.10

过程

安装依赖环境

  • pymysql安装:pip install pymysql
  • qqbot安装:pip install qqbot

数据库处理

数据库操作非常简单,跟Java类似,自己去 菜鸟教程 看一下基础语法就好了。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#coding: utf-8
import pymysql	#导入pymysql模块

db = pymysql.connect("localhost","root","root","info_db" )  		#数据库链接信息
cursor = db.cursor()

#插入任务
def insertSchedule(schedule):
    insertsql = "insert into dutyschedule_tb(worktime,name) values(%s,%s)"
    try:
	    #这种查询语句可以防止sql注入
        cursor.execute(insertsql,(schedule['worktime'],schedule['name']))
        db.commit()
    except Exception:
        db.rollback()
        raise Exception

#删除任务
def deleteSchedule():
    deletesql = ""
    try:
        cursor.execute(deletesql)
        db.commit()
    except Exception:
        db.rollback()

def updateSchedule(user):
    updatesql = ""
    try:
        cursor.execute(updatesql)
        db.commit()
    except Exception:
        db.rollback()

#获取下一个任务
def findScheduleByNewTime():
    selectsql = "SELECT * FROM dutyschedule_tb where NOW() <= date_format(worktime,'%Y-%m-%d %H:%i:%S') ORDER BY worktime ASC;"
    try:
        cursor.execute(selectsql)
        results = cursor.fetchone()
        schedule = {}
        schedule['worktime'] = results[1]
        schedule['name'] = results[2]
        schedule['content'] = results[3]
        return schedule
    except Exception:
        return None

配置qqbot登陆信息

也可以不配置,不配置的话默认就是每次扫码登陆,但这在Linux系统下不好用,我按说明将配置改成了每次将登陆二维码发到固定qq邮箱。qqbot模块在GitHub上,大家可以去看一下模块说明:qqbot

配置文件默认在用户目录下的.qqbot-tmp/v2.3.confLinux下类似

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

{

    # QQBot 的配置文件
    # 使用 qqbot -u somebody 启动程序时,依次加载:
    #     根配置 -> 默认配置 -> 用户 somebody 的配置 -> 命令行参数配置
    # 使用 qqbot 启动程序时,依次加载:
    #     根配置 -> 默认配置 -> 命令行参数配置
   
	"fantasy" : {
	        # 这是自己创建的用户自定义配置,可以在启动qqbot启动时选择加载哪个配置文件   
        # QQBot-term (HTTP-API) 服务器端口号(该服务器监听 IP 为 127.0.0.1 )
        # 设置为 0 则不会开启本服务器(此时 qq 命令和 HTTP-API 接口都无法使用)。
        "termServerPort" : 8188,
        
        # 二维码 http 服务器 ip,请设置为公网 ip 或空字符串
        "httpServerIP" : "",
        
        # 二维码 http 服务器端口号
        "httpServerPort" : 8189,
        
        # 自动登录的 QQ 号
        "qq" : "你的qq",
        
        # 接收二维码图片的邮箱账号
        "mailAccount" : "你的邮箱",
        
        # 该邮箱的 IMAP/SMTP 服务授权码,一般在邮箱设置中有
        "mailAuthCode" : "你的授权码",
        
        # 是否以文本模式显示二维码
        "cmdQrcode" : False,
    
        # 显示/关闭调试信息
        "debug" : False,

        # QQBot 掉线后自动重启
        "restartOnOffline" : True,
        
        # 在后台运行 qqbot ( daemon 模式)
        "daemon": False,
        
        # 完成全部联系人列表获取之后才启动 QQBot 
        "startAfterFetch" : False,
        
        # 插件目录
        "pluginPath" : ".",
        
        # 启动时需加载的插件
        "plugins" : [],
        
        # 插件的配置(由用户自定义)
        "pluginsConf" : {},
    
    },
	
    # 用户 somebody 的配置,这是默认配置
    "somebody" : {
        #这里的基本内容跟上面一样,就不贴出来了,太长了占地方
    
    
    },
    
    # 可以在 默认配置 中配置所有用户都通用的设置
    "默认配置" : {
        "qq" : "",
        "pluginPath" : "",
        "plugins" : [
            'qqbot.plugins.sampleslots',
            'qqbot.plugins.schedrestart',
        ],
	    "pluginsConf" : {
	        'qqbot.plugins.schedrestart': '8:00',
	    }
    },
    
    # # 注意:根配置是固定的,用户无法修改(在本文件中修改根配置不会生效)
    # "根配置" : {
    #     "termServerPort" : 8188,
    #     "httpServerIP" : "",
    #     "httpServerPort" : 8189,
    #     "qq" : "",
    #     "mailAccount" : "",
    #     "mailAuthCode" : "",
    #     "cmdQrcode" : False,
    #     "debug" : False,
    #     "restartOnOffline" : False,
    #     "daemon" : False,
    #     "startAfterFetch" : False,
    #     "pluginPath" : "",
    #     "plugins" : [],
    #     "pluginsConf" : {}
    # },

}

自定义功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from qqbot import _bot as bot

#登陆qq,使用配置文件为fantasy
bot.Login(['-u','fantasy'])

#自定义函数,用来进一步封装qqbot接口
#获取所有好友列表
def getBuddyByName(nickname):
    return bot.List('buddy',nickname)

#获取所有群列表
def getGroupByName(groupname):
    return bot.List('group',groupname)

#给备注(没用备注就是昵称)为nickname的好友发送content消息
def sendToNickname(nickname,content):
    user = getBuddyByName(nickname)
    if user:
        bot.SendTo(user[0],content)
    else:
        print("未找到联系人:"+nickname)

入口主程序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#coding: utf-8
import time
import sched
import datetime
from Dao.DutyscheduleDao import *
from Utils.QQInterface import *
#sched是python的定时任务模块


schedule = sched.scheduler(time.time, time.sleep)
#从数据库获取第一个任务
newschedule = findScheduleByNewTime()

#返回距下次任务还有多少秒
def getSeconds():
    #申明全局变量
    global newschedule
    newschedule = findScheduleByNewTime()
    if newschedule:
        return (newschedule['worktime'] - datetime.datetime.now()).total_seconds()
    else:
        print("所有任务执行完毕,退出程序……")
        exit()

#发消息函数
def SendTo():
    global newschedule
    sendToNickname(newschedule['name'],newschedule['content'])

#中间函数,用于循环运行所有数据库未执行事件
def perform():
    SendTo()
    #睡眠5秒,不然可能会重复发送消息
    time.sleep(5)
    sleepSecond = getSeconds()
    print("下次任务执行时间:"+str(newschedule['worktime']))
    #这次任务执行完后添加新任务
    schedule.enter(sleepSecond,1,perform,())


def run():
    #1.获取数据库最近将执行任务的时间及姓名
    #2.计算执行任务的时间与现在时间的差值(单位:秒)
    sleepSecond = getSeconds()
    print("下次通知:"+str(newschedule['worktime']))
    #3.加入定时处理函数
    schedule.enter(sleepSecond,1,perform,())
    #4.执行定时任务
    schedule.run()

if __name__ == '__main__':
    run()

其它

数据库结构:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
drop database if exists info_db;
create database info_db default character set utf8;

use info_db;
create table dutyschedule_tb(
	id int(11) auto_increment primary key,
	worktime timestamp not null,
	name varchar(10) not null,
	content varchar(100) not null
)engine=InnoDB auto_increment=1 default charset=utf8;

以上就是循环发送qq消息的代码,以下是项目目录结构,其中一些没有出现的文件是我自己测试所用,可以不用关心:
https://cdn.jsdelivr.net/gh/fantasy-ctgu/FileCloud/img/20180918120427595.png

效果图:
https://cdn.jsdelivr.net/gh/fantasy-ctgu/FileCloud/img/20180918121804402.png
https://cdn.jsdelivr.net/gh/fantasy-ctgu/FileCloud/img/20180918121522791.png

总结

基本功能完成了,但是操作不够友好,需要手动往数据库录入数据,之后准备做一个数据管理的前端配合使用,可以简化很多操作。有什么问题欢迎讨论