Skip to content

weixin-ts / bot/src / WeixinBot

Class: WeixinBot

Defined in: bot/src/bot.ts:71

High-level WeChat Bot client with automatic long-polling and event-driven message handling.

Example

ts
const bot = new WeixinBot({ token: 'YOUR_TOKEN' })

bot.on('message', (msg) => {
  // Handle incoming message
  const text = msg.item_list?.find(i => i.type === 1)?.text_item?.text
  if (text) {
    bot.sendText({ to: msg.from_user_id!, text: `Echo: ${text}` })
  }
})

bot.on('error', console.error)
bot.start()

Extends

Constructors

Constructor

new WeixinBot(options?): WeixinBot

Defined in: bot/src/bot.ts:86

Parameters

options?

WeixinBotOptions

Returns

WeixinBot

Overrides

TypedEventEmitter.constructor

Accessors

baseUrl

Get Signature

get baseUrl(): string

Defined in: bot/src/bot.ts:100

The API base URL being used

Returns

string


cdnBaseUrl

Get Signature

get cdnBaseUrl(): string

Defined in: bot/src/bot.ts:105

The CDN base URL being used

Returns

string


isLoggedIn

Get Signature

get isLoggedIn(): boolean

Defined in: bot/src/bot.ts:236

Check if the bot has a valid token (from constructor, login, or session).

Returns

boolean


isPolling

Get Signature

get isPolling(): boolean

Defined in: bot/src/bot.ts:95

Whether the bot is currently polling for messages

Returns

boolean

Methods

emit()

emit<K>(event, ...args): void

Defined in: bot/src/events.ts:91

Emit an event, calling all registered listeners with the provided arguments.

Type Parameters

K

K extends "message" | "error" | "connected" | "disconnected" | "session:loaded" | "session:expired"

Parameters

event

K

The event name to emit

args

...BotEventMap[K] extends any[] ? any[any] : any[]

Arguments to pass to the listeners

Returns

void

Inherited from

TypedEventEmitter.emit


getConfigForUser()

getConfigForUser(userId, contextToken?): Promise<GetConfigResp>

Defined in: bot/src/bot.ts:446

Fetch bot configuration for a specific user. Useful for getting the typing ticket.

Parameters

userId

string

The iLink user ID

contextToken?

string

Optional context token

Returns

Promise<GetConfigResp>


getContextToken()

getContextToken(userId): string | undefined

Defined in: bot/src/bot.ts:480

Get the cached context token for a user. Context tokens are automatically cached from incoming messages.

Parameters

userId

string

Returns

string | undefined


getUpdates()

getUpdates(getUpdatesBuf?): Promise<WeixinMessage[]>

Defined in: bot/src/bot.ts:464

Manually call getUpdates for custom polling logic. Most users should use start() instead for automatic polling.

Parameters

getUpdatesBuf?

string

The context buffer from the previous response

Returns

Promise<WeixinMessage[]>

Array of new messages


login()

login(callbacks?): Promise<LoginResult>

Defined in: bot/src/bot.ts:174

Login via QR code scanning.

This is the simplest way to authenticate. If session is configured, the token is automatically persisted for next time.

Parameters

callbacks?

LoginCallbacks

Callbacks for QR display and status updates

Returns

Promise<LoginResult>

Login result with token and account info

Example

ts
const bot = new WeixinBot({ session: '.weixin-bot.session.json' })

await bot.login({
  onQrCode: (url) => console.log('Scan:', url),
  onScanned: () => console.log('Confirm in WeChat...'),
})

bot.start()

off()

off<K>(event, handler): this

Defined in: bot/src/events.ts:59

Remove an event listener.

Type Parameters

K

K extends "message" | "error" | "connected" | "disconnected" | "session:loaded" | "session:expired"

Parameters

event

K

The event name

handler

(...args) => void

The handler to remove

Returns

this

this for chaining

Inherited from

TypedEventEmitter.off


on()

on<K>(event, handler): this

Defined in: bot/src/events.ts:42

Register an event listener.

Type Parameters

K

K extends "message" | "error" | "connected" | "disconnected" | "session:loaded" | "session:expired"

Parameters

event

K

The event name to listen for

handler

(...args) => void

The callback function

Returns

this

this for chaining

Inherited from

TypedEventEmitter.on


once()

once<K>(event, handler): this

Defined in: bot/src/events.ts:77

Register a one-time event listener. The handler is automatically removed after the first invocation.

Type Parameters

K

K extends "message" | "error" | "connected" | "disconnected" | "session:loaded" | "session:expired"

Parameters

event

K

The event name

handler

(...args) => void

The callback function (called at most once)

Returns

this

this for chaining

Inherited from

TypedEventEmitter.once


removeAllListeners()

removeAllListeners<K>(event?): this

Defined in: bot/src/events.ts:105

Remove all listeners for a specific event, or all listeners if no event is specified.

Type Parameters

K

K extends "message" | "error" | "connected" | "disconnected" | "session:loaded" | "session:expired"

Parameters

event?

K

Optional event name. If omitted, removes all listeners.

Returns

this

Inherited from

TypedEventEmitter.removeAllListeners


sendFile()

sendFile(options): Promise<string>

Defined in: bot/src/bot.ts:318

Send a file attachment. Handles CDN upload and encryption automatically.

Parameters

options

SendMediaOptions

Send media options (file as Uint8Array/ArrayBuffer, fileName recommended)

Returns

Promise<string>

The client-generated message ID

Example

ts
await bot.sendFile({ to: 'user_id', file: pdfBuffer, fileName: 'report.pdf' })

sendImage()

sendImage(options): Promise<string>

Defined in: bot/src/bot.ts:293

Send an image message. Handles CDN upload and encryption automatically.

Parameters

options

SendMediaOptions

Send media options (file as Uint8Array/ArrayBuffer)

Returns

Promise<string>

The client-generated message ID

Example

ts
const imageBuffer = await fetch('https://example.com/photo.jpg').then(r => r.arrayBuffer())
await bot.sendImage({ to: 'user_id', file: new Uint8Array(imageBuffer) })

sendText()

sendText(options): Promise<string>

Defined in: bot/src/bot.ts:251

Send a text message to a user.

Parameters

options

SendTextOptions

Send text options

Returns

Promise<string>

The client-generated message ID

Example

ts
await bot.sendText({ to: 'user_id', text: 'Hello!' })

sendTyping()

sendTyping(userId, status?): Promise<void>

Defined in: bot/src/bot.ts:411

Send a typing indicator to a user. Requires a valid typing ticket (fetched automatically via getConfig).

Parameters

userId

string

The user to show typing to

status?

2 | 1

Typing status (defaults to TYPING)

Returns

Promise<void>

Example

ts
await bot.sendTyping('user_id')
// ... do work ...
await bot.sendTyping('user_id', TypingStatus.CANCEL)

sendVideo()

sendVideo(options): Promise<string>

Defined in: bot/src/bot.ts:303

Send a video message. Handles CDN upload and encryption automatically.

Parameters

options

SendMediaOptions

Send media options (file as Uint8Array/ArrayBuffer)

Returns

Promise<string>

The client-generated message ID


start()

start(): void

Defined in: bot/src/bot.ts:117

Start long-polling for messages. Returns immediately — polling runs in the background. The bot will emit 'message' events for each incoming message and 'connected' once polling has started.

Returns

void

Throws

Error if already polling


stop()

stop(): void

Defined in: bot/src/bot.ts:148

Stop polling for messages. In-flight requests will be aborted gracefully.

Returns

void

Released under the MIT License.