Skip to content

Commit

Permalink
feat(core): support bot.logger
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Nov 11, 2023
1 parent 96674c7 commit 5d3614a
Show file tree
Hide file tree
Showing 42 changed files with 156 additions and 211 deletions.
9 changes: 3 additions & 6 deletions adapters/dingtalk/src/bot.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Bot, Context, Logger, Quester, Schema } from '@satorijs/satori'
import { Bot, Context, Quester, Schema } from '@satorijs/satori'
import { HttpServer } from './http'
import { DingtalkMessageEncoder } from './message'
import { WsClient } from './ws'
import { Internal } from './internal'

const logger = new Logger('dingtalk')

// https://open.dingtalk.com/document/orgapp/enterprise-created-chatbot
export class DingtalkBot<C extends Context = Context> extends Bot<C, DingtalkBot.Config> {
static MessageEncoder = DingtalkMessageEncoder
Expand All @@ -16,8 +14,7 @@ export class DingtalkBot<C extends Context = Context> extends Bot<C, DingtalkBot
private refreshTokenTimer: NodeJS.Timeout

constructor(ctx: C, config: DingtalkBot.Config) {
super(ctx, config)
this.platform = 'dingtalk'
super(ctx, config, 'dingtalk')
this.selfId = config.appkey
this.http = ctx.http.extend(config.api)
this.oldHttp = ctx.http.extend(config.oldApi)
Expand Down Expand Up @@ -50,7 +47,7 @@ export class DingtalkBot<C extends Context = Context> extends Bot<C, DingtalkBot
appKey: this.config.appkey,
appSecret: this.config.secret,
})
logger.debug('gettoken result: %o', data)
this.logger.debug('gettoken result: %o', data)
this.token = data.accessToken
// https://open.dingtalk.com/document/orgapp/authorization-overview
this.http = this.http.extend({
Expand Down
7 changes: 6 additions & 1 deletion adapters/dingtalk/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import { decodeMessage } from './utils'
export class HttpServer<C extends Context = Context> extends Adapter<C, DingtalkBot<C>> {
static inject = ['router']

logger = new Logger('dingtalk')
private logger: Logger

constructor(ctx: C, bot: DingtalkBot<C>) {
super(ctx)
this.logger = ctx.logger('dingtalk')
}

async connect(bot: DingtalkBot<C>) {
await bot.refreshToken()
Expand Down
6 changes: 3 additions & 3 deletions adapters/dingtalk/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
this.bot.online()
this.socket.addEventListener('message', async ({ data }) => {
const parsed = JSON.parse(data.toString())
this.ctx.logger('dingtalk').debug(parsed)
this.bot.logger.debug(parsed)
if (parsed.type === 'SYSTEM') {
if (parsed.headers.topic === 'ping') {
this.socket.send(JSON.stringify({
Expand All @@ -37,10 +37,10 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
}))
}
} else if (parsed.type === 'CALLBACK') {
this.ctx.logger('dingtalk').debug(JSON.parse(parsed.data))
this.bot.logger.debug(JSON.parse(parsed.data))
const session = await decodeMessage(this.bot, JSON.parse(parsed.data))
if (session) this.bot.dispatch(session)
this.ctx.logger('dingtalk').debug(session)
this.bot.logger.debug(session)
}
})
}
Expand Down
11 changes: 4 additions & 7 deletions adapters/discord/src/bot.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Bot, Context, Fragment, h, Logger, Quester, Schema, Universal } from '@satorijs/satori'
import { Bot, Context, Fragment, h, Quester, Schema, Universal } from '@satorijs/satori'
import * as Discord from './utils'
import { DiscordMessageEncoder } from './message'
import { Internal, Webhook } from './types'
Expand All @@ -7,8 +7,6 @@ import { WsClient } from './ws'
// @ts-ignore
import { version } from '../package.json'

const logger = new Logger('discord')

export class DiscordBot<C extends Context = Context> extends Bot<C, DiscordBot.Config> {
static MessageEncoder = DiscordMessageEncoder

Expand All @@ -19,8 +17,7 @@ export class DiscordBot<C extends Context = Context> extends Bot<C, DiscordBot.C
public commands: Universal.Command[] = []

constructor(ctx: C, config: DiscordBot.Config) {
super(ctx, config)
this.platform = 'discord'
super(ctx, config, 'discord')
this.http = ctx.http.extend({
...config,
headers: {
Expand All @@ -29,7 +26,7 @@ export class DiscordBot<C extends Context = Context> extends Bot<C, DiscordBot.C
...config.headers,
},
})
this.internal = new Internal(this.http)
this.internal = new Internal(this)
ctx.plugin(WsClient, this)
}

Expand Down Expand Up @@ -195,7 +192,7 @@ export class DiscordBot<C extends Context = Context> extends Bot<C, DiscordBot.C
this.commands = commands
const updates = commands.map(Discord.encodeCommand)
if (updates.length) {
logger.debug('update %d command(s)', updates.length)
this.logger.debug('update %d command(s)', updates.length)
await this.internal.bulkOverwriteGlobalApplicationCommands(this.selfId, updates)
}
}
Expand Down
6 changes: 2 additions & 4 deletions adapters/discord/src/message.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Context, Dict, h, Logger, MessageEncoder, Quester, Schema, Universal } from '@satorijs/satori'
import { Context, Dict, h, MessageEncoder, Quester, Schema, Universal } from '@satorijs/satori'
import FormData from 'form-data'
import { DiscordBot } from './bot'
import { ActionRow, Button, ButtonStyles, Channel, ComponentType, Message } from './types'
import { decodeMessage, sanitize } from './utils'

type RenderMode = 'default' | 'figure'

const logger = new Logger('discord')

class State {
author: Partial<Universal.User> = {}
quote: Partial<Universal.Message> = {}
Expand Down Expand Up @@ -75,7 +73,7 @@ export class DiscordMessageEncoder<C extends Context = Context> extends MessageE
} catch (e) {
if (Quester.isAxiosError(e) && e.response) {
if (e.response.data?.code === 10015) {
logger.debug('webhook has been deleted, recreating..., %o', e.response.data)
this.bot.logger.debug('webhook has been deleted, recreating..., %o', e.response.data)
if (!this.bot.webhookLock[this.channelId]) this.bot.webhooks[this.channelId] = null
await this.ensureWebhook()
return this.post(data, headers)
Expand Down
11 changes: 5 additions & 6 deletions adapters/discord/src/types/internal.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Dict, Logger, makeArray, Quester } from '@satorijs/satori'

const logger = new Logger('discord')
import { Dict, makeArray, Quester } from '@satorijs/satori'
import { DiscordBot } from '../bot'

export class Internal {
constructor(private http: Quester) {}
constructor(private bot: DiscordBot) {}

static define(routes: Dict<Partial<Record<Quester.Method, string | string[]>>>) {
for (const path in routes) {
Expand All @@ -30,8 +29,8 @@ export class Internal {
throw new Error(`too many arguments for ${path}, received ${raw}`)
}
try {
logger.debug(`${method} ${url}`, config)
return await this.http(method, url, config)
this.bot.logger.debug(`${method} ${url}`, config)
return await this.bot.http(method, url, config)
} catch (error) {
if (!Quester.isAxiosError(error) || !error.response) throw error
throw new Error(`[${error.response.status}] ${JSON.stringify(error.response.data)}`)
Expand Down
18 changes: 8 additions & 10 deletions adapters/discord/src/ws.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Adapter, Context, Logger, Schema } from '@satorijs/satori'
import { Adapter, Context, Schema } from '@satorijs/satori'
import { Gateway } from './types'
import { adaptSession, decodeUser } from './utils'
import { DiscordBot } from './bot'

const logger = new Logger('discord')

export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, DiscordBot<C>> {
_d = 0
_ping: NodeJS.Timeout
Expand All @@ -20,7 +18,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
}

heartbeat() {
logger.debug(`heartbeat d ${this._d}`)
this.bot.logger.debug(`heartbeat d ${this._d}`)
this.socket.send(JSON.stringify({
op: Gateway.Opcode.HEARTBEAT,
d: this._d,
Expand All @@ -33,9 +31,9 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
try {
parsed = JSON.parse(data.toString())
} catch (error) {
return logger.warn('cannot parse message', data)
return this.bot.logger.warn('cannot parse message', data)
}
logger.debug(parsed)
this.bot.logger.debug(parsed)
if (parsed.s) {
this._d = parsed.s
}
Expand All @@ -44,7 +42,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
if (parsed.op === Gateway.Opcode.HELLO) {
this._ping = setInterval(() => this.heartbeat(), parsed.d.heartbeat_interval)
if (this._sessionId) {
logger.debug('resuming')
this.bot.logger.debug('resuming')
this.socket.send(JSON.stringify({
op: Gateway.Opcode.RESUME,
d: {
Expand All @@ -69,7 +67,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
if (parsed.op === Gateway.Opcode.INVALID_SESSION) {
if (parsed.d) return
this._sessionId = ''
logger.warn('offline: invalid session')
this.bot.logger.warn('offline: invalid session')
this.socket?.close()
}

Expand All @@ -83,7 +81,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
this._sessionId = parsed.d.session_id
this._resumeUrl = parsed.d.resume_gateway_url
this.bot.user = decodeUser(parsed.d.user)
logger.debug('session_id ' + this._sessionId)
this.bot.logger.debug('session_id ' + this._sessionId)
return this.bot.online()
}
if (parsed.t === 'RESUMED') {
Expand All @@ -94,7 +92,7 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, D
}

if (parsed.op === Gateway.Opcode.RECONNECT) {
logger.warn('offline: discord request reconnect')
this.bot.logger.warn('offline: discord request reconnect')
this.socket?.close()
}
})
Expand Down
3 changes: 1 addition & 2 deletions adapters/kook/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ export class KookBot<C extends Context = Context, T extends KookBot.Config = Koo
internal: Kook.Internal

constructor(ctx: C, config: T) {
super(ctx, config)
this.platform = 'kook'
super(ctx, config, 'kook')
this.http = ctx.http.extend({
headers: {
'Authorization': `Bot ${config.token}`,
Expand Down
9 changes: 5 additions & 4 deletions adapters/kook/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ import {} from '@satorijs/router'
import { KookBot } from './bot'
import { adaptSession } from './utils'

const logger = new Logger('kook')

export class HttpServer<C extends Context = Context> extends Adapter<C, KookBot<C, KookBot.BaseConfig & HttpServer.Config>> {
static inject = ['router']

private logger: Logger

constructor(ctx: C, bot: KookBot<C>) {
super()
super(ctx)
this.logger = ctx.logger('kook')
let { path } = bot.config as HttpServer.Config
path = sanitize(path)
ctx.router.post(path, async (ctx) => {
const { body } = ctx.request
logger.debug('receive %o', body)
this.logger.debug('receive %o', body)

const { challenge } = body.d
ctx.status = 200
Expand Down
8 changes: 3 additions & 5 deletions adapters/kook/src/ws.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Adapter, Context, Logger, Schema, Time, Universal } from '@satorijs/satori'
import { Adapter, Context, Schema, Time, Universal } from '@satorijs/satori'
import { KookBot } from './bot'
import { adaptSession } from './utils'
import { Payload, Signal } from './types'

const logger = new Logger('kook')

const heartbeatIntervals = [6, 2, 4]

export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, KookBot<C, KookBot.BaseConfig & WsClient.Config>> {
Expand Down Expand Up @@ -44,10 +42,10 @@ export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, K
try {
parsed = JSON.parse(data.toString())
} catch (error) {
return logger.warn('cannot parse message', data)
return this.bot.logger.warn('cannot parse message', data)
}

logger.debug('[receive] %o', parsed)
this.bot.logger.debug('[receive] %o', parsed)
if (parsed.s === Signal.event) {
this._sn = Math.max(this._sn, parsed.sn)
const session = await adaptSession(this.bot, parsed.d)
Expand Down
15 changes: 5 additions & 10 deletions adapters/lark/src/bot.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Bot, Context, h, Logger, Quester, Schema } from '@satorijs/satori'
import { Bot, Context, h, Quester, Schema } from '@satorijs/satori'

import { HttpServer } from './http'
import { LarkMessageEncoder } from './message'
import { Internal } from './types'
import * as Utils from './utils'

const logger = new Logger('lark')

export class LarkBot<C extends Context = Context> extends Bot<C, LarkBot.Config> {
static inject = ['router']
static MessageEncoder = LarkMessageEncoder
Expand All @@ -18,25 +16,22 @@ export class LarkBot<C extends Context = Context> extends Bot<C, LarkBot.Config>
internal: Internal

constructor(ctx: C, config: LarkBot.Config) {
super(ctx, config)
super(ctx, config, 'lark')

// lark bot needs config.selfUrl to be set as it should be serve on a public url
if (!config.selfUrl && !ctx.router.config.selfUrl) {
logger.warn('selfUrl is not set, some features may not work')
this.logger.warn('selfUrl is not set, some features may not work')
}

this.platform = 'lark'
this.selfId = config.appId

this.http = ctx.http.extend({
endpoint: config.endpoint,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
})
this.assetsQuester = ctx.http

this.internal = new Internal(this.http)
this.internal = new Internal(this)

ctx.plugin(HttpServer, this)
}
Expand All @@ -51,7 +46,7 @@ export class LarkBot<C extends Context = Context> extends Bot<C, LarkBot.Config>
app_id: this.config.appId,
app_secret: this.config.appSecret,
})
logger.debug('refreshed token %s', token)
this.logger.debug('refreshed token %s', token)
this.token = token
// Token would be expired in 2 hours, refresh it every 1 hour
// see https://open.larksuite.com/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
Expand Down
14 changes: 9 additions & 5 deletions adapters/lark/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ import { FeishuBot } from './bot'
import { AllEvents } from './types'
import { adaptSession, Cipher } from './utils'

const logger = new Logger('lark')

export class HttpServer<C extends Context = Context> extends Adapter<C, FeishuBot<C>> {
static inject = ['router']

private logger: Logger
private ciphers: Record<string, Cipher> = {}

constructor(ctx: C, bot: FeishuBot<C>) {
super(ctx)
this.logger = ctx.logger('lark')
}

fork(ctx: C, bot: FeishuBot<C>) {
super.fork(ctx, bot)

Expand Down Expand Up @@ -66,7 +70,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, FeishuBo
}

// dispatch message
logger.debug('received decryped event: %o', body)
bot.logger.debug('received decryped event: %o', body)
this.dispatchSession(body)

// Lark requires 200 OK response to make sure event is received
Expand Down Expand Up @@ -114,11 +118,11 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, FeishuBo
return JSON.parse(cipher.decrypt(body.encrypt))
} catch {}
}
logger.warn('failed to decrypt message: %o', body)
this.logger.warn('failed to decrypt message: %o', body)
}

if (typeof body.encrypt === 'string' && !ciphers.length) {
logger.warn('encryptKey is not set, but received encrypted message: %o', body)
this.logger.warn('encryptKey is not set, but received encrypted message: %o', body)
}

return body
Expand Down
Loading

0 comments on commit 5d3614a

Please sign in to comment.