Skip to content

Commit

Permalink
feat: add gelbooru apikey support
Browse files Browse the repository at this point in the history
  • Loading branch information
MaikoTan committed Mar 10, 2024
1 parent 5234ef1 commit 3c091e2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
16 changes: 16 additions & 0 deletions docs/zh-CN/plugins/gelbooru.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,19 @@
- 默认值:`https://gelbooru.com/index.php`

Gelbooru 的 API 地址。

#### keyPairs

- 类型:`string[]`
- 默认值:`[]`

Gelbooru 的登录凭据。如该项为空,则使用匿名登录。

由于 Gelbooru 的 API 限制,匿名用户极易触发防火墙限制(这表现为请求时无法获取图片,并返回 403 错误码)。因此推荐设置至少一个登录凭据用于检索图片,当登录凭据设置为多个时,将会针对每个凭据的搜索次数进行平均分配。

## 获取与设置登录凭据

1. 访问 [Gelbooru](https://gelbooru.com) 并登录。如果你还没有账号,你需要先注册一个账号。
1. 访问 [个人页面](https://gelbooru.com/index.php?page=account&s=options) 并翻阅到页面底部找到 `API Access Credentials` 字样,复制其右侧的文本框的内容。
1. 在 Koishi 端的 `kayPairs` 配置项中添加项目,并粘贴刚刚复制的内容。
1. 保存配置。
15 changes: 14 additions & 1 deletion packages/gelbooru/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ class GelbooruImageSource extends ImageSource<GelbooruImageSource.Config> {
super(ctx, config)
}

get keyPair() {
if (!this.config.keyPairs.length) return
return this.config.keyPairs[Math.floor(Math.random() * this.config.keyPairs.length)]
}

async get(query: ImageSource.Query): Promise<ImageSource.Result[]> {
// API docs: https://gelbooru.com/index.php?page=help&topic=dapi
const params = {
Expand All @@ -20,7 +25,13 @@ class GelbooruImageSource extends ImageSource<GelbooruImageSource.Config> {
json: 1,
limit: query.count
}
const url = trimSlash(this.config.endpoint) + '?' + Object.entries(params).map(([key, value]) => `${key}=${value}`).join('&')
let url = trimSlash(this.config.endpoint) + '?' + Object.entries(params).map(([key, value]) => `${key}=${value}`).join('&')

const keyPair = this.keyPair
if (keyPair) {
// The keyPair from Gelbooru is already url-encoded.
url += keyPair
}

const data = await this.http.get<Gelbooru.Response>(url)

Expand All @@ -43,12 +54,14 @@ class GelbooruImageSource extends ImageSource<GelbooruImageSource.Config> {
namespace GelbooruImageSource {
export interface Config extends ImageSource.Config {
endpoint: string
keyPairs: string[]
}

export const Config: Schema<Config> = Schema.intersect([
ImageSource.createSchema({ label: 'gelbooru' }),
Schema.object({
endpoint: Schema.string().description('Gelbooru 的 URL。').default('https://gelbooru.com/index.php'),
keyPairs: Schema.array(Schema.string()).description('Gelbooru 的登录凭据。').default([]),
}).description('搜索设置'),
])
}
Expand Down

0 comments on commit 3c091e2

Please sign in to comment.