@elizaos/plugin-telegram 2.0.0-alpha.4 → 2.0.0-alpha.537

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/account-auth-service.ts"],"sourcesContent":["import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Api, TelegramClient } from 'telegram';\nimport { StringSession } from 'telegram/sessions/index.js';\n\nexport type TelegramAccountAuthStatus =\n | 'idle'\n | 'waiting_for_provisioning_code'\n | 'waiting_for_telegram_code'\n | 'waiting_for_password'\n | 'configured'\n | 'connected'\n | 'error';\n\nexport interface TelegramAccountAuthAccount {\n id: string;\n username: string | null;\n firstName: string | null;\n lastName: string | null;\n phone: string | null;\n}\n\nexport interface TelegramAccountAuthSnapshot {\n status: TelegramAccountAuthStatus;\n phone: string | null;\n error: string | null;\n isCodeViaApp: boolean;\n account: TelegramAccountAuthAccount | null;\n}\n\nexport interface TelegramAccountApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nexport interface TelegramAccountConnectorConfig {\n phone: string;\n appId: string;\n appHash: string;\n deviceModel: string;\n systemVersion: string;\n enabled: true;\n}\n\nexport interface TelegramAccountAuthSessionLike {\n start(options: {\n phone: string;\n credentials: TelegramAccountApiCredentials | null;\n }): Promise<TelegramAccountAuthSnapshot>;\n submit(input: {\n provisioningCode?: string;\n telegramCode?: string;\n password?: string;\n }): Promise<TelegramAccountAuthSnapshot>;\n stop(): Promise<void>;\n getSnapshot(): TelegramAccountAuthSnapshot;\n getResolvedConnectorConfig(): TelegramAccountConnectorConfig | null;\n}\n\ntype TelegramAccountProvisioningApp = {\n api_id: number;\n api_hash: string;\n};\n\ntype PersistedTelegramAccountAuthState = {\n snapshot: TelegramAccountAuthSnapshot;\n credentials: TelegramAccountApiCredentials | null;\n connectorConfig: TelegramAccountConnectorConfig | null;\n provisioningRandomHash: string | null;\n phoneCodeHash: string | null;\n};\n\ntype TelegramAccountAuthDeps = {\n createTelegramClient?: (\n session: StringSession,\n credentials: TelegramAccountApiCredentials,\n deviceModel: string,\n systemVersion: string,\n ) => TelegramClient;\n sendProvisioningCode?: (phone: string) => Promise<string>;\n completeProvisioningLogin?: (\n phone: string,\n randomHash: string,\n code: string,\n ) => Promise<string>;\n getOrCreateProvisionedApp?: (\n stelToken: string,\n ) => Promise<TelegramAccountProvisioningApp>;\n};\n\nconst MY_TELEGRAM_URL = 'https://my.telegram.org';\nconst TELEGRAM_USER_AGENT =\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36';\nconst TELEGRAM_ACCOUNT_AUTH_STATUSES = new Set<TelegramAccountAuthStatus>([\n 'idle',\n 'waiting_for_provisioning_code',\n 'waiting_for_telegram_code',\n 'waiting_for_password',\n 'configured',\n 'connected',\n 'error',\n]);\n\nfunction resolveStateDir(): string {\n return (\n process.env.ELIZA_STATE_DIR?.trim() || path.join(os.homedir(), '.eliza')\n );\n}\n\nfunction resolveTelegramAccountSessionDir(): string {\n const sessionDir = path.join(resolveStateDir(), 'telegram-account');\n fs.mkdirSync(sessionDir, { recursive: true });\n return sessionDir;\n}\n\nexport function resolveTelegramAccountSessionFile(): string {\n return path.join(resolveTelegramAccountSessionDir(), 'session.txt');\n}\n\nfunction resolveTelegramAccountAuthStateFile(): string {\n return path.join(resolveTelegramAccountSessionDir(), 'auth-state.json');\n}\n\nexport function loadTelegramAccountSessionString(): string {\n const sessionFile = resolveTelegramAccountSessionFile();\n if (!fs.existsSync(sessionFile)) {\n return '';\n }\n return fs.readFileSync(sessionFile, 'utf8').trim();\n}\n\nexport function saveTelegramAccountSessionString(session: string): void {\n fs.writeFileSync(resolveTelegramAccountSessionFile(), session, {\n encoding: 'utf8',\n mode: 0o600,\n });\n}\n\nexport function clearTelegramAccountSession(): void {\n fs.rmSync(resolveTelegramAccountSessionFile(), { force: true });\n}\n\nexport function telegramAccountSessionExists(): boolean {\n const sessionFile = resolveTelegramAccountSessionFile();\n return fs.existsSync(sessionFile) && fs.statSync(sessionFile).size > 0;\n}\n\nfunction readTrimmedString(value: unknown): string | null {\n if (typeof value !== 'string') {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction readPersistedAccount(\n value: unknown,\n): TelegramAccountAuthAccount | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const id = readTrimmedString(record.id);\n if (!id) {\n return null;\n }\n return {\n id,\n username: readTrimmedString(record.username),\n firstName: readTrimmedString(record.firstName),\n lastName: readTrimmedString(record.lastName),\n phone: readTrimmedString(record.phone),\n };\n}\n\nfunction readPersistedSnapshot(\n value: unknown,\n): TelegramAccountAuthSnapshot | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const status = record.status;\n if (\n typeof status !== 'string' ||\n !TELEGRAM_ACCOUNT_AUTH_STATUSES.has(status as TelegramAccountAuthStatus)\n ) {\n return null;\n }\n return {\n status: status as TelegramAccountAuthStatus,\n phone: readTrimmedString(record.phone),\n error:\n typeof record.error === 'string' && record.error.trim().length > 0\n ? record.error\n : null,\n isCodeViaApp: record.isCodeViaApp === true,\n account: readPersistedAccount(record.account),\n };\n}\n\nfunction readPersistedCredentials(\n value: unknown,\n): TelegramAccountApiCredentials | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const apiIdValue = record.apiId;\n const apiId =\n typeof apiIdValue === 'number'\n ? apiIdValue\n : typeof apiIdValue === 'string' && apiIdValue.trim().length > 0\n ? Number.parseInt(apiIdValue, 10)\n : Number.NaN;\n const apiHash = readTrimmedString(record.apiHash);\n if (!Number.isInteger(apiId) || apiId <= 0 || !apiHash) {\n return null;\n }\n return { apiId, apiHash };\n}\n\nfunction readPersistedConnectorConfig(\n value: unknown,\n): TelegramAccountConnectorConfig | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const phone = readTrimmedString(record.phone);\n const appId = readTrimmedString(record.appId);\n const appHash = readTrimmedString(record.appHash);\n const deviceModel = readTrimmedString(record.deviceModel);\n const systemVersion = readTrimmedString(record.systemVersion);\n if (!phone || !appId || !appHash || !deviceModel || !systemVersion) {\n return null;\n }\n return {\n phone,\n appId,\n appHash,\n deviceModel,\n systemVersion,\n enabled: true,\n };\n}\n\nfunction loadTelegramAccountAuthState(): PersistedTelegramAccountAuthState | null {\n const authStateFile = resolveTelegramAccountAuthStateFile();\n if (!fs.existsSync(authStateFile)) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(\n fs.readFileSync(authStateFile, 'utf8'),\n ) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n const record = parsed as Record<string, unknown>;\n const snapshot = readPersistedSnapshot(record.snapshot);\n if (!snapshot) {\n return null;\n }\n return {\n snapshot,\n credentials: readPersistedCredentials(record.credentials),\n connectorConfig: readPersistedConnectorConfig(record.connectorConfig),\n provisioningRandomHash: readTrimmedString(record.provisioningRandomHash),\n phoneCodeHash: readTrimmedString(record.phoneCodeHash),\n };\n } catch {\n return null;\n }\n}\n\nfunction saveTelegramAccountAuthState(\n state: PersistedTelegramAccountAuthState,\n): void {\n fs.writeFileSync(\n resolveTelegramAccountAuthStateFile(),\n JSON.stringify(state),\n {\n encoding: 'utf8',\n mode: 0o600,\n },\n );\n}\n\nexport function clearTelegramAccountAuthState(): void {\n fs.rmSync(resolveTelegramAccountAuthStateFile(), { force: true });\n}\n\nexport function telegramAccountAuthStateExists(): boolean {\n const authStateFile = resolveTelegramAccountAuthStateFile();\n return fs.existsSync(authStateFile) && fs.statSync(authStateFile).size > 0;\n}\n\nexport function defaultTelegramAccountDeviceModel(): string {\n return 'Eliza Desktop';\n}\n\nexport function defaultTelegramAccountSystemVersion(): string {\n const platform = os.platform();\n const release = os.release();\n if (platform === 'darwin') {\n return `macOS ${release}`;\n }\n if (platform === 'win32') {\n return `Windows ${release}`;\n }\n return `${platform} ${release}`;\n}\n\nfunction mapTelegramAccount(user: Api.User): TelegramAccountAuthAccount {\n return {\n id: user.id.toString(),\n username: typeof user.username === 'string' ? user.username : null,\n firstName: typeof user.firstName === 'string' ? user.firstName : null,\n lastName: typeof user.lastName === 'string' ? user.lastName : null,\n phone: typeof user.phone === 'string' ? user.phone : null,\n };\n}\n\nfunction createTelegramClient(\n session: StringSession,\n credentials: TelegramAccountApiCredentials,\n deviceModel: string,\n systemVersion: string,\n): TelegramClient {\n return new TelegramClient(session, credentials.apiId, credentials.apiHash, {\n connectionRetries: 5,\n deviceModel,\n systemVersion,\n });\n}\n\ninterface SerializableTelegramSession {\n save(): unknown;\n}\n\nfunction isSerializableTelegramSession(\n session: unknown,\n): session is SerializableTelegramSession {\n return (\n typeof session === 'object' &&\n session !== null &&\n typeof Reflect.get(session, 'save') === 'function'\n );\n}\n\nfunction serializeSession(client: TelegramClient): string {\n if (!isSerializableTelegramSession(client.session)) {\n throw new Error('Telegram client session cannot be serialized');\n }\n const savedSession = client.session.save();\n if (typeof savedSession !== 'string') {\n throw new Error('Telegram client session did not serialize to a string');\n }\n return savedSession;\n}\n\nfunction createAjaxHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'User-Agent': TELEGRAM_USER_AGENT,\n Origin: MY_TELEGRAM_URL,\n 'X-Requested-With': 'XMLHttpRequest',\n };\n}\n\nfunction createFormHeaders(cookie?: string): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'User-Agent': TELEGRAM_USER_AGENT,\n ...(cookie ? { Cookie: cookie } : {}),\n };\n}\n\nfunction extractRandomHash(data: unknown): string | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const randomHash = (data as { random_hash?: unknown }).random_hash;\n return typeof randomHash === 'string' && randomHash.trim().length > 0\n ? randomHash.trim()\n : null;\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const withGetSetCookie = headers as Headers & {\n getSetCookie?: () => string[];\n };\n if (typeof withGetSetCookie.getSetCookie === 'function') {\n return withGetSetCookie.getSetCookie();\n }\n const single = headers.get('set-cookie');\n return single ? [single] : [];\n}\n\nfunction extractCookieValue(\n headers: Headers,\n cookieName: string,\n): string | null {\n const pattern = new RegExp(`(?:^|;\\\\s*)${cookieName}=([^;]+)`);\n for (const header of getSetCookieHeaders(headers)) {\n const match = header.match(pattern);\n if (match?.[1]) {\n return match[1];\n }\n }\n return null;\n}\n\nfunction extractProvisionedApp(html: string): TelegramAccountProvisioningApp {\n const apiIdMatch = html.match(\n /<span class=\"form-control input-xlarge uneditable-input\"[^>]*><strong>(\\d+)<\\/strong><\\/span>/,\n );\n const apiHashMatch = html.match(\n /<span class=\"form-control input-xlarge uneditable-input\"[^>]*>([a-f0-9]{32})<\\/span>/i,\n );\n if (!apiIdMatch?.[1] || !apiHashMatch?.[1]) {\n throw new Error('Failed to parse Telegram app credentials');\n }\n return {\n api_id: Number(apiIdMatch[1]),\n api_hash: apiHashMatch[1],\n };\n}\n\nfunction extractCreationHash(html: string): string | null {\n const match = html.match(/<input[^>]*name=\"hash\"[^>]*value=\"([^\"]+)\"/i);\n return match?.[1] ?? null;\n}\n\nasync function sendProvisioningCode(phone: string): Promise<string> {\n const response = await fetch(`${MY_TELEGRAM_URL}/auth/send_password`, {\n method: 'POST',\n headers: createAjaxHeaders(),\n body: new URLSearchParams({ phone }),\n signal: AbortSignal.timeout(15_000),\n });\n const text = await response.text();\n if (text.includes('Sorry, too many tries')) {\n throw new Error('Telegram provisioning is rate limited right now');\n }\n const parsed = JSON.parse(text) as unknown;\n const randomHash = extractRandomHash(parsed);\n if (!randomHash) {\n throw new Error('Telegram provisioning did not return a login token');\n }\n return randomHash;\n}\n\nasync function completeProvisioningLogin(\n phone: string,\n randomHash: string,\n code: string,\n): Promise<string> {\n const response = await fetch(`${MY_TELEGRAM_URL}/auth/login`, {\n method: 'POST',\n headers: createAjaxHeaders(),\n body: new URLSearchParams({\n phone,\n random_hash: randomHash,\n password: code,\n }),\n redirect: 'manual',\n signal: AbortSignal.timeout(15_000),\n });\n const text = await response.text();\n if (text === 'Invalid confirmation code!') {\n throw new Error('Invalid Telegram provisioning code');\n }\n if (text !== 'true') {\n throw new Error('Telegram provisioning login failed');\n }\n const stelToken = extractCookieValue(response.headers, 'stel_token');\n if (!stelToken) {\n throw new Error('Telegram provisioning did not return a session token');\n }\n return stelToken;\n}\n\nasync function getOrCreateProvisionedApp(\n stelToken: string,\n): Promise<TelegramAccountProvisioningApp> {\n const cookie = `stel_token=${stelToken}`;\n const response = await fetch(`${MY_TELEGRAM_URL}/apps`, {\n headers: {\n Cookie: cookie,\n 'User-Agent': TELEGRAM_USER_AGENT,\n },\n signal: AbortSignal.timeout(15_000),\n });\n const html = await response.text();\n if (/<title>\\s*App configuration\\s*<\\/title>/i.test(html)) {\n return extractProvisionedApp(html);\n }\n if (!/<title>\\s*Create new application\\s*<\\/title>/i.test(html)) {\n throw new Error('Telegram app provisioning page could not be parsed');\n }\n const creationHash = extractCreationHash(html);\n if (!creationHash) {\n throw new Error('Telegram app provisioning hash missing');\n }\n const createResponse = await fetch(`${MY_TELEGRAM_URL}/apps/create`, {\n method: 'POST',\n headers: createFormHeaders(cookie),\n body: new URLSearchParams({\n hash: creationHash,\n app_title: 'eliza',\n app_shortname: 'eliza',\n app_platform: 'other',\n app_url: '',\n app_desc: '',\n }),\n signal: AbortSignal.timeout(15_000),\n });\n return extractProvisionedApp(await createResponse.text());\n}\n\nexport class TelegramAccountAuthSession implements TelegramAccountAuthSessionLike {\n private snapshot: TelegramAccountAuthSnapshot = {\n status: 'idle',\n phone: null,\n error: null,\n isCodeViaApp: false,\n account: null,\n };\n private client: TelegramClient | null = null;\n private credentials: TelegramAccountApiCredentials | null = null;\n private connectorConfig: TelegramAccountConnectorConfig | null = null;\n private provisioningRandomHash: string | null = null;\n private phoneCodeHash: string | null = null;\n private readonly deviceModel: string;\n private readonly systemVersion: string;\n private readonly deps: Required<TelegramAccountAuthDeps>;\n\n constructor(\n options: {\n deviceModel?: string;\n systemVersion?: string;\n } = {},\n deps: TelegramAccountAuthDeps = {},\n ) {\n this.deviceModel =\n options.deviceModel?.trim() || defaultTelegramAccountDeviceModel();\n this.systemVersion =\n options.systemVersion?.trim() || defaultTelegramAccountSystemVersion();\n this.deps = {\n createTelegramClient: deps.createTelegramClient ?? createTelegramClient,\n sendProvisioningCode: deps.sendProvisioningCode ?? sendProvisioningCode,\n completeProvisioningLogin:\n deps.completeProvisioningLogin ?? completeProvisioningLogin,\n getOrCreateProvisionedApp:\n deps.getOrCreateProvisionedApp ?? getOrCreateProvisionedApp,\n };\n\n const persisted = loadTelegramAccountAuthState();\n if (persisted) {\n this.snapshot = persisted.snapshot;\n this.credentials = persisted.credentials;\n this.connectorConfig = persisted.connectorConfig;\n this.provisioningRandomHash = persisted.provisioningRandomHash;\n this.phoneCodeHash = persisted.phoneCodeHash;\n }\n }\n\n getSnapshot(): TelegramAccountAuthSnapshot {\n return { ...this.snapshot };\n }\n\n getResolvedConnectorConfig(): TelegramAccountConnectorConfig | null {\n return this.connectorConfig ? { ...this.connectorConfig } : null;\n }\n\n async start(options: {\n phone: string;\n credentials: TelegramAccountApiCredentials | null;\n }): Promise<TelegramAccountAuthSnapshot> {\n const phone = options.phone.trim();\n if (!phone) {\n throw new Error('Telegram phone number is required');\n }\n\n await this.disconnectClient();\n clearTelegramAccountSession();\n clearTelegramAccountAuthState();\n this.snapshot = {\n status: 'idle',\n phone,\n error: null,\n isCodeViaApp: false,\n account: null,\n };\n this.credentials = options.credentials;\n this.connectorConfig = null;\n\n if (this.credentials) {\n await this.beginTelegramLogin();\n return this.getSnapshot();\n }\n\n this.provisioningRandomHash = await this.deps.sendProvisioningCode(phone);\n this.snapshot.status = 'waiting_for_provisioning_code';\n this.persistAuthState();\n return this.getSnapshot();\n }\n\n async submit(input: {\n provisioningCode?: string;\n telegramCode?: string;\n password?: string;\n }): Promise<TelegramAccountAuthSnapshot> {\n switch (this.snapshot.status) {\n case 'waiting_for_provisioning_code': {\n const provisioningCode = input.provisioningCode?.trim();\n if (!provisioningCode) {\n throw new Error('Telegram provisioning code is required');\n }\n if (!this.snapshot.phone || !this.provisioningRandomHash) {\n throw new Error('Telegram provisioning session is missing state');\n }\n const stelToken = await this.deps.completeProvisioningLogin(\n this.snapshot.phone,\n this.provisioningRandomHash,\n provisioningCode,\n );\n const app = await this.deps.getOrCreateProvisionedApp(stelToken);\n this.credentials = {\n apiId: app.api_id,\n apiHash: app.api_hash,\n };\n this.provisioningRandomHash = null;\n await this.beginTelegramLogin();\n return this.getSnapshot();\n }\n case 'waiting_for_telegram_code': {\n const telegramCode = input.telegramCode?.trim();\n if (!telegramCode) {\n throw new Error('Telegram login code is required');\n }\n await this.ensureClientConnected();\n await this.completeTelegramCode(telegramCode);\n return this.getSnapshot();\n }\n case 'waiting_for_password': {\n const password = input.password ?? '';\n if (!password.trim()) {\n throw new Error('Telegram two-factor password is required');\n }\n await this.ensureClientConnected();\n await this.completePassword(password);\n return this.getSnapshot();\n }\n default:\n throw new Error('Telegram login is not waiting for input');\n }\n }\n\n async stop(): Promise<void> {\n await this.disconnectClient();\n this.provisioningRandomHash = null;\n this.phoneCodeHash = null;\n this.credentials = null;\n this.connectorConfig = null;\n this.snapshot = {\n status: 'idle',\n phone: null,\n error: null,\n isCodeViaApp: false,\n account: null,\n };\n clearTelegramAccountAuthState();\n }\n\n private async beginTelegramLogin(): Promise<void> {\n if (!this.credentials || !this.snapshot.phone) {\n throw new Error('Telegram login credentials are incomplete');\n }\n\n const session = new StringSession(loadTelegramAccountSessionString());\n this.client = this.deps.createTelegramClient(\n session,\n this.credentials,\n this.deviceModel,\n this.systemVersion,\n );\n await this.client.connect();\n this.persistSession();\n\n if (await this.client.checkAuthorization()) {\n const me = (await this.client.getEntity('me')) as Api.User;\n await this.finishAuthorized(me);\n return;\n }\n\n const sentCode = await this.client.sendCode(\n this.credentials,\n this.snapshot.phone,\n );\n this.phoneCodeHash = sentCode.phoneCodeHash;\n this.snapshot.status = 'waiting_for_telegram_code';\n this.snapshot.isCodeViaApp = sentCode.isCodeViaApp;\n this.snapshot.error = null;\n this.persistSession();\n this.persistAuthState();\n }\n\n private async completeTelegramCode(code: string): Promise<void> {\n if (\n !this.client ||\n !this.credentials ||\n !this.snapshot.phone ||\n !this.phoneCodeHash\n ) {\n throw new Error('Telegram login session is missing state');\n }\n try {\n const result = await this.client.invoke(\n new Api.auth.SignIn({\n phoneNumber: this.snapshot.phone,\n phoneCodeHash: this.phoneCodeHash,\n phoneCode: code,\n }),\n );\n if (!(result instanceof Api.auth.Authorization)) {\n throw new Error('Telegram returned an unexpected authorization state');\n }\n await this.finishAuthorized(result.user as Api.User);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes('SESSION_PASSWORD_NEEDED')) {\n this.snapshot.status = 'waiting_for_password';\n this.snapshot.error = null;\n this.persistSession();\n this.persistAuthState();\n return;\n }\n this.snapshot.status = 'error';\n this.snapshot.error = message;\n this.persistAuthState();\n throw error;\n }\n }\n\n private async completePassword(password: string): Promise<void> {\n if (!this.client || !this.credentials) {\n throw new Error('Telegram password login session is missing state');\n }\n try {\n const user = (await this.client.signInWithPassword(this.credentials, {\n password: async () => password,\n onError: (error: unknown) => {\n throw error instanceof Error ? error : new Error(String(error));\n },\n })) as Api.User;\n await this.finishAuthorized(user);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.snapshot.status = 'error';\n this.snapshot.error = message;\n this.persistAuthState();\n throw error;\n }\n }\n\n private async finishAuthorized(user: Api.User): Promise<void> {\n if (!this.snapshot.phone || !this.credentials || !this.client) {\n throw new Error('Telegram authorization finished without session state');\n }\n saveTelegramAccountSessionString(serializeSession(this.client));\n this.connectorConfig = {\n phone: this.snapshot.phone,\n appId: String(this.credentials.apiId),\n appHash: this.credentials.apiHash,\n deviceModel: this.deviceModel,\n systemVersion: this.systemVersion,\n enabled: true,\n };\n this.snapshot = {\n status: 'configured',\n phone: this.snapshot.phone,\n error: null,\n isCodeViaApp: false,\n account: mapTelegramAccount(user),\n };\n clearTelegramAccountAuthState();\n await this.disconnectClient();\n }\n\n private persistSession(): void {\n if (!this.client) {\n return;\n }\n const session = serializeSession(this.client);\n if (session.trim().length > 0) {\n saveTelegramAccountSessionString(session);\n }\n }\n\n private persistAuthState(): void {\n saveTelegramAccountAuthState({\n snapshot: this.snapshot,\n credentials: this.credentials,\n connectorConfig: this.connectorConfig,\n provisioningRandomHash: this.provisioningRandomHash,\n phoneCodeHash: this.phoneCodeHash,\n });\n }\n\n private async disconnectClient(): Promise<void> {\n if (!this.client) {\n return;\n }\n this.persistSession();\n await this.client.disconnect().catch(() => undefined);\n this.client = null;\n }\n\n private async ensureClientConnected(): Promise<void> {\n if (this.client) {\n return;\n }\n if (!this.credentials) {\n throw new Error('Telegram login session is missing credentials');\n }\n const sessionString = loadTelegramAccountSessionString();\n if (!sessionString.trim()) {\n throw new Error(\n 'Telegram login session is missing persisted session data',\n );\n }\n this.client = this.deps.createTelegramClient(\n new StringSession(sessionString),\n this.credentials,\n this.deviceModel,\n this.systemVersion,\n );\n await this.client.connect();\n }\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,KAAK,sBAAsB;AACpC,SAAS,qBAAqB;AAuF9B,IAAM,kBAAkB;AACxB,IAAM,sBACJ;AACF,IAAM,iCAAiC,oBAAI,IAA+B;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,kBAA0B;AACjC,SACE,QAAQ,IAAI,iBAAiB,KAAK,KAAK,KAAK,KAAK,GAAG,QAAQ,GAAG,QAAQ;AAE3E;AAEA,SAAS,mCAA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L,KAAK;AAAA,IACP;AACA,UAAM,KAAK,OAAO,QAAQ;AAAA,EAC5B;AACF;","names":[]}
@@ -0,0 +1,539 @@
1
+ import { MessagePayload, WorldPayload, EventPayload, EntityPayload, Content, IAgentRuntime, Media, Service, TargetInfo, Plugin } from '@elizaos/core';
2
+ import { Message, ReactionType, Chat, Update } from '@telegraf/types';
3
+ import { Context, Telegraf, NarrowedContext } from 'telegraf';
4
+ export { TelegramAccountApiCredentials, TelegramAccountAuthAccount, TelegramAccountAuthSession, TelegramAccountAuthSessionLike, TelegramAccountAuthSnapshot, TelegramAccountAuthStatus, TelegramAccountConnectorConfig, clearTelegramAccountAuthState, clearTelegramAccountSession, defaultTelegramAccountDeviceModel, defaultTelegramAccountSystemVersion, loadTelegramAccountSessionString, resolveTelegramAccountSessionFile, saveTelegramAccountSessionString, telegramAccountAuthStateExists, telegramAccountSessionExists } from './account-auth-service.js';
5
+ import 'telegram';
6
+ import 'telegram/sessions/index.js';
7
+
8
+ /**
9
+ * Telegram account (user-account) auth HTTP routes.
10
+ *
11
+ * Provides a multi-step login flow for linking a personal Telegram account
12
+ * (as opposed to a bot token) using the `telegram` library (GramJS):
13
+ *
14
+ * GET /api/telegram-account/status current auth/connection status
15
+ * POST /api/telegram-account/auth/start begin login (phone + optional app creds)
16
+ * POST /api/telegram-account/auth/submit submit provisioning code, telegram code, or 2FA password
17
+ * POST /api/telegram-account/disconnect tear down session + clear saved credentials
18
+ *
19
+ * These routes are registered with `rawPath: true` so they mount at their
20
+ * legacy paths without the plugin-name prefix.
21
+ */
22
+
23
+ /** Called on plugin shutdown to clean up the auth session. */
24
+ declare function stopTelegramAccountAuthSession(): Promise<void>;
25
+
26
+ /**
27
+ * Extention of the core Content type just for Telegram
28
+ */
29
+ interface TelegramContent extends Content {
30
+ /** Array of buttons */
31
+ buttons?: Button[];
32
+ }
33
+ /**
34
+ * Represents a flexible button configuration
35
+ */
36
+ type Button = {
37
+ /** The type of button */
38
+ kind: 'login' | 'url';
39
+ /** The text to display on the button */
40
+ text: string;
41
+ /** The URL or endpoint the button should link to */
42
+ url: string;
43
+ };
44
+ /**
45
+ * Telegram-specific event types
46
+ */
47
+ declare enum TelegramEventTypes {
48
+ WORLD_JOINED = "TELEGRAM_WORLD_JOINED",
49
+ WORLD_CONNECTED = "TELEGRAM_WORLD_CONNECTED",
50
+ WORLD_LEFT = "TELEGRAM_WORLD_LEFT",
51
+ ENTITY_JOINED = "TELEGRAM_ENTITY_JOINED",
52
+ ENTITY_LEFT = "TELEGRAM_ENTITY_LEFT",
53
+ ENTITY_UPDATED = "TELEGRAM_ENTITY_UPDATED",
54
+ MESSAGE_RECEIVED = "TELEGRAM_MESSAGE_RECEIVED",
55
+ MESSAGE_SENT = "TELEGRAM_MESSAGE_SENT",
56
+ REACTION_RECEIVED = "TELEGRAM_REACTION_RECEIVED",
57
+ INTERACTION_RECEIVED = "TELEGRAM_INTERACTION_RECEIVED",
58
+ SLASH_START = "TELEGRAM_SLASH_START"
59
+ }
60
+ /**
61
+ * Telegram-specific event payload map
62
+ */
63
+ interface TelegramEventPayloadMap {
64
+ [TelegramEventTypes.MESSAGE_RECEIVED]: TelegramMessageReceivedPayload;
65
+ [TelegramEventTypes.MESSAGE_SENT]: TelegramMessageSentPayload;
66
+ [TelegramEventTypes.REACTION_RECEIVED]: TelegramReactionReceivedPayload;
67
+ [TelegramEventTypes.WORLD_JOINED]: TelegramWorldPayload;
68
+ [TelegramEventTypes.WORLD_CONNECTED]: TelegramWorldPayload;
69
+ [TelegramEventTypes.WORLD_LEFT]: TelegramWorldPayload;
70
+ [TelegramEventTypes.SLASH_START]: TelegramSlashStartPayload;
71
+ [TelegramEventTypes.ENTITY_JOINED]: TelegramEntityPayload;
72
+ [TelegramEventTypes.ENTITY_LEFT]: TelegramEntityPayload;
73
+ [TelegramEventTypes.ENTITY_UPDATED]: TelegramEntityPayload;
74
+ [TelegramEventTypes.INTERACTION_RECEIVED]: TelegramReactionReceivedPayload;
75
+ }
76
+ declare module '@elizaos/core' {
77
+ interface EventPayloadMap extends TelegramEventPayloadMap {
78
+ }
79
+ }
80
+ interface TelegramSlashStartPayload extends EventPayload {
81
+ ctx: Context;
82
+ }
83
+ /**
84
+ * Telegram-specific message received payload
85
+ */
86
+ interface TelegramMessageReceivedPayload extends MessagePayload {
87
+ /** The original Telegram context */
88
+ ctx: Context;
89
+ /** The original Telegram message */
90
+ originalMessage: Message;
91
+ }
92
+ /**
93
+ * Telegram-specific message sent payload
94
+ */
95
+ interface TelegramMessageSentPayload extends MessagePayload {
96
+ /** The original Telegram messages */
97
+ originalMessages: Message[];
98
+ /** The chat ID where the message was sent */
99
+ chatId: number | string;
100
+ }
101
+ /**
102
+ * Telegram-specific reaction received payload
103
+ */
104
+ interface TelegramReactionReceivedPayload extends TelegramMessageReceivedPayload {
105
+ /** The reaction type as a string */
106
+ reactionString: string;
107
+ /** The original reaction object */
108
+ originalReaction: ReactionType;
109
+ }
110
+ /**
111
+ * Telegram-specific world payload
112
+ */
113
+ interface TelegramWorldPayload extends WorldPayload {
114
+ chat: Chat;
115
+ botUsername?: string;
116
+ }
117
+ /**
118
+ * Telegram-specific entity payload
119
+ */
120
+ interface TelegramEntityPayload extends EntityPayload {
121
+ telegramUser: {
122
+ id: number;
123
+ username?: string;
124
+ first_name?: string;
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Interface for structured document processing results.
130
+ */
131
+ interface DocumentProcessingResult {
132
+ title: string;
133
+ fullText: string;
134
+ formattedDescription: string;
135
+ fileName: string;
136
+ mimeType: string | undefined;
137
+ fileSize: number | undefined;
138
+ error?: string;
139
+ }
140
+ /**
141
+ * Enum representing different types of media.
142
+ * @enum { string }
143
+ * @readonly
144
+ */
145
+ declare enum MediaType {
146
+ PHOTO = "photo",
147
+ VIDEO = "video",
148
+ DOCUMENT = "document",
149
+ AUDIO = "audio",
150
+ ANIMATION = "animation"
151
+ }
152
+ /**
153
+ * Class representing a message manager.
154
+ * @class
155
+ */
156
+ declare class MessageManager {
157
+ bot: Telegraf<Context>;
158
+ protected runtime: IAgentRuntime;
159
+ /**
160
+ * Constructor for creating a new instance of a BotAgent.
161
+ *
162
+ * @param {Telegraf<Context>} bot - The Telegraf instance used for interacting with the bot platform.
163
+ * @param {IAgentRuntime} runtime - The runtime environment for the agent.
164
+ */
165
+ constructor(bot: Telegraf<Context>, runtime: IAgentRuntime);
166
+ /**
167
+ * Process an image from a Telegram message to extract the image URL and description.
168
+ *
169
+ * @param {Message} message - The Telegram message object containing the image.
170
+ * @returns {Promise<{ description: string } | null>} The description of the processed image or null if no image found.
171
+ */
172
+ processImage(message: Message): Promise<{
173
+ description: string;
174
+ } | null>;
175
+ /**
176
+ * Process a document from a Telegram message to extract the document URL and description.
177
+ * Handles PDFs and other document types by converting them to text when possible.
178
+ *
179
+ * @param {Message} message - The Telegram message object containing the document.
180
+ * @returns {Promise<{ description: string } | null>} The description of the processed document or null if no document found.
181
+ */
182
+ processDocument(message: Message): Promise<DocumentProcessingResult | null>;
183
+ /**
184
+ * Get the appropriate document processor based on MIME type.
185
+ */
186
+ private getDocumentProcessor;
187
+ /**
188
+ * Process PDF documents by converting them to text.
189
+ */
190
+ private processPdfDocument;
191
+ /**
192
+ * Process text documents by fetching their content.
193
+ */
194
+ private processTextDocument;
195
+ /**
196
+ * Processes the message content, documents, and images to generate
197
+ * processed content and media attachments.
198
+ *
199
+ * @param {Message} message The message to process
200
+ * @returns {Promise<{ processedContent: string; attachments: Media[] }>} Processed content and media attachments
201
+ */
202
+ processMessage(message: Message): Promise<{
203
+ processedContent: string;
204
+ attachments: Media[];
205
+ }>;
206
+ /**
207
+ * Sends a message in chunks, handling attachments and splitting the message if necessary
208
+ *
209
+ * @param {Context} ctx - The context object representing the current state of the bot
210
+ * @param {TelegramContent} content - The content of the message to be sent
211
+ * @param {number} [replyToMessageId] - The ID of the message to reply to, if any
212
+ * @returns {Promise<Message.TextMessage[]>} - An array of TextMessage objects representing the messages sent
213
+ */
214
+ sendMessageInChunks(ctx: Context, content: TelegramContent, replyToMessageId?: number): Promise<Message.TextMessage[]>;
215
+ /**
216
+ * Sends media to a chat using the Telegram API.
217
+ *
218
+ * @param {Context} ctx - The context object containing information about the current chat.
219
+ * @param {string} mediaPath - The path to the media to be sent, either a URL or a local file path.
220
+ * @param {MediaType} type - The type of media being sent (PHOTO, VIDEO, DOCUMENT, AUDIO, or ANIMATION).
221
+ * @param {string} [caption] - Optional caption for the media being sent.
222
+ *
223
+ * @returns {Promise<void>} A Promise that resolves when the media is successfully sent.
224
+ */
225
+ sendMedia(ctx: Context, mediaPath: string, type: MediaType, caption?: string): Promise<void>;
226
+ /**
227
+ * Splits a given text into an array of strings based on the maximum message length.
228
+ *
229
+ * @param {string} text - The text to split into chunks.
230
+ * @returns {string[]} An array of strings with each element representing a chunk of the original text.
231
+ */
232
+ private splitMessage;
233
+ /**
234
+ * Handle incoming messages from Telegram and process them accordingly.
235
+ * @param {Context} ctx - The context object containing information about the message.
236
+ * @returns {Promise<void>}
237
+ */
238
+ handleMessage(ctx: Context): Promise<void>;
239
+ /**
240
+ * Handles the reaction event triggered by a user reacting to a message.
241
+ * @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update
242
+ * @returns {Promise<void>} A Promise that resolves when the reaction handling is complete
243
+ */
244
+ handleReaction(ctx: NarrowedContext<Context<Update>, Update.MessageReactionUpdate>): Promise<void>;
245
+ /**
246
+ * Sends a message to a Telegram chat and emits appropriate events
247
+ * @param {number | string} chatId - The Telegram chat ID to send the message to
248
+ * @param {Content} content - The content to send
249
+ * @param {number} [replyToMessageId] - Optional message ID to reply to
250
+ * @returns {Promise<Message.TextMessage[]>} The sent messages
251
+ */
252
+ sendMessage(chatId: number | string, content: Content, replyToMessageId?: number): Promise<Message.TextMessage[]>;
253
+ }
254
+
255
+ /**
256
+ * TelegramOwnerPairingService
257
+ *
258
+ * Implements the connector side of the owner-pairing flow for Telegram:
259
+ * - `/eliza_pair <code>` bot command: relays a 6-digit pair code to the
260
+ * backend `verifyOwnerBindFromConnector` service and reports the result.
261
+ * - `sendOwnerLoginDmLink({ externalId, link })`: called by the backend's
262
+ * `/api/auth/login/owner/dm-link/request` handler to DM a login link to
263
+ * the Telegram user identified by their numeric user ID.
264
+ *
265
+ * Hard rules:
266
+ * - Backend is the authority. The connector only relays; it never decides
267
+ * whether a binding succeeds.
268
+ * - Fail closed: if the backend service is unreachable, we reply with an
269
+ * explicit error message and do NOT silently succeed.
270
+ * - Per-user rate limit on `/eliza_pair` invocations: 5 attempts per minute.
271
+ * - DM-link sender never pre-fetches or auto-redeems the link.
272
+ *
273
+ * Telegram command naming: underscores instead of hyphens, per Telegram bot
274
+ * command conventions (commands must match [a-z0-9_]{1,32}).
275
+ */
276
+
277
+ /** Service type string used by the backend to look up this service. */
278
+ declare const TELEGRAM_OWNER_PAIRING_SERVICE_TYPE = "OWNER_PAIRING_TELEGRAM";
279
+ /**
280
+ * Public service interface exposed via the runtime service registry.
281
+ * The backend's `owner-binding.ts` calls `sendOwnerLoginDmLink` when the
282
+ * user requests a DM login link via the dashboard.
283
+ */
284
+ interface TelegramOwnerPairingService {
285
+ /**
286
+ * DMs the Telegram user identified by `externalId` (a numeric Telegram user
287
+ * ID as a string) with a login link. The link is presented as-is; this
288
+ * method never pre-fetches or auto-redeems it.
289
+ *
290
+ * Throws if the DM cannot be delivered (Telegram API error, bot blocked by
291
+ * user, etc.). The caller is responsible for surfacing the error.
292
+ */
293
+ sendOwnerLoginDmLink(params: {
294
+ externalId: string;
295
+ link: string;
296
+ }): Promise<void>;
297
+ }
298
+ declare class TelegramOwnerPairingServiceImpl extends Service implements TelegramOwnerPairingService {
299
+ static serviceType: string;
300
+ capabilityDescription: string;
301
+ static start(runtime: IAgentRuntime): Promise<Service>;
302
+ stop(): Promise<void>;
303
+ /**
304
+ * Registers the /eliza_pair command with the active Telegraf bot instance
305
+ * by looking up the TelegramService from the runtime service registry.
306
+ * Called during `start`; it is safe to call this before or after the bot
307
+ * has finished initialising because Telegraf accepts handler registration
308
+ * at any point before `launch()`.
309
+ *
310
+ * If the TelegramService is unavailable, the command is not registered.
311
+ */
312
+ private registerPairCommand;
313
+ sendOwnerLoginDmLink(params: {
314
+ externalId: string;
315
+ link: string;
316
+ }): Promise<void>;
317
+ }
318
+
319
+ /**
320
+ * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.
321
+ * This service handles all Telegram-specific functionality including:
322
+ * - Initializing and managing the Telegram bot
323
+ * - Setting up middleware for preprocessing messages
324
+ * - Handling message and reaction events
325
+ * - Synchronizing Telegram chats, users, and entities with the agent runtime
326
+ * - Managing forum topics as separate rooms
327
+ *
328
+ * @extends Service
329
+ */
330
+ declare class TelegramService extends Service {
331
+ static serviceType: string;
332
+ capabilityDescription: string;
333
+ private bot;
334
+ messageManager: MessageManager | null;
335
+ private options;
336
+ private knownChats;
337
+ private syncedEntityIds;
338
+ private readonly botToken;
339
+ /**
340
+ * Constructor for TelegramService class.
341
+ * @param {IAgentRuntime} runtime - The runtime object for the agent.
342
+ */
343
+ constructor(runtime?: IAgentRuntime);
344
+ /**
345
+ * Starts the Telegram service for the given runtime.
346
+ *
347
+ * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.
348
+ * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.
349
+ */
350
+ static start(runtime: IAgentRuntime): Promise<TelegramService>;
351
+ /**
352
+ * Stops the agent runtime.
353
+ * @param {IAgentRuntime} runtime - The agent runtime to stop
354
+ */
355
+ static stop(runtime: IAgentRuntime): Promise<void>;
356
+ /**
357
+ * Asynchronously stops the bot.
358
+ *
359
+ * @returns A Promise that resolves once the bot has stopped.
360
+ */
361
+ stop(): Promise<void>;
362
+ /**
363
+ * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.
364
+ * @returns {Promise<void>} A Promise that resolves when the initialization is complete.
365
+ */
366
+ private initializeBot;
367
+ /**
368
+ * Sets up the middleware chain for preprocessing messages before they reach handlers.
369
+ * This critical method establishes a sequential processing pipeline that:
370
+ *
371
+ * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings
372
+ * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed
373
+ * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management
374
+ * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities
375
+ *
376
+ * The middleware chain runs in sequence for each message, with each step potentially
377
+ * enriching the context or stopping processing if conditions aren't met.
378
+ * This preprocessing is essential for maintaining consistent state before message handlers execute.
379
+ *
380
+ * @private
381
+ */
382
+ private setupMiddlewares;
383
+ /**
384
+ * Authorization middleware - checks if chat is allowed to interact with the bot
385
+ * based on the TELEGRAM_ALLOWED_CHATS configuration.
386
+ *
387
+ * @param {Context} ctx - The context of the incoming update
388
+ * @param {Function} next - The function to call to proceed to the next middleware
389
+ * @returns {Promise<void>}
390
+ * @private
391
+ */
392
+ private authorizationMiddleware;
393
+ /**
394
+ * Chat and entity management middleware - handles new chats, forum topics, and entity synchronization.
395
+ * This middleware implements decision logic to determine which operations are needed based on
396
+ * the chat type and whether we've seen this chat before.
397
+ *
398
+ * @param {Context} ctx - The context of the incoming update
399
+ * @param {Function} next - The function to call to proceed to the next middleware
400
+ * @returns {Promise<void>}
401
+ * @private
402
+ */
403
+ private chatAndEntityMiddleware;
404
+ /**
405
+ * Process an existing chat based on chat type and message properties.
406
+ * Different chat types require different processing steps.
407
+ *
408
+ * @param {Context} ctx - The context of the incoming update
409
+ * @returns {Promise<void>}
410
+ * @private
411
+ */
412
+ private processExistingChat;
413
+ /**
414
+ * Sets up message and reaction handlers for the bot.
415
+ * Configures event handlers to process incoming messages and reactions.
416
+ *
417
+ * @private
418
+ */
419
+ private setupMessageHandlers;
420
+ /**
421
+ * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.
422
+ * @param {Context} ctx - The context of the incoming update.
423
+ * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.
424
+ */
425
+ private isGroupAuthorized;
426
+ /**
427
+ * Synchronizes an entity from a message context with the runtime system.
428
+ * This method handles three cases:
429
+ * 1. Message sender - most common case
430
+ * 2. New chat member - when a user joins the chat
431
+ * 3. Left chat member - when a user leaves the chat
432
+ *
433
+ * @param {Context} ctx - The context of the incoming update
434
+ * @returns {Promise<void>}
435
+ * @private
436
+ */
437
+ private syncEntity;
438
+ /**
439
+ * Synchronizes the message sender entity with the runtime system.
440
+ * This is the most common entity sync case.
441
+ *
442
+ * @param {Context} ctx - The context of the incoming update
443
+ * @param {UUID} worldId - The ID of the world
444
+ * @param {UUID} roomId - The ID of the room
445
+ * @param {string} chatId - The ID of the chat
446
+ * @returns {Promise<void>}
447
+ * @private
448
+ */
449
+ private syncMessageSender;
450
+ /**
451
+ * Synchronizes a new chat member entity with the runtime system.
452
+ * Triggered when a user joins the chat.
453
+ *
454
+ * @param {Context} ctx - The context of the incoming update
455
+ * @param {UUID} worldId - The ID of the world
456
+ * @param {UUID} roomId - The ID of the room
457
+ * @param {string} chatId - The ID of the chat
458
+ * @returns {Promise<void>}
459
+ * @private
460
+ */
461
+ private syncNewChatMember;
462
+ /**
463
+ * Updates entity status when a user leaves the chat.
464
+ *
465
+ * @param {Context} ctx - The context of the incoming update
466
+ * @returns {Promise<void>}
467
+ * @private
468
+ */
469
+ private syncLeftChatMember;
470
+ /**
471
+ * Handles forum topics by creating appropriate rooms in the runtime system.
472
+ * This enables proper conversation management for Telegram's forum feature.
473
+ *
474
+ * @param {Context} ctx - The context of the incoming update
475
+ * @returns {Promise<void>}
476
+ * @private
477
+ */
478
+ private handleForumTopic;
479
+ /**
480
+ * Builds entity for message sender
481
+ */
482
+ private buildMsgSenderEntity;
483
+ /**
484
+ * Handles new chat discovery and emits WORLD_JOINED event.
485
+ * This is a critical function that ensures new chats are properly
486
+ * registered in the runtime system and appropriate events are emitted.
487
+ *
488
+ * @param {Context} ctx - The context of the incoming update
489
+ * @returns {Promise<void>}
490
+ * @private
491
+ */
492
+ private handleNewChat;
493
+ /**
494
+ * Processes entities in batches to prevent overwhelming the system.
495
+ *
496
+ * @param {Entity[]} entities - The entities to process
497
+ * @param {UUID} roomId - The ID of the room to connect entities to
498
+ * @param {string} channelId - The channel ID
499
+ * @param {ChannelType} roomType - The type of the room
500
+ * @param {UUID} worldId - The ID of the world
501
+ * @returns {Promise<void>}
502
+ * @private
503
+ */
504
+ private batchProcessEntities;
505
+ /**
506
+ * Gets chat title and channel type based on Telegram chat type.
507
+ * Maps Telegram-specific chat types to standardized system types.
508
+ *
509
+ * @param {any} chat - The Telegram chat object
510
+ * @returns {Object} Object containing chatTitle and channelType
511
+ * @private
512
+ */
513
+ private getChatTypeInfo;
514
+ /**
515
+ * Builds standardized entity representations from Telegram chat data.
516
+ * Transforms Telegram-specific user data into system-standard Entity objects.
517
+ *
518
+ * @param {any} chat - The Telegram chat object
519
+ * @returns {Promise<Entity[]>} Array of standardized Entity objects
520
+ * @private
521
+ */
522
+ private buildStandardizedEntities;
523
+ /**
524
+ * Extracts and builds the room object for a forum topic from a message context.
525
+ * This refactored method can be used both in middleware and when handling new chats.
526
+ *
527
+ * @param {Context} ctx - The context of the incoming update
528
+ * @param {UUID} worldId - The ID of the world the topic belongs to
529
+ * @returns {Promise<Room | null>} A Promise that resolves with the room or null if not a topic
530
+ * @private
531
+ */
532
+ private buildForumTopicRoom;
533
+ static registerSendHandlers(runtime: IAgentRuntime, serviceInstance: TelegramService): void;
534
+ handleSendMessage(runtime: IAgentRuntime, target: TargetInfo, content: Content): Promise<void>;
535
+ }
536
+
537
+ declare const telegramPlugin: Plugin;
538
+
539
+ export { MessageManager, TELEGRAM_OWNER_PAIRING_SERVICE_TYPE, type TelegramOwnerPairingService, TelegramOwnerPairingServiceImpl, TelegramService, telegramPlugin as default, stopTelegramAccountAuthSession };