├── .gitignore ├── config.template.json ├── README.md ├── base.py ├── config.py ├── lolicon.py ├── __init__.py ├── acggov.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | *.py[cod] 3 | .vscode/ 4 | .vs/ 5 | 6 | *.json 7 | !config.template.json 8 | -------------------------------------------------------------------------------- /config.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "base": { 3 | "daily_max": 10, 4 | "freq_limit": 10, 5 | "whitelistmode": false, 6 | "blacklistmode": false, 7 | "ban_if_group_num_over": 3000, 8 | "max_pic_once_send": 1, 9 | "enable_forward_msg": true 10 | }, 11 | "default": { 12 | "withdraw": 0, 13 | "lolicon": true, 14 | "lolicon_r18": false, 15 | "acggov": false 16 | }, 17 | "lolicon": { 18 | "mode": 2, 19 | "r18": true, 20 | "use_thumb": false, 21 | "pixiv_direct": false, 22 | "proxy_site": "", 23 | "local_proxy": "" 24 | }, 25 | "acggov": { 26 | "mode": 2, 27 | "apikey": "", 28 | "ranking_mode": "daily", 29 | "use_thumb": false, 30 | "per_page": 25, 31 | "pixiv_direct": false, 32 | "pixiv_proxy": "", 33 | "acggov_proxy": "" 34 | } 35 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # setu_renew 2 | 3 | **Deprecated** 4 | 5 | 基于HoshinoBot v2的涩图插件, 从 [acg-gov.com](https://acg-gov.com) 和 [lolicon.app](https://lolicon.app/) 获取图片. 6 | 7 | **本项目基于@zyujs的[setu_mix](https://github.com/zyujs/setu_mix)改进而来。** 8 | 9 | ## 主要改进 10 | 11 | - [x] 加入了群黑白名单功能 12 | - [x] 加入了群人数限制功能 13 | - [x] 代理全覆盖,从查询到获取到下载 14 | - [x] 搜索/发送/下载失败时均会发送提示,防止出现指令无响应或无下文的假象 15 | - [x] 搜索无结果时可以随机发送一份涩图 16 | - [x] 优化发送消息结构 17 | - [x] 优化发图流程,本地图片使用file协议发送 18 | - [x] 可根据图片pid提取图片,若本地有则会直接发送,否则会给出原图链接 19 | - [x] 优化触发指令,将随机涩图的指令与指定关键词的指令合并 20 | - [x] 支持自定义一人一次最多要的涩图数量 21 | - [x] 中文化管理指令 22 | - [x] 自动反和谐(~~感谢[@dexzopiclone](https://github.com/dexzopiclone)~~) 23 | - [x] 使用转发消息的形式发送(规避检测,降低被举报的风险) 24 | 25 | ## 注意事项 26 | 刚开始使用插件时本地仓库为空, 会导致无法发送随机图片, 可以在安装配置完毕后使用 `setu 缓存` 命令手动抓取一批图片. 27 | 28 | ## 安装方法 29 | 30 | 1. 在HoshinoBot的插件目录modules下clone本项目 `git clone https://github.com/pcrbot/setu_renew.git` 31 | 1. 将本插件目录下的配置文件模板 `config.template.json` 复制并重命名为 `config.json` , 修改该配置文件设置自己的apikey和其他选项, 除apikey以外都可保持默认值. 32 | 1. 在 `config/__bot__.py`的模块列表里加入 `setu_renew` 33 | 1. 重启HoshinoBot 34 | 35 | ## 配置文件详细说明 36 | 37 | **lolicon api v2 不再需要apikey** 38 | 39 | **acggov源已废弃,不再支持** 40 | 41 | - `base`分组: 42 | - `daily_max` : 每日每人要涩图的上限 43 | - `freq_limit` : 两次之间的冷却时间 44 | - `whitelistmode` : 白名单模式, 仅允许位于白名单中的群要涩图 45 | - `blacklistmode` : 黑名单模式, 不允许黑名单中的群要涩图 46 | - `ban_if_group_num_over` : 自动黑名单设置, 将群人数超过此处设置的自动加入黑名单, 设置为3000表示不启用 47 | - `max_pic_once_send` : 每人一次最多要涩图的张数 48 | - `enable_forward_msg`: 是否启用转发消息模式 49 | - `default`分组 : 此处的配置为每个群的默认配置 50 | - `withdraw` : 撤回时间, 0为不撤回 51 | - `lolicon`、`lolicon_r18`、`acggov` : 是否启用各图源 52 | - `lolicon`分组: 53 | - `mode` : 模块模式, 0=关闭, 1=在线(不使用本地仓库), 2=在线(使用本地仓库), 3=离线(仅使用本地仓库), 默认模式为2. 54 | - `r18` : 是否启用r18 55 | - `use_thumb` : 是否发送大小更小的图 56 | - `pixiv_direct` : 是否直连访问pixiv, 若使用代理请在下方配置代理,并将此项置否 57 | - `proxy_site` : pixiv的代理站或镜像站 **(推荐使用`https://i.pixiv.re/`)** 58 | - `local_proxy` : 本地代理地址, 不需要请留空. 59 | 60 | ## 指令说明 61 | 62 | - 来 [num] 张 [keyword] 涩/色/瑟图 : 来num张keyword的涩图 63 | (不指定数量与关键字发送一张随机涩图) 64 | - 涩/色/瑟图 : 发送一张随机涩图 65 | - 本日涩图排行榜 [page] : 获取[第page页]p站排行榜(需开启acggov模块) 66 | - 看涩图 [n] 或 [start end] : 获取p站排行榜[第n名/从start名到end名]色图(需开启acggov模块) 67 | - 提取图片 pid : 获取指定pid的图片,若本地有则会直接发送,否则将给出原图链接. 68 | 69 | ### 以下指令仅限超级用户使用 70 | 71 | - `setu 设置 模块 设置值 [群号]` : 修改本群或指定群的设置 72 | 设置项 - 取值 - 说明: 73 | - `acggov` : `开 / 关` 是否开启acggov模块 74 | - `lolicon` : `开 / 关` 是否开启lolicon模块 75 | - `lolicon_r18` : `开 / 关` 是否开启lolicon_r18模块 76 | - `撤回` : `n` 发出的图片在n秒后撤回, 设置为0表示不撤回 77 | - `setu 状态 [群号]` : 查看本群或指定群的模块开启状态 78 | - `setu 缓存` : 手动从api拉取一批图片存入本地仓库(插件每10分钟会自动拉取一次) 79 | - `setu 仓库` : 查询本地仓库图片数量 80 | - `setu 黑/白名单 新增/添加/移除/删除 群号` : 修改黑白名单 81 | 82 | ## 已知问题 83 | 84 | - 使用纯在线模式时,采用的是base64方式发送,而此方法无法发送过大的图片,故有较大概率无法发送 85 | 86 | ## 开源协议 87 | 88 | 本插件以AGPL-v3协议开源 89 | -------------------------------------------------------------------------------- /base.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import base64 3 | import io 4 | import os 5 | import random 6 | from typing import Tuple 7 | 8 | from PIL import Image, ImageDraw 9 | 10 | from hoshino import R 11 | from .acggov import acggov_fetch_process, acggov_get_ranking, acggov_get_ranking_setu, acggov_get_setu, acggov_init, \ 12 | acggov_search_setu, get_setu_native 13 | from .config import get_config, get_group_config 14 | from .lolicon import get_setu_native, lolicon_fetch_process, lolicon_get_setu, lolicon_init, lolicon_search_setu 15 | 16 | 17 | def check_path(): 18 | state = {} 19 | sub_dirs = ['acggov', 'lolicon', 'lolicon_r18'] 20 | for item in sub_dirs: 21 | res = R.img('setu_mix/' + item) 22 | if not os.path.exists(res.path): 23 | os.makedirs(res.path) 24 | state[item] = len(os.listdir(res.path)) // 2 25 | return state 26 | 27 | 28 | check_path() 29 | 30 | 31 | def get_spec_image(id): 32 | image = get_setu_native(0, id) 33 | if not image: 34 | return None 35 | else: 36 | image = format_setu_msg(image) 37 | return image 38 | 39 | 40 | def format_setu_msg(image): 41 | try: 42 | if image["title"]: 43 | try: 44 | im = Image.open(io.BytesIO(image["data"])) 45 | except: 46 | im = Image.open(image["data"]) 47 | width, height = im.size 48 | draw = ImageDraw.Draw(im) 49 | draw.point((random.randint(1, width), random.randint(1, height)), fill=(random.randint(0, 255), 50 | random.randint(0, 255), 51 | random.randint(0, 255))) 52 | image["data"] = io.BytesIO() 53 | im.save(image["data"], format='JPEG') 54 | image["data"] = image["data"].getvalue() 55 | base64_str = f"base64://{base64.b64encode(image['data']).decode()}" 56 | msg = f'「{image["title"]}」/「{image["author"]}」\nPID:{image["id"]}[CQ:image,file={base64_str}]' 57 | return msg 58 | else: 59 | return None 60 | except TypeError: 61 | return None 62 | 63 | 64 | async def get_setu(group_id): 65 | source_list = [] 66 | if get_group_config(group_id, 'lolicon'): 67 | source_list.append(1) 68 | if get_group_config(group_id, 'lolicon_r18'): 69 | source_list.append(2) 70 | if get_group_config(group_id, 'acggov'): 71 | source_list.append(3) 72 | source = 0 73 | if len(source_list) > 0: 74 | source = random.choice(source_list) 75 | 76 | image = None 77 | if source == 1: 78 | image = await lolicon_get_setu(0) 79 | elif source == 2: 80 | image = await lolicon_get_setu(1) 81 | elif source == 3: 82 | image = await acggov_get_setu() 83 | else: 84 | return None 85 | if not image: 86 | return '获取失败' 87 | elif image['id'] != 0: 88 | return format_setu_msg(image) 89 | else: 90 | return image['title'] 91 | 92 | 93 | async def search_setu(group_id, keyword, num): 94 | source_list = [] 95 | if get_group_config(group_id, 'lolicon') and get_group_config(group_id, 'lolicon_r18'): 96 | source_list.append(2) 97 | elif get_group_config(group_id, 'lolicon'): 98 | source_list.append(0) 99 | elif get_group_config(group_id, 'lolicon_r18'): 100 | source_list.append(1) 101 | if get_group_config(group_id, 'acggov'): 102 | source_list.append(3) 103 | 104 | if len(source_list) == 0: 105 | return [] 106 | 107 | image_list = None 108 | msg_list = [] 109 | while len(source_list) > 0 and len(msg_list) == 0: 110 | source = source_list.pop(random.randint(0, len(source_list) - 1)) 111 | if source == 0: 112 | image_list = await lolicon_search_setu(keyword, 0, num) 113 | elif source == 1: 114 | image_list = await lolicon_search_setu(keyword, 1, num) 115 | elif source == 2: 116 | image_list = await lolicon_search_setu(keyword, 2, num) 117 | elif source == 3: 118 | image_list = await acggov_search_setu(keyword, num) 119 | if image_list and len(image_list) > 0: 120 | for image in image_list: 121 | msg_list.append(format_setu_msg(image)) 122 | return msg_list 123 | 124 | 125 | async def get_ranking(group_id, page: int = 0): 126 | if not get_group_config(group_id, 'acggov'): 127 | return None 128 | return await acggov_get_ranking(page) 129 | 130 | 131 | async def get_ranking_setu(group_id, number: int) -> Tuple[int, str]: 132 | if not get_group_config(group_id, 'acggov'): 133 | return None 134 | image = await acggov_get_ranking_setu(number) 135 | if not image: 136 | return '获取失败' 137 | elif image['id'] != 0: 138 | return format_setu_msg(image) 139 | else: 140 | return image['title'] 141 | 142 | 143 | async def fetch_process(): 144 | tasks = [] 145 | if get_config('default', 'acggov'): 146 | await acggov_fetch_process() 147 | if get_config('default', 'lolicon') or get_config('default', 'lolicon_r18'): 148 | await lolicon_fetch_process() 149 | 150 | 151 | acggov_init() 152 | lolicon_init() 153 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import os 4 | import random 5 | import traceback 6 | 7 | import nonebot 8 | 9 | import hoshino 10 | 11 | cfgpath = os.path.join(os.path.dirname(__file__), 'config.json') 12 | grouplistpath = os.path.join(os.path.dirname(__file__), 'grouplist.json') 13 | groupconfigpath = os.path.join(os.path.dirname(__file__), 'groupconfig.json') 14 | group_config = {} 15 | config = {} 16 | invaild_key_dict = {} 17 | group_list = {} 18 | config = json.load(open(cfgpath, 'r', encoding='utf8')) 19 | group_list = json.load(open(grouplistpath, 'r', encoding='utf8')) 20 | group_config = json.load(open(groupconfigpath, 'r', encoding='utf8')) 21 | 22 | 23 | 24 | def get_config(key, sub_key): 25 | if key in config and sub_key in config[key]: 26 | return config[key][sub_key] 27 | return None 28 | 29 | 30 | def group_list_check(gid): 31 | """ 32 | 响应值:\n 33 | 0 : ok\n 34 | 1 : 启用白名单模式且不在白名单内\n 35 | 2 : 启用黑名单模式且在黑名单内\n 36 | 白名单优先级高于黑名单 37 | """ 38 | gid = str(gid) 39 | if get_config('base', 'whitelistmode') is True: 40 | if gid in group_list["white_list"]: 41 | return 0 42 | else: 43 | return 1 44 | elif get_config('base', 'blacklistmode') is True: 45 | if gid in group_list["black_list"]: 46 | return 2 47 | else: 48 | return 0 49 | else: 50 | return 0 51 | 52 | 53 | def set_group_list(gid, _list, mode): 54 | """ 55 | gid(int,str/list) : group id \n 56 | _list(int/str) : 0 whitelist / 1 blacklist\n 57 | mode(int/str) : 0 add / 1 remove\n 58 | 返回值(第一字段 / int) : \n 59 | 0 ok\n 60 | 401 黑名单模式未开启\n 61 | 402 白名单模式未开启\n 62 | 403 无法访问黑白名单\n 63 | 404 gid不在指定的列表中\n 64 | 500 传入数据格式无效\n 65 | 返回值(第二字段 / list/str) :\n 66 | 空字符串 ok\n 67 | gid 未完成操作的gid 68 | """ 69 | failed_gids = [] 70 | try: 71 | _list = int(_list) 72 | except: 73 | return 500, '' 74 | try: 75 | mode = int(mode) 76 | except: 77 | return 500, '' 78 | if type(gid) == int or type(gid) == str: 79 | gid = [str(gid)] 80 | elif type(gid) == list: 81 | gid = [str(i) for i in gid] 82 | else: 83 | return 500, '' 84 | if _list == 0: 85 | if mode == 0: 86 | for i in gid: 87 | group_list["white_list"].append(i) 88 | if mode == 1: 89 | for i in gid: 90 | if i in group_list["white_list"]: 91 | group_list["white_list"].remove(i) 92 | else: 93 | hoshino.logger.error(f'[ERROR]gid {i} 不在指定列表中') 94 | failed_gids.append(i) 95 | continue 96 | group_list["white_list"] = list(set(group_list["white_list"])) 97 | else: 98 | if mode == 0: 99 | for i in gid: 100 | group_list["black_list"].append(i) 101 | if mode == 1: 102 | for i in gid: 103 | if i in group_list["black_list"]: 104 | group_list["black_list"].remove(i) 105 | else: 106 | hoshino.logger.error(f'[ERROR]gid {i} 不在指定列表中') 107 | failed_gids.append(i) 108 | continue 109 | group_list["black_list"] = list(set(group_list["black_list"])) 110 | try: 111 | with open(grouplistpath, 'w') as f: 112 | json.dump(group_list, f, ensure_ascii=False, indent=2) 113 | if get_config('base', 'blacklistmode') is False: 114 | return 401, failed_gids 115 | if get_config('base', 'whitelistmode') is False: 116 | return 402, failed_gids 117 | return 0, failed_gids 118 | except: 119 | return 403, failed_gids 120 | 121 | 122 | def get_api_num(): 123 | return int(len(config["lolicon"]["apikey"])) 124 | 125 | 126 | def get_group_config(group_id, key): 127 | group_id = str(group_id) 128 | if group_id not in group_config: 129 | return config['default'][key] 130 | if key in group_config[group_id]: 131 | return group_config[group_id][key] 132 | else: 133 | return None 134 | 135 | 136 | def set_group_config(group_id, key, value): 137 | group_id = str(group_id) 138 | if group_id not in group_config: 139 | group_config[group_id] = {} 140 | for k, v in config['default'].items(): 141 | group_config[group_id][k] = v 142 | group_config[group_id][key] = value 143 | try: 144 | with open(groupconfigpath, 'w', encoding='utf8') as f: 145 | json.dump(group_config, f, ensure_ascii=False, indent=2) 146 | except: 147 | traceback.print_exc() 148 | 149 | 150 | async def get_group_info(group_ids=0, info_type='member_count'): 151 | """ 152 | 1. 传入一个整型数字, 返回单个群指定信息, 格式为字典 153 | 2. 传入一个list, 内含多个群号(int), 返回一个字典, 键为群号, 值为指定信息 154 | 3. 不填入参数, 返回一个包含所有群号与指定信息的字典 155 | 无论获取多少群信息, 均只有一次API的开销, 传入未加入的群时, 将自动忽略 156 | info_type支持group_id, group_name, max_member_count, member_count 157 | """ 158 | group_info_all = await get_group_list_all() 159 | _gids = [] 160 | _gnames = [] 161 | # 获得的已加入群为列表形式, 处理为需要的字典形式 162 | for it in group_info_all: 163 | _gids.append(it['group_id']) 164 | _gnames.append(it[info_type]) 165 | group_info_dir = dict(zip(_gids, _gnames)) 166 | 167 | if group_ids == 0: 168 | return group_info_dir 169 | if type(group_ids) == int: 170 | # 转为列表 171 | group_ids = [group_ids] 172 | hoshino.logger.error(group_ids) 173 | 174 | for key in list(group_info_dir.keys()): 175 | if key not in group_ids: 176 | del group_info_dir[key] 177 | else: 178 | # TODO: group not joined 179 | pass 180 | return group_info_dir 181 | 182 | 183 | async def get_group_list_all(): 184 | """ 185 | 获取所有群, 无论授权与否, 返回为原始类型(列表) 186 | """ 187 | bot = nonebot.get_bot() 188 | self_ids = bot._wsr_api_clients.keys() 189 | for sid in self_ids: 190 | group_list = await bot.get_group_list(self_id=sid) 191 | return group_list 192 | -------------------------------------------------------------------------------- /lolicon.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import io 3 | import json 4 | import os 5 | import random 6 | import traceback 7 | 8 | import aiohttp 9 | from PIL import Image 10 | 11 | import hoshino 12 | from hoshino import R 13 | from .config import get_api_num, get_config 14 | 15 | quota_limit_time = datetime.datetime.now() 16 | 17 | 18 | def generate_image_struct(): 19 | return { 20 | 'id': 0, 21 | 'url': '', 22 | 'title': '', 23 | 'author': '', 24 | 'tags': [], 25 | 'r18': False, 26 | 'data': None, 27 | 'native': False, 28 | } 29 | 30 | 31 | native_info = {} 32 | native_r18_info = {} 33 | 34 | 35 | def load_native_info(sub_dir): 36 | info = {} 37 | path = f'setu_mix/' + sub_dir 38 | res = R.img(path) 39 | if not os.path.exists(res.path): 40 | return info 41 | fnlist = os.listdir(res.path) 42 | 43 | for fn in fnlist: 44 | s = fn.split('.') 45 | if len(s) != 2 or s[1] != 'json' or not s[0].isdigit(): 46 | continue 47 | uid = int(s[0]) 48 | try: 49 | with open(res.path + '/' + fn, encoding='utf8') as f: 50 | d = json.load(f) 51 | d['tags'].append(d['title']) 52 | d['tags'].append(d['author']) 53 | info[uid] = ','.join(d['tags']) 54 | except: 55 | pass 56 | hoshino.logger.info(f'[INFO]read{len(info)}setu from{sub_dir}') 57 | return info 58 | 59 | 60 | # 获取随机色图 61 | async def query_setu(r18=0, keyword=None): 62 | image_list = [] 63 | 64 | data = {} 65 | url = 'https://api.lolicon.app/setu/v2' 66 | params = { 67 | 'r18': r18, 68 | 'num': 10, 69 | } 70 | if keyword: 71 | params['keyword'] = keyword 72 | thumb = get_config('lolicon', 'use_thumb') 73 | if thumb: 74 | params['size'] = 'regular' 75 | if get_config('lolicon', 'pixiv_direct'): 76 | params['proxy'] = '' 77 | 78 | try: 79 | async with aiohttp.ClientSession() as session: 80 | async with session.get(url, params=params, proxy=get_config('lolicon', 'local_proxy')) as resp: 81 | data = await resp.json(content_type='application/json') 82 | except Exception: 83 | traceback.print_exc() 84 | return image_list 85 | if 'error' not in data: 86 | return image_list 87 | if data['error'] != '': 88 | hoshino.logger.error(f'[ERROR]lolicon api error,msg:{data["error"]}') 89 | return image_list 90 | for item in data['data']: 91 | image = generate_image_struct() 92 | image['id'] = item['pid'] 93 | image['title'] = item['title'] 94 | image['url'] = item['urls']['regular' if thumb else 'original'].replace("https://i.pixiv.cat/", 95 | get_config('lolicon', 'proxy_site')) 96 | image['tags'] = item['tags'] 97 | image['r18'] = item['r18'] 98 | image['author'] = item['author'] 99 | image_list.append(image) 100 | return image_list 101 | 102 | 103 | async def download_image(url: str): 104 | hoshino.logger.info(f'[INFO]lolicon downloading image:{url}') 105 | try: 106 | async with aiohttp.ClientSession() as session: 107 | async with session.get(url, proxy=get_config('lolicon', 'local_proxy')) as resp: 108 | data = await resp.read() 109 | # 转jpg 110 | byte_stream = io.BytesIO(data) 111 | roiImg = Image.open(byte_stream) 112 | if roiImg.mode != 'RGB': 113 | roiImg = roiImg.convert('RGB') 114 | imgByteArr = io.BytesIO() 115 | roiImg.save(imgByteArr, format='JPEG') 116 | return imgByteArr.getvalue() 117 | except Exception as e: 118 | hoshino.logger.error( 119 | '[ERROR]download image {} failed,error {}'.format(url, e)) 120 | # traceback.print_exc() 121 | return None 122 | 123 | 124 | async def download_pixiv_image(url: str, id): 125 | hoshino.logger.info(f'[INFO]lolicon downloading pixiv image:{url}') 126 | headers = { 127 | 'referer': f'https://www.pixiv.net/member_illust.php?mode=medium&illust_id={id}' 128 | } 129 | try: 130 | async with aiohttp.ClientSession(headers=headers) as session: 131 | async with session.get(url, proxy=get_config('lolicon', 'local_proxy')) as resp: 132 | data = await resp.read() 133 | # 转jpg 134 | byte_stream = io.BytesIO(data) 135 | roiImg = Image.open(byte_stream) 136 | if roiImg.mode != 'RGB': 137 | roiImg = roiImg.convert('RGB') 138 | imgByteArr = io.BytesIO() 139 | roiImg.save(imgByteArr, format='JPEG') 140 | return imgByteArr.getvalue() 141 | except Exception as e: 142 | hoshino.logger.error( 143 | '[ERROR]download image {} failed,error {}'.format(url, e)) 144 | # traceback.print_exc() 145 | return None 146 | 147 | 148 | def save_image(image): 149 | path = f'setu_mix/lolicon/{image["id"]}' 150 | if image['r18']: 151 | path = f'setu_mix/lolicon_r18/{image["id"]}' 152 | 153 | res = R.img(path + '.jpg') 154 | with open(res.path, 'wb') as f: 155 | f.write(image['data']) 156 | 157 | res = R.img(path + '.json') 158 | info = { 159 | 'title': image['title'], 160 | 'author': image['author'], 161 | 'url': image['url'], 162 | 'tags': image['tags'], 163 | } 164 | with open(res.path, 'w', encoding='utf8') as f: 165 | json.dump(info, f, ensure_ascii=False, indent=2) 166 | 167 | 168 | async def get_setu_online(num, r18=0, keyword=None): 169 | image_list = await query_setu(r18=r18, keyword=keyword) 170 | if image_list == None: 171 | return 172 | valid_list = [] 173 | 174 | while len(image_list) > 0: 175 | image = image_list.pop(random.randint(0, len(image_list) - 1)) 176 | # 检查本地是否存在该图片 177 | path = f'setu_mix/lolicon/{image["id"]}.jpg' 178 | if image['r18']: 179 | path = f'setu_mix/lolicon_r18/{image["id"]}.jpg' 180 | res = R.img(path) 181 | if os.path.exists(res.path): 182 | image['data'] = res.path 183 | image['native'] = True 184 | else: 185 | if get_config('lolicon', 'pixiv_direct'): 186 | image['data'] = await download_pixiv_image(image['url'], image['id']) 187 | else: 188 | image['data'] = await download_image(image['url']) 189 | image['native'] = False 190 | if image['data'] and get_config('lolicon', 'mode') == 2: 191 | save_image(image) 192 | image['data'] = res.path 193 | if image['data']: 194 | valid_list.append(image) 195 | if len(valid_list) >= num: 196 | break 197 | return valid_list 198 | 199 | 200 | def get_setu_native(r18=0, uid=0): 201 | image = generate_image_struct() 202 | 203 | path = f'setu_mix/lolicon' 204 | if r18 == 1: 205 | path = f'setu_mix/lolicon_r18' 206 | elif r18 == 2: 207 | if random.randint(1, 100) > 50: 208 | path = f'setu_mix/lolicon_r18' 209 | res = R.img(path) 210 | if not os.path.exists(res.path): 211 | return image 212 | 213 | if uid == 0: 214 | fn = random.choice(os.listdir(res.path)) 215 | if fn.split('.')[0].isdigit(): 216 | uid = int(fn.split('.')[0]) 217 | 218 | if not uid: 219 | return image 220 | 221 | image['id'] = int(uid) 222 | image['native'] = True 223 | 224 | path += f'/{uid}' 225 | res = R.img(path) 226 | try: 227 | image['data'] = res.path + '.jpg' 228 | with open(res.path + '.json', encoding='utf8') as f: 229 | d = json.load(f) 230 | if 'title' in d: 231 | image['title'] = d['title'] 232 | if 'author' in d: 233 | image['author'] = d['author'] 234 | if 'url' in d: 235 | image['url'] = d['url'] 236 | except: 237 | pass 238 | 239 | return image 240 | 241 | 242 | def search_setu_native(keyword, r18, num): 243 | result_list = [] 244 | if r18 == 0 or r18 == 2: 245 | for k, v in native_info.items(): 246 | if v.find(keyword) >= 0: 247 | result_list.append({ 248 | 'uid': k, 249 | 'r18': 0, 250 | }) 251 | if r18 == 1 or r18 == 2: 252 | for k, v in native_r18_info.items(): 253 | if v.find(keyword) >= 0: 254 | result_list.append({ 255 | 'uid': k, 256 | 'r18': 1, 257 | }) 258 | if len(result_list) > num: 259 | result_list = random.sample(result_list, num) 260 | image_list = [] 261 | for result in result_list: 262 | image = get_setu_native(result['r18'], result['uid']) 263 | if image['data']: 264 | image_list.append(image) 265 | return image_list 266 | 267 | 268 | # r18: 0 正常 1 r18 2 混合 269 | async def lolicon_get_setu(r18): 270 | if get_config('lolicon', 'mode') >= 2: 271 | return get_setu_native(r18) 272 | elif get_config('lolicon', 'mode') == 1: 273 | image_list = await get_setu_online(1, r18) 274 | if len(image_list) > 0: 275 | return image_list[0] 276 | else: 277 | return None 278 | else: 279 | return None 280 | 281 | 282 | # r18: 0 正常 1 r18 2 混合 283 | async def lolicon_search_setu(keyword, r18, num): 284 | if get_config('lolicon', 'mode') == 1 or get_config('lolicon', 'mode') == 2: 285 | return await get_setu_online(num, r18, keyword) 286 | elif get_config('lolicon', 'mode') == 3: # 离线模式 287 | return search_setu_native(keyword, r18, num) 288 | else: 289 | return None 290 | 291 | 292 | async def lolicon_fetch_process(): 293 | if get_config('lolicon', 'mode') == 2: 294 | hoshino.logger.info('[INFO]fetch lolicon setu') 295 | await get_setu_online(10, 0) 296 | if not get_config('lolicon', 'r18') or not get_config('default', 'lolicon_r18'): 297 | return 298 | hoshino.logger.info('[INFO]fetch lolicon r18 setu') 299 | await get_setu_online(10, 1) 300 | 301 | 302 | def lolicon_init(): 303 | global native_info 304 | global native_r18_info 305 | if get_config('lolicon', 'mode') == 3: 306 | native_info = load_native_info('lolicon') 307 | native_r18_info = load_native_info('lolicon_r18') 308 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import traceback 4 | 5 | from nonebot import scheduler 6 | 7 | import hoshino 8 | 9 | HELP_MSG = ''' 10 | 来 [num] 张 [keyword] 涩/色/瑟图 : 来num张keyword的涩图(不指定数量与关键字发送一张随机涩图) 11 | 涩/色/瑟图 : 发送一张随机涩图 12 | 提取图片pid : 获取指定id的p站图片,没有时发送链接 13 | 本日涩图排行榜 [page] : 获取[第page页]p站排行榜(需开启acggov模块) 14 | 看涩图 [n] 或 [start end] : 获取p站排行榜[第n名/从start名到end名]色图(需开启acggov模块) 15 | ''' 16 | sv = hoshino.Service('涩图', bundle='pcr娱乐', help_=HELP_MSG) 17 | 18 | config_default = { 19 | "base": { 20 | "daily_max": 20, # 每日上限次数 21 | "freq_limit": 300, # 频率限制 22 | "whitelistmode": False, # 白名单模式开关 23 | "blacklistmode": False, # 黑名单模式开关 24 | "ban_if_group_num_over": 3000, # 字面意思 25 | "max_pic_once_send": 1, # 一次最大发送图片数量 26 | "enable_forward_msg": True # 启用转发消息模式 27 | }, 28 | "default": { 29 | "withdraw": 45, # 撤回时间,单位秒 30 | "lolicon": True, # lolicon模块开关 31 | "lolicon_r18": False, # lolicon_r18模块开关 32 | "acggov": False # acggov模块开关 33 | }, 34 | "lolicon": { 35 | "mode": 2, # 0禁用 1无缓存 2有缓存在线 3有缓存离线 36 | "r18": False, # R18图开关 37 | "use_thumb": True, # 选取小图开关 38 | "pixiv_direct": False, # 是否直连pixiv 39 | "proxy_site": "https://i.pixiv.re", # pixiv代理地址 40 | "local_proxy": "" # lolicon代理地址 41 | }, 42 | "acggov": { 43 | "mode": 2, # 0禁用 1无缓存 2有缓存在线 3有缓存离线 44 | "apikey": "", # acggov API 45 | "ranking_mode": "daily", # 排行榜模式 46 | "per_page": 25, # 一米哇甘耐 47 | "use_thumb": True, # 选取小图开关 48 | "pixiv_direct": False, # 是否直连pixiv 49 | "pixiv_proxy": "https://i.pixiv.re", # pixiv代理地址 50 | "acggov_proxy": "" # acggov代理地址 51 | } 52 | } 53 | group_list_default = { 54 | "white_list": [ 55 | 56 | ], 57 | "black_list": [ 58 | 59 | ] 60 | } 61 | groupconfig_default = {} 62 | 63 | # Check config if exist 64 | pathcfg = os.path.join(os.path.dirname(__file__), 'config.json') 65 | if not os.path.exists(pathcfg): 66 | try: 67 | with open(pathcfg, 'w') as cfgf: 68 | json.dump(config_default, cfgf, ensure_ascii=False, indent=2) 69 | hoshino.logger.error('[WARNING]未找到配置文件,已根据默认配置模板创建,请打开插件目录内config.json查看和修改。') 70 | except: 71 | hoshino.logger.error('[ERROR]创建配置文件失败,请检查插件目录的读写权限及是否存在config.json。') 72 | traceback.print_exc() 73 | 74 | # check group list if exist 75 | glpath = os.path.join(os.path.dirname(__file__), 'grouplist.json') 76 | if not os.path.exists(glpath): 77 | try: 78 | with open(glpath, 'w') as cfggl: 79 | json.dump(group_list_default, cfggl, ensure_ascii=False, indent=2) 80 | hoshino.logger.error('[WARNING]未找到黑白名单文件,已根据默认黑白名单模板创建。') 81 | except: 82 | hoshino.logger.error('[ERROR]创建黑白名单文件失败,请检查插件目录的读写权限。') 83 | traceback.print_exc() 84 | 85 | # check group config if exist 86 | gpcfgpath = os.path.join(os.path.dirname(__file__), 'groupconfig.json') 87 | if not os.path.exists(gpcfgpath): 88 | try: 89 | with open(gpcfgpath, 'w') as gpcfg: 90 | json.dump(groupconfig_default, gpcfg, ensure_ascii=False, indent=2) 91 | hoshino.logger.error('[WARNING]未找到群个体设置文件,已创建。') 92 | except: 93 | hoshino.logger.error('[ERROR]创建群个体设置文件失败,请检查插件目录的读写权限。') 94 | traceback.print_exc() 95 | 96 | from .base import * 97 | from .config import get_config, get_group_config, get_group_info, set_group_config, group_list_check, set_group_list 98 | 99 | # 设置limiter 100 | tlmt = hoshino.util.DailyNumberLimiter(get_config('base', 'daily_max')) 101 | flmt = hoshino.util.FreqLimiter(get_config('base', 'freq_limit')) 102 | 103 | 104 | def check_lmt(uid, num, gid): 105 | if uid in hoshino.config.SUPERUSERS: 106 | return 0, '' 107 | if group_list_check(gid) != 0: 108 | if group_list_check(gid) == 1: 109 | return 1, f'此功能启用了白名单模式,本群未在白名单中,请联系维护组解决' 110 | else: 111 | return 1, f'此功能已在本群禁用,可能因为人数超限或之前有滥用行为,请联系维护组解决' 112 | if not tlmt.check(uid): 113 | return 1, f"您今天已经冲过{get_config('base', 'daily_max')}次了,请明天再来~" 114 | if num > 1 and (get_config('base', 'daily_max') - tlmt.get_num(uid)) < num: 115 | return 1, f"您今天的剩余次数为{get_config('base', 'daily_max') - tlmt.get_num(uid)}次,已不足{num}次,请少冲点(恼)!" 116 | if not flmt.check(uid): 117 | return 1, f'您冲的太快了,{round(flmt.left_time(uid))}秒后再来吧~' 118 | # tlmt.increase(uid,num) 119 | flmt.start_cd(uid) 120 | return 0, '' 121 | 122 | 123 | def render_forward_msg(msg_list: list, uid=2854196306, name='小冰'): 124 | forward_msg = [] 125 | for msg in msg_list: 126 | forward_msg.append({ 127 | "type": "node", 128 | "data": { 129 | "name": str(name), 130 | "uin": str(uid), 131 | "content": msg 132 | } 133 | }) 134 | return forward_msg 135 | 136 | 137 | async def send_msg(msg_list, ev): 138 | result_list = [] 139 | if not get_config('base', 'enable_forward_msg'): 140 | for msg in msg_list: 141 | try: 142 | result_list.append(await hoshino.get_bot().send(ev, msg)) 143 | except: 144 | hoshino.logger.error('[ERROR]图片发送失败') 145 | await hoshino.get_bot().send(ev, f'涩图太涩,发不出去力...') 146 | await asyncio.sleep(1) 147 | else: 148 | forward_msg = render_forward_msg(msg_list) 149 | try: 150 | result_list.append(await hoshino.get_bot().send_group_forward_msg(group_id=ev.group_id, messages=forward_msg)) 151 | except: 152 | traceback.print_exc() 153 | hoshino.logger.error('[ERROR]图片发送失败') 154 | await hoshino.get_bot().send(ev, f'涩图太涩,发不出去力...') 155 | await asyncio.sleep(1) 156 | return result_list 157 | 158 | 159 | @sv.on_prefix('setu') 160 | async def send_setu(bot, ev): 161 | uid = ev['user_id'] 162 | gid = ev['group_id'] 163 | is_su = hoshino.priv.check_priv(ev, hoshino.priv.SUPERUSER) 164 | args = ev.message.extract_plain_text().split() 165 | 166 | msg = '' 167 | if not is_su: 168 | msg = '需要超级用户权限\n发送"帮助 pcr娱乐"获取操作指令' 169 | elif len(args) == 0: 170 | msg = '无效参数\n发送"帮助 pcr娱乐"获取操作指令' 171 | elif args[0] == '设置' and len(args) >= 3: # setu set module on [group] 172 | if len(args) >= 4 and args[3].isdigit(): 173 | gid = int(args[3]) 174 | if args[1] == 'lolicon': 175 | key = 'lolicon' 176 | elif args[1] == 'lolicon_r18': 177 | key = 'lolicon_r18' 178 | elif args[1] == 'acggov': 179 | key = 'acggov' 180 | elif args[1] == '撤回': 181 | key = 'withdraw' 182 | else: 183 | key = None 184 | if args[2] == '开' or args[2] == '启用': 185 | value = True 186 | elif args[2] == '关' or args[2] == '禁用': 187 | value = False 188 | elif args[2].isdigit(): 189 | value = int(args[2]) 190 | else: 191 | value = None 192 | if key and (not value is None): 193 | set_group_config(gid, key, value) 194 | msg = '设置成功!当前设置值如下:\n' 195 | msg += f'群/{gid} : 设置项/{key} = 值/{value}' 196 | else: 197 | msg = '无效参数' 198 | elif args[0] == '状态': 199 | if len(args) >= 2 and args[1].isdigit(): 200 | gid = int(args[1]) 201 | withdraw_status = "不撤回" if get_group_config(gid, "withdraw") == 0 else f'{get_group_config(gid, "withdraw")}秒' 202 | lolicon_status = "启用" if get_group_config(gid, "lolicon") else "禁用" 203 | lolicon_r18_status = "启用" if get_group_config(gid, "lolicon_r18") else "禁用" 204 | acggov_status = "启用" if get_group_config(gid, "acggov") else "禁用" 205 | msg = f'群 {gid} :' 206 | msg += f'\n撤回时间: {withdraw_status}' 207 | msg += f'\nlolicon 源: {lolicon_status}' 208 | msg += f'\nlolicon_r18 源: {lolicon_r18_status}' 209 | msg += f'\nacggov 源: {acggov_status}' 210 | elif args[0] == '缓存': 211 | await bot.send(ev, '开始缓存') 212 | await fetch_process() 213 | msg = '缓存进程结束' 214 | elif args[0] == '仓库': 215 | msg = '仓库:' 216 | state = check_path() 217 | for k, v in state.items(): 218 | msg += f'\n{k}源 : {v}张' 219 | elif args[0] == "黑名单" and len(args) == 3: # setu 黑名单 新增/删除 gid(一次只能提供一个) 220 | if args[1] in ["新增", "添加"]: 221 | mode = 0 222 | elif args[1] in ["删除", "移除"]: 223 | mode = 1 224 | else: 225 | await bot.finish(ev,"操作错误,应为新增/删除其一") 226 | group_id = args[2] 227 | statuscode, failedgid = set_group_list(group_id, 1, mode) 228 | if statuscode == 403: 229 | msg = '无法访问黑白名单' 230 | elif statuscode == 404: 231 | msg = f'群{failedgid[0]}不在黑名单中' 232 | elif statuscode == 401: 233 | msg = f'警告!黑名单模式未开启!\n成功{args[1]}群{group_id}' 234 | else: 235 | msg = f'成功{args[1]}群{group_id}' 236 | elif args[0] == '白名单' and len(args) == 3: # setu 白名单 新增/删除 gid(一次只能提供一个) 237 | if args[1] in ["新增", "添加"]: 238 | mode = 0 239 | elif args[1] in ["删除", "移除"]: 240 | mode = 1 241 | else: 242 | await bot.finish(ev, "操作错误,应为新增/删除其一") 243 | group_id = args[2] 244 | statuscode, failedgid = set_group_list(group_id, 0, mode) 245 | if statuscode == 403: 246 | msg = '无法访问黑白名单' 247 | elif statuscode == 404: 248 | msg = f'群{failedgid[0]}不在白名单中' 249 | elif statuscode == 402: 250 | msg = f'警告!白名单模式未开启!\n成功{args[1]}群{group_id}' 251 | else: 252 | msg = f'成功{args[1]}群{group_id}' 253 | else: 254 | msg = '无效参数' 255 | await bot.send(ev, msg) 256 | 257 | 258 | @sv.on_rex(r'^[色涩瑟][图圖]$|^[来來发發给給]((?P\d+)|(?:.*))[张張个個幅点點份丶](?P.*?)[色涩瑟][图圖]$') 259 | async def send_search_setu(bot, ev): 260 | uid = ev['user_id'] 261 | gid = ev['group_id'] 262 | num = ev['match'].group('num') 263 | if num: 264 | try: 265 | num = int(num) 266 | max_num = int(get_config('base', 'max_pic_once_send')) 267 | if num > max_num: 268 | await bot.send(ev, f'太贪心辣,一次只能要{max_num}份涩图哦~') 269 | num = max_num 270 | else: 271 | pass 272 | except: 273 | num = 1 274 | else: 275 | num = 1 276 | result, msg = check_lmt(uid, num, gid) 277 | if result != 0: 278 | await bot.send(ev, msg) 279 | return 280 | keyword = ev['match'].group('keyword') 281 | result_list = [] 282 | msg_list = [] 283 | if not keyword: 284 | for _ in range(num): 285 | msg = await get_setu(gid) 286 | if msg == None: 287 | await bot.send(ev, '获取图片失败了,可能有以下原因:\n没有启用任何一个setu模块\n网络不佳/配置有误\n初次使用,请使用"setu 缓存"来缓存图片后再发送') 288 | return 289 | msg_list.append(msg) 290 | result_list = await send_msg(msg_list, ev) 291 | else: 292 | keyword = keyword.strip() 293 | await bot.send(ev, '搜索中...') 294 | msg_list = await search_setu(gid, keyword, num) 295 | if len(msg_list) == 0: 296 | await bot.send(ev, '没~找~到~哦,随机赠送你一份setu吧~\n可能原因:1.没有使用标准或正式角色名称\n2.兄啊,你的XP怎么这么怪啊.jpg\n3.网络不佳/搜索额度超限') 297 | for _ in range(num): 298 | msg = await get_setu(gid) 299 | if msg == None: 300 | await bot.send(ev, '获取图片失败了,可能有以下原因:\n没有启用任何一个setu模块\n网络不佳/配置有误\n初次使用,请使用"setu 缓存"来缓存图片后再发送') 301 | return 302 | msg_list.append(msg) 303 | result_list = await send_msg(msg_list, ev) 304 | else: 305 | result_list = await send_msg(msg_list, ev) 306 | tlmt.increase(uid, len(result_list)) 307 | second = get_group_config(gid, "withdraw") 308 | if second and second > 0: 309 | await asyncio.sleep(second) 310 | for result in result_list: 311 | try: 312 | await bot.delete_msg(self_id=ev['self_id'], message_id=result['message_id']) 313 | except: 314 | traceback.print_exc() 315 | hoshino.logger.error('[ERROR]撤回失败') 316 | await asyncio.sleep(1) 317 | 318 | 319 | @sv.on_rex(r'^[本每]日[涩色瑟]图排行榜\D*(\d*)') 320 | async def send_ranking(bot, ev): 321 | gid = ev['group_id'] 322 | page = ev['match'].group(1) 323 | if page and page.isdigit(): 324 | page = int(page) 325 | page -= 1 326 | else: 327 | page = 0 328 | if page < 0: 329 | page = 0 330 | msg = await get_ranking(gid, page) 331 | if msg == None: 332 | msg = '模块未启用' 333 | await send_msg(msg, ev) 334 | 335 | 336 | @sv.on_prefix(('看涩图', '看色图', '看瑟图')) 337 | async def send_ranking_setu(bot, ev): 338 | uid = ev['user_id'] 339 | gid = ev['group_id'] 340 | start = 0 341 | end = 0 342 | args = ev.message.extract_plain_text().split() 343 | if len(args) > 0 and args[0].isdigit(): 344 | start = int(args[0]) 345 | start -= 1 346 | if start < 0: 347 | start = 0 348 | end = start + 1 349 | if len(args) > 1 and args[1].isdigit(): 350 | end = int(args[1]) 351 | result, msg = check_lmt(uid, end - start, gid) 352 | if result != 0: 353 | await bot.send(ev, msg) 354 | return 355 | msg_list = [] 356 | for i in range(start, end): 357 | msg = await get_ranking_setu(gid, i) 358 | if msg == None: 359 | await bot.send(ev, '模块未启用') 360 | return 361 | msg_list.append(msg) 362 | result_list = await send_msg(msg_list, ev) 363 | tlmt.increase(uid, len(result_list)) 364 | second = get_group_config(gid, "withdraw") 365 | if second and second > 0: 366 | if not get_config('base', 'enable_forward_msg'): 367 | await asyncio.sleep(second) 368 | for result in result_list: 369 | try: 370 | await bot.delete_msg(self_id=ev['self_id'], message_id=result['message_id']) 371 | except: 372 | traceback.print_exc() 373 | hoshino.logger.error('[ERROR]撤回失败') 374 | await asyncio.sleep(1) 375 | 376 | 377 | @sv.on_prefix('提取图片') 378 | async def get_spec_setu(bot, ev): 379 | args = ev.message.extract_plain_text().split() 380 | try: 381 | args = args[0] 382 | except: 383 | await bot.send(ev, '请在命令之后提供p站id哦~') 384 | return 385 | args = str(args) 386 | if len(args) == 8: 387 | msg = get_spec_image(args) 388 | if not msg: 389 | await bot.send(ev, f'没有在本地找到这张图片/不支持r18图片的提取\n原图地址:https://pixiv.lancercmd.cc/{args}') 390 | else: 391 | await bot.send(ev, msg) 392 | else: 393 | await bot.send(ev, 'p站id无效,应为8位数字id哦~') 394 | 395 | 396 | @sv.scheduled_job('interval', minutes=10) 397 | async def fetch_setu_process(): 398 | await fetch_process() 399 | 400 | 401 | # @sv.on_fullmatch('test') 402 | @scheduler.scheduled_job('cron', hour=4, minute=40) 403 | async def set_ban_list(): 404 | ban_list = [] 405 | group_info = await get_group_info(info_type='member_count') 406 | for group in group_info: 407 | group_info[group] = int(group_info[group]) 408 | if group_info[group] >= int(get_config('base', 'ban_if_group_num_over')): 409 | ban_list.append(group) 410 | else: 411 | pass 412 | set_group_list(ban_list, 1, 0) 413 | -------------------------------------------------------------------------------- /acggov.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import datetime 3 | import io 4 | import json 5 | import os 6 | import random 7 | import sys 8 | import traceback 9 | 10 | import httpx 11 | from PIL import Image 12 | 13 | import hoshino 14 | from hoshino import R 15 | from .config import get_config 16 | 17 | 18 | ranking_list = {} 19 | 20 | ranking_date = None 21 | 22 | acggov_headers = { 23 | 'token': get_config('acggov', 'apikey'), 24 | 'referer': 'https://www.acgmx.com/', 25 | 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36' 26 | } 27 | 28 | native_info = {} 29 | 30 | 31 | def load_native_info(sub_dir): 32 | info = {} 33 | path = f'setu_mix/' + sub_dir 34 | res = R.img(path) 35 | if not os.path.exists(res.path): 36 | return info 37 | fnlist = os.listdir(res.path) 38 | 39 | for fn in fnlist: 40 | s = fn.split('.') 41 | if len(s) != 2 or s[1] != 'json' or not s[0].isdigit(): 42 | continue 43 | uid = int(s[0]) 44 | try: 45 | with open(res.path + '/' + fn, encoding='utf8') as f: 46 | d = json.load(f) 47 | d['tags'].append(d['title']) 48 | d['tags'].append(d['author']) 49 | info[uid] = ','.join(d['tags']) 50 | except: 51 | pass 52 | hoshino.logger.info(f'[INFO]read{len(info)}setu from{sub_dir}') 53 | return info 54 | 55 | 56 | def generate_image_struct(): 57 | return { 58 | 'id': 0, 59 | 'url': '', 60 | 'title': '', 61 | 'author': '', 62 | 'tags': [], 63 | 'data': None, 64 | 'native': False, 65 | } 66 | 67 | 68 | # 读取排行榜 69 | async def query_ranking(date: str, page: int) -> dict: 70 | if date not in ranking_list: 71 | ranking_list[date] = {} 72 | if page in ranking_list[date]: 73 | return ranking_list[date][page] 74 | url = f'https://api.acgmx.com/public/ranking' 75 | params = { 76 | 'ranking_type': 'illust', 77 | 'mode': get_config('acggov', 'ranking_mode'), 78 | 'date': date, 79 | 'per_page': get_config('acggov', 'per_page'), 80 | 'page': page + 1, 81 | } 82 | data = {} 83 | try: 84 | async with httpx.AsyncClient(headers=acggov_headers) as session: 85 | async with session.get(url, params=params, proxy=get_config('acggov', 'acggov_proxy'), ssl=False) as resp: 86 | data = await resp.json(content_type='application/json') 87 | ranking_list[date][page] = data 88 | except: 89 | traceback.print_exc() 90 | return data 91 | 92 | 93 | # 获取随机色图 94 | async def query_setu(): 95 | data = {} 96 | image = generate_image_struct() 97 | try: 98 | async with httpx.AsyncClient(headers=acggov_headers) as session: 99 | async with session.get('https://api.acgmx.com/public/setu', 100 | proxy=get_config('acggov', 'acggov_proxy'), ssl=False) as resp: 101 | data = await resp.json(content_type='application/json') 102 | except Exception: 103 | traceback.print_exc() 104 | image['title'] = '无法访问api' 105 | return image 106 | if 'data' not in data: 107 | image['title'] = 'api返回数据无效' 108 | return image 109 | data = data['data'] 110 | 111 | image['id'] = data['illust'] 112 | image['title'] = data['title'] 113 | image['author'] = data['user']['name'] 114 | for tag in data['tags']: 115 | image['tags'].append(tag['name']) 116 | if get_config('acggov', 'use_thumb'): 117 | image['url'] = data['large'] 118 | else: 119 | num = random.randint(0, int(data['pageCount']) - 1) 120 | image['url'] = data['originals'][num]['url'] 121 | return image 122 | 123 | 124 | # 获取搜索结果 125 | async def query_search(keyword): 126 | data = {} 127 | image_list = [] 128 | image = generate_image_struct() 129 | url = f'https://api.acgmx.com/public/search' 130 | params = { 131 | 'q': keyword, 132 | 'offset': 0, 133 | } 134 | try: 135 | async with httpx.AsyncClient(headers=acggov_headers) as session: 136 | async with session.get(url, params=params, proxy=get_config('acggov', 'acggov_proxy'), ssl=False) as resp: 137 | data = await resp.json(content_type='application/json') 138 | except Exception: 139 | traceback.print_exc() 140 | image['title'] = '无法访问api' 141 | return image_list 142 | if 'illusts' not in data: 143 | image['title'] = 'api返回数据无效' 144 | return image_list 145 | 146 | for item in data['illusts']: 147 | image = generate_image_struct() 148 | image['id'] = item['id'] 149 | image['title'] = item['title'] 150 | image['author'] = item['user']['name'] 151 | for tag in item['tags']: 152 | image['tags'].append(tag['name']) 153 | try: 154 | if get_config('acggov', 'use_thumb'): 155 | image['url'] = item['image_urls']['large'] 156 | else: 157 | if item['page_count'] == 1: 158 | image['url'] = item['meta_single_page']['original_image_url'] 159 | else: 160 | num = random.randint(0, item['page_count'] - 1) 161 | image['url'] = item['meta_pages'][num]['image_urls']['original'] 162 | except: 163 | pass 164 | if image['url']: 165 | image_list.append(image) 166 | hoshino.logger.info(f"[INFO]搜索结果数量{len(data['illusts'])}") 167 | return image_list 168 | 169 | 170 | # 获取排行榜图片 171 | async def query_ranking_setu(number: int) -> dict: 172 | image = generate_image_struct() 173 | 174 | page = number // get_config('acggov', 'per_page') 175 | number = number % get_config('acggov', 'per_page') 176 | date = (datetime.datetime.now() + 177 | datetime.timedelta(days=-2)).strftime("%Y-%m-%d") 178 | data = await query_ranking(date, page) 179 | if not 'response' in data: 180 | image['title'] = '排行榜数据获取失败' 181 | return image 182 | 183 | illust = data['illusts'][number]['id'] 184 | image['title'] = data['illusts'][number]['title'] 185 | image['author'] = data['illusts'][number]['user']['name'] 186 | for tag in data['illusts'][number]['tags']: 187 | image['tags'].append(tag) 188 | 189 | if get_config('acggov', 'use_thumb'): 190 | image['url'] = data['illusts'][number]['image_urls']['large'] 191 | else: 192 | data = {} 193 | url = 'https://api.acgmx.com/illusts/detail' 194 | params = { 195 | 'illustId': illust, 196 | 'reduction': 'true', 197 | } 198 | try: 199 | async with httpx.AsyncClient(headers=acggov_headers) as session: 200 | async with session.get(url, params=params, proxy=get_config('acggov', 'acggov_proxy'), ssl=False) as resp: 201 | data = await resp.json(content_type='application/json') 202 | except Exception as _: 203 | traceback.print_exc() 204 | image['title'] = 'detail获取失败' 205 | return image 206 | if 'illusts' not in data: 207 | image['title'] = 'detail数据异常' 208 | return image 209 | data = data['illusts'] 210 | page_count = data[number]['page_count'] 211 | if page_count == 1: 212 | image['url'] = data[number]['meta_single_page']['original_image_url'] 213 | else: 214 | meta_pages = data[number]['meta_pages'] 215 | num = random.randint(0, len(meta_pages) - 1) 216 | image['url'] = meta_pages[num]['image_urls']['original'] 217 | 218 | image['id'] = illust 219 | return image 220 | 221 | 222 | async def download_acggov_image(url: str): 223 | hoshino.logger.info(f'[INFO]acggov downloading image {url}') 224 | try: 225 | async with httpx.AsyncClient(headers=acggov_headers) as session: 226 | async with session.get(url, proxy=get_config('acggov', 'acggov_proxy'), ssl=False) as resp: 227 | data = await resp.read() 228 | # 转jpg 229 | byte_stream = io.BytesIO(data) 230 | roiImg = Image.open(byte_stream) 231 | if roiImg.mode != 'RGB': 232 | roiImg = roiImg.convert('RGB') 233 | imgByteArr = io.BytesIO() 234 | roiImg.save(imgByteArr, format='JPEG') 235 | return imgByteArr.getvalue() 236 | except Exception as e: 237 | hoshino.logger.error( 238 | '[ERROR]download image {} failed,error {}'.format(url, e)) 239 | # traceback.print_exc() 240 | return None 241 | 242 | 243 | async def download_pixiv_image(url: str, id): 244 | hoshino.logger.info(f'[INFO]acggov downloading pixiv image{url}') 245 | headers = { 246 | 'referer': f'https://www.pixiv.net/member_illust.php?mode=medium&illust_id={id}' 247 | } 248 | try: 249 | async with httpx.AsyncClient(headers=headers) as session: 250 | async with session.get(url, proxy=get_config('acggov', 'pixiv_proxy'), ssl=False) as resp: 251 | data = await resp.read() 252 | # 转jpg 253 | byte_stream = io.BytesIO(data) 254 | roiImg = Image.open(byte_stream) 255 | if roiImg.mode != 'RGB': 256 | roiImg = roiImg.convert('RGB') 257 | imgByteArr = io.BytesIO() 258 | roiImg.save(imgByteArr, format='JPEG') 259 | return imgByteArr.getvalue() 260 | except Exception as e: 261 | hoshino.logger.error( 262 | '[ERROR]download image {} failed,error {}'.format(url, e)) 263 | # traceback.print_exc() 264 | return None 265 | 266 | 267 | def save_image(image, mode='acggov'): 268 | path = f'setu_mix/{mode}/{image["id"]}' 269 | 270 | res = R.img(path + '.jpg') 271 | with open(res.path, 'wb') as f: 272 | f.write(image['data']) 273 | 274 | res = R.img(path + '.json') 275 | info = { 276 | 'title': image['title'], 277 | 'author': image['author'], 278 | 'url': image['url'], 279 | 'tags': image['tags'], 280 | } 281 | with open(res.path, 'w', encoding='utf8') as f: 282 | json.dump(info, f, ensure_ascii=False, indent=2) 283 | 284 | 285 | async def get_setu_online(): 286 | image = await query_setu() 287 | # 检查本地是否存在该图片 288 | path = f'setu_mix/acggov/{image["id"]}.jpg' 289 | res = R.img(path) 290 | if os.path.exists(res.path): 291 | image['data'] = res.path 292 | image['native'] = True 293 | else: 294 | image['data'] = await download_acggov_image(image['url']) 295 | image['native'] = False 296 | if not image['data']: 297 | image['id'] = 0 298 | image['title'] = '图片下载失败' 299 | return image 300 | if get_config('acggov', 'mode') == 2: 301 | save_image(image) 302 | image['data'] = res.path 303 | return image 304 | 305 | 306 | def get_setu_native(uid=0): 307 | image = generate_image_struct() 308 | 309 | path = f'setu_mix/acggov' 310 | res = R.img(path) 311 | if not os.path.exists(res.path): 312 | return image 313 | 314 | if uid == 0: 315 | fn = random.choice(os.listdir(res.path)) 316 | if fn.split('.')[0].isdigit(): 317 | uid = int(fn.split('.')[0]) 318 | 319 | if not uid: 320 | return image 321 | 322 | image['id'] = int(uid) 323 | image['native'] = True 324 | 325 | path = f'setu_mix/acggov/{uid}' 326 | res = R.img(path) 327 | try: 328 | image['data'] = res.path + '.jpg' 329 | with open(res.path + '.json', encoding='utf8') as f: 330 | d = json.load(f) 331 | for k, v in d.items(): 332 | image[k] = v 333 | except: 334 | pass 335 | 336 | return image 337 | 338 | 339 | async def search_setu_online(keyword, num): 340 | image_list = await query_search(keyword) 341 | valid_list = [] 342 | while len(image_list) > 0: 343 | image = image_list.pop(random.randint(0, len(image_list) - 1)) 344 | # 检查本地是否存在该图片 345 | path = f'setu_mix/acggov/{image["id"]}.jpg' 346 | res = R.img(path) 347 | if os.path.exists(res.path): 348 | image['data'] = res.path 349 | image['native'] = True 350 | else: 351 | url = image['url'] 352 | if get_config('acggov', 'pixiv_direct'): 353 | image['data'] = await download_pixiv_image(url, image['id']) 354 | else: 355 | url = url.replace("https://i.pximg.net", "https://i.pixiv.cat") 356 | image['data'] = await download_acggov_image(url) 357 | image['native'] = False 358 | if image['data']: 359 | if get_config('acggov', 'mode') == 2: 360 | save_image(image) 361 | image['data'] = res.path 362 | if image['data']: 363 | valid_list.append(image) 364 | if len(valid_list) >= num: 365 | break 366 | return valid_list 367 | 368 | 369 | def search_setu_native(keyword, num): 370 | image = generate_image_struct() 371 | result_list = [] 372 | for k, v in native_info.items(): 373 | if v.find(keyword) >= 0: 374 | result_list.append(k) 375 | 376 | if len(result_list) > num: 377 | result_list = random.sample(result_list, num) 378 | image_list = [] 379 | for result in result_list: 380 | image = get_setu_native(result) 381 | if image['data']: 382 | image_list.append(image) 383 | return image_list 384 | 385 | 386 | async def acggov_get_setu(): 387 | if get_config('acggov', 'mode') >= 2: 388 | return get_setu_native() 389 | elif get_config('acggov', 'mode') == 1: 390 | return await get_setu_online() 391 | else: 392 | return None 393 | 394 | 395 | async def acggov_search_setu(keyword, num): 396 | if get_config('acggov', 'mode') == 1 or get_config('acggov', 'mode') == 2: 397 | return await search_setu_online(keyword, num) 398 | elif get_config('acggov', 'mode') == 3: 399 | return search_setu_native(keyword, num) 400 | else: 401 | return None 402 | 403 | 404 | # 获取排行榜 405 | async def acggov_get_ranking(page: int = 0) -> str: 406 | date = (datetime.datetime.now() + 407 | datetime.timedelta(days=-2)).strftime("%Y-%m-%d") 408 | data = await query_ranking(date, page) 409 | if not 'illusts' in data: 410 | return '数据获取失败' 411 | works = data['illusts'] 412 | pages = 10 413 | current = page + 1 414 | num = page * get_config('acggov', 'per_page') + 1 415 | msg = '' 416 | for i in works: 417 | msg += f'{num}.' + i['title'] + \ 418 | '-' + str(i['id']) + '\n' 419 | num += 1 420 | msg += f'第{current}页,共{str(pages)}页' 421 | return msg 422 | 423 | 424 | # 获取排行榜图片 425 | async def acggov_get_ranking_setu(number: int) -> dict: 426 | image = await query_ranking_setu(number) 427 | 428 | path = f'setu_mix/acggov/{image["id"]}.jpg' 429 | res = R.img(path) 430 | if os.path.exists(res.path): 431 | image['data'] = res.path 432 | image['native'] = True 433 | else: 434 | url = image['url'] 435 | if get_config('acggov', 'pixiv_direct'): 436 | image['data'] = await download_pixiv_image(url, image['id']) 437 | else: 438 | url = url.replace("https://i.pximg.net", "https://i.pixiv.cat") 439 | image['data'] = await download_acggov_image(url) 440 | image['native'] = False 441 | if not image['data']: 442 | image['id'] = 0 443 | image['title'] = '图片下载失败' 444 | elif get_config('acggov', 'mode') == 2: 445 | save_image(image) 446 | image['data'] = res.path 447 | 448 | return image 449 | 450 | 451 | async def acggov_fetch_process(): 452 | global ranking_date 453 | if get_config('acggov', 'mode') == 2: 454 | hoshino.logger.info('[INFO]fetch acggov setu') 455 | for _ in range(10): 456 | await get_setu_online() 457 | 458 | date = (datetime.datetime.now() + 459 | datetime.timedelta(days=-2)).strftime("%Y-%m-%d") 460 | if date != ranking_date: 461 | hoshino.logger.info('[INFO]fetch acggov ranking setu') 462 | for i in range(25): 463 | await acggov_get_ranking_setu(i) 464 | ranking_date = date 465 | 466 | 467 | def acggov_init(): 468 | global native_info 469 | if get_config('acggov', 'mode') == 3: 470 | native_info = load_native_info('acggov') 471 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------