使用方法
命令:急转弯/猜谜语
发送命令后会返回问题,再次发送1可以查看答案
使用截图
实现思路
调用急速数据网API,网址为https://www.jisuapi.com/
注册账号,获取appkey,申请该数据,发送api请求,便可以获取数据。由于免费版一天只能请求100次,在群里中使用,可以次数不够。在此编写了一个脚本程序,每天定时循环调用API满次数,将返回的数据与数据库对比,将新数据存储在数据库中,发送指令时,机器人只本地数据库,不再进行API的调用。
代码部分
将获取到的数据与数据库进行对比,新数据添加到数据库中
def data_to_csv(data, file_name = jzw_file_name):
try:
with open(file_name, 'r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
existing_data = [row for row in reader]
next_id = len(existing_data) + 1
except FileNotFoundError:
existing_data = []
next_id = 1
fieldnames = ['序号', 'content', 'answer']
with open(file_name, 'a', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not existing_data:
writer.writeheader()
for item in data:
if not any(existing_item['content'] == item['content'] and existing_item['answer'] == item['answer'] for existing_item in existing_data):
new_item = {'序号': next_id, 'content': item['content'], 'answer': item['answer']}
writer.writerow(new_item)
next_id += 1
完整代码如下
import requests
import csv
import logging
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
# 创建一个文件处理器,将日志输出到'my_log.log'文件
fh = logging.FileHandler('my_log.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
# appkey更改为自己的
miyu_url = 'https://api.jisuapi.com/miyu/search?appkey=########&pagenum=1&pagesize=2&classid='
jwz_url = 'https://api.jisuapi.com/jzw/search?appkey=########&pagenum=1&pagesize=1'
# 文件路径更改为自己路径
miyu_file_name = r'C:\bot\*\dict_miyu.csv'
jzw_file_name = r'C:\bot\*\dict_jzw.csv'
def data_to_csv(data):
try:
with open(file_name, 'r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
existing_data = [row for row in reader]
next_id = len(existing_data) + 1
except FileNotFoundError:
existing_data = []
next_id = 1
fieldnames = ['序号', 'content', 'answer']
with open(file_name, 'a', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not existing_data:
writer.writeheader()
for item in data:
if not any(existing_item['content'] == item['content'] and existing_item['answer'] == item['answer'] for existing_item in existing_data):
new_item = {'序号': next_id, 'content': item['content'], 'answer': item['answer']}
writer.writerow(new_item)
next_id += 1
for _ in range(100):
response = requests.get(miyu_url)
data = response.json()
data_to_csv(data['result']['list'],file_name = miyu_file_name)
for _ in range(100):
response = requests.get(jwz_url)
data = response.json()
data_to_csv(data["result"]["list"],file_name = jzw_file_name)
logger.critical('运行完成')
定时任务
参考2开机自启配置,分别创建task.bat和runbat.vbs文件
bat代码
@echo off
python task.py
vbs代码
Set objShell = CreateObject("WScript.Shell")
objShell.Run "task.bat", 0, False
在计算机管理-->系统工具-->任务计划程序中创建任务,更改触发器类型为每日固定时间,
操作为启动程序runbat.vbs