cut / lib /tg /index.js
Surf Studio
tg: tracked chats every 20s; polling is the primary path for channels
56c49e4
Raw History Blame Contribute Delete
29.6 kB
/**
* Telegram, logged in as the user's own account (MTProto via GramJS).
*
* Three layers so nothing is missed:
* 1. realtime — every new / edited message in *every* chat the account is in
* is checked the moment Telegram delivers it
* 2. catch-up — every 2 min, the tracked chats are read from the last message
* id seen, oldest → newest, no upper limit on the gap
* 3. global — every 3 min, Telegram's own search over all chats for
* "asksurf" (covers chats that are not tracked)
* Duplicates are harmless: a message is keyed by chat + message id.
*/
const { TelegramClient, Api } = require('telegram')
const { StringSession } = require('telegram/sessions')
const { computeCheck } = require('telegram/Password')
const { Raw } = require('telegram/events')
const db = require('../db')
const log = require('../log')
const detect = require('../detect')
const pipeline = require('../pipeline')
const tgPublic = require('./public')
// 走 443 端口更稳(部分云主机对 80 端口长连接不友好);TG_PORT=80 可切回
const USE_WSS = String(process.env.TG_PORT || '443') !== '80'
const DEFAULT_API_ID = 2040
const DEFAULT_API_HASH = 'b18441a1ff607e10a989891a5462e627'
/** During a redeploy HF runs old and new containers side by side for a moment. */
const BOOT_GRACE_MS = Number(process.env.TG_BOOT_GRACE_MS || 75000)
const FIRST_READ = 50
const MAX_CATCHUP = 1000
const state = {
phase: 'off', // off | waiting | connecting | live | needs-login | flood | error
error: null,
me: null,
events: 0,
kept: 0,
lastEventAt: null,
lastKeptAt: null,
lastCatchup: null,
lastGlobal: null,
globalHits: 0,
floodUntil: 0,
connectedAt: null,
lastPoll: null,
polled: 0,
missedByRealtime: 0,
realtimeResets: 0,
raw: 0,
rawTypes: {},
}
let client = null
let connecting = null
let pendingLogin = null
/** id → { entity, title, username, type } for every chat we know about. */
const chats = new Map()
function enabled() {
const flag = String(process.env.TG_READER || '').toLowerCase()
if (['0', 'false', 'off', 'no'].includes(flag)) return false
if (['1', 'true', 'on', 'yes'].includes(flag)) return true
return Boolean(process.env.SPACE_ID)
}
function credentials() {
const apiId = Number(db.getSetting('tg_api_id') || DEFAULT_API_ID)
return { apiId: Number.isFinite(apiId) ? apiId : DEFAULT_API_ID, apiHash: db.getSetting('tg_api_hash') || DEFAULT_API_HASH }
}
const FRIENDLY = {
PHONE_NUMBER_INVALID: '手机号格式不对,请带上国家码(例如 +8613800138000)',
PHONE_CODE_INVALID: '验证码不对,请重新输入',
PHONE_CODE_EXPIRED: '验证码已过期,请重新发送',
PASSWORD_HASH_INVALID: '两步验证密码不对',
FLOOD_WAIT: 'Telegram 要求放慢速度,请稍后再试',
AUTH_KEY_UNREGISTERED: '登录已失效,请重新登录',
AUTH_KEY_DUPLICATED: '登录会话被 Telegram 判定为重复使用,请重新登录一次',
SESSION_REVOKED: '登录已在其他设备上被注销,请重新登录',
USER_DEACTIVATED: '这个账号已被 Telegram 限制',
INVITE_HASH_EXPIRED: '邀请链接已失效',
USERNAME_NOT_OCCUPIED: '找不到这个用户名',
CHANNEL_PRIVATE: '这个群/频道是私密的,账号不在里面',
}
function friendly(err) {
const raw = String(err?.errorMessage || err?.message || err)
const key = Object.keys(FRIENDLY).find((name) => raw.includes(name))
return Object.assign(new Error(key ? FRIENDLY[key] : raw), { status: 400, raw })
}
const DEAD_SESSION = /AUTH_KEY_UNREGISTERED|AUTH_KEY_DUPLICATED|SESSION_REVOKED|USER_DEACTIVATED|SESSION_EXPIRED/
/** Handle errors that are about the session or rate limits; returns true when handled. */
function handleFatal(err) {
const raw = String(err?.errorMessage || err?.message || err)
const flood = /FLOOD_WAIT_(\d+)|wait of (\d+) seconds/i.exec(raw)
if (flood) {
const seconds = Number(flood[1] || flood[2] || 60)
state.floodUntil = Date.now() + (seconds + 30) * 1000
log.warn('telegram', `Telegram 限流,暂停 ${seconds} 秒`)
return true
}
if (DEAD_SESSION.test(raw)) {
const message = friendly(err).message
db.setSetting('tg_session_bad', message)
state.phase = 'needs-login'
state.error = message
log.error('telegram', message)
stop().catch(() => {})
return true
}
return false
}
/* ------------------------------------------------------------ chat info -- */
const idOf = (value) => (value === undefined || value === null ? null : String(value))
function peerId(peer) {
if (!peer) return null
return idOf(peer.channelId ?? peer.chatId ?? peer.userId)
}
function describe(entity) {
if (!entity) return null
const isUser = entity.className === 'User'
return {
entity,
id: idOf(entity.id),
username: entity.username || null,
title: isUser
? [entity.firstName, entity.lastName].filter(Boolean).join(' ') || entity.username || String(entity.id)
: entity.title || entity.username || String(entity.id),
type: isUser ? 'user' : entity.className === 'Channel' && !entity.megagroup ? 'channel' : 'group',
members: Number(entity.participantsCount || 0) || null,
}
}
function remember(entity) {
const info = describe(entity)
if (info?.id) chats.set(info.id, info)
return info
}
async function loadDialogs() {
const dialogs = await client.getDialogs({ limit: 500 })
for (const dialog of dialogs) if (dialog.entity) remember(dialog.entity)
return dialogs
}
/** Entity for a tracked chat row (by id from the dialog cache, or by username). */
async function entityFor(row) {
if (chats.has(row.id)) return chats.get(row.id).entity
const ref = row.username || (/^\d+$/.test(row.id) ? null : row.id)
if (!ref) throw new Error('账号不在这个群里了(或还没加载到)')
const info = remember(await client.getEntity(ref))
// Legacy rows were keyed by username; switch them to the numeric id.
if (info.id !== row.id) {
db.run('DELETE FROM tg_chats WHERE id = $new', { new: info.id })
db.run('UPDATE tg_chats SET id = $new, title = $title WHERE id = $old', { new: info.id, old: row.id, title: info.title })
row.id = info.id
}
return info.entity
}
/* ------------------------------------------------------------- messages -- */
function messageLinks(message) {
const text = message.message || ''
const links = []
for (const entity of message.entities || []) {
if (entity.className === 'MessageEntityTextUrl' && entity.url) links.push(entity.url)
if (entity.className === 'MessageEntityUrl') links.push(text.slice(entity.offset, entity.offset + entity.length))
}
links.push(...detect.urlsIn(text))
for (const row of message.replyMarkup?.rows || []) {
for (const button of row.buttons || []) if (button?.url) links.push(button.url)
}
const page = message.media?.webpage
if (page?.url) links.push(page.url)
return [...new Set(links.filter(Boolean))]
}
function postUrl(info, messageId) {
if (info.username) return `https://t.me/${info.username}/${messageId}`
if (info.type === 'channel' || info.type === 'group') return `https://t.me/c/${info.id}/${messageId}`
return null
}
function toPost(message, info) {
return {
id: `tg:${info.id}:${message.id}`,
source: 'telegram',
via: info.title,
chat_id: info.id,
author: info.username || info.title,
author_name: info.title,
text: message.message || '',
url: postUrl(info, message.id),
created_at: Number(message.date) || log.now(),
views: Number(message.views || 0),
links: messageLinks(message),
}
}
/** Shared by realtime, catch-up and global search. */
async function handleMessage(message, info, { source = 'realtime' } = {}) {
if (!message || message.className !== 'Message' || !info) return null
const row = db.get('SELECT full FROM tg_chats WHERE id = $id', { id: info.id })
const full = Boolean(row?.full)
const links = messageLinks(message)
if (!detect.maybeRelevant(`${message.message || ''} ${links.join(' ')}`, full)) return null
const result = await pipeline.ingest(toPost(message, info), { full })
if (!result.kept) return result
if (result.kind === 'gift' && info.type !== 'user') {
// A chat that shares gift links gets caught up on from now on.
const added = db.run(
`INSERT INTO tg_chats (id, username, title, type, last_id, hits, auto, added_at)
VALUES ($id, $username, $title, $type, $last, 1, 1, $now)
ON CONFLICT (id) DO UPDATE SET hits = hits + $inc`,
{
id: info.id,
username: info.username,
title: info.title,
type: info.type,
last: Number(message.id),
now: log.now(),
inc: result.isNew ? 1 : 0,
}
)
if (added.changes && !row) log.info('telegram', `自动加入补读列表:${info.title}`)
}
if (source === 'realtime') {
state.kept += 1
state.lastKeptAt = log.now()
}
return result
}
const MESSAGE_UPDATES = new Set(['UpdateNewMessage', 'UpdateNewChannelMessage', 'UpdateEditMessage', 'UpdateEditChannelMessage'])
/** Every raw update from Telegram passes through here. */
function onRaw(update) {
const type = update?.className || update?.constructor?.name || typeof update
const key = type === 'UpdateConnectionState' ? `${type}:${update.state}` : type
state.raw += 1
state.rawTypes[key] = (state.rawTypes[key] || 0) + 1
if (MESSAGE_UPDATES.has(type)) {
onMessage(update.message, update._entities).catch((err) => log.warn('telegram', `处理消息出错:${err.message}`))
} else if (type === 'UpdateShortChatMessage' || type === 'UpdateShortMessage') {
// Text-only short form: count it as delivered; the minute poll reads the full message.
state.events += 1
state.lastEventAt = log.now()
markSeen(idOf(update.chatId ?? update.userId), update.id)
}
}
async function onMessage(message, entities) {
if (!message || message.className !== 'Message') return
state.events += 1
state.lastEventAt = log.now()
const id = peerId(message.peerId)
if (!id) return
markSeen(id, message.id)
let info = chats.get(id)
if (!info) {
// Quick text check first so we only look up chats that matter.
if (!detect.maybeRelevant(`${message.message || ''} ${messageLinks(message).join(' ')}`, true)) return
try {
const known = [...(entities?.values?.() || [])].find((e) => idOf(e?.id) === id)
info = remember(known || (await client.getEntity(message.peerId)))
} catch {
info = { id, title: `Telegram ${id}`, username: null, type: 'group' }
}
}
await handleMessage(message, info)
}
/* ----------------------------------------------------------- connection -- */
async function startClient() {
const session = db.getSetting('tg_session')
if (!session) {
state.phase = 'needs-login'
state.error = null
return
}
if (db.getSetting('tg_session_bad')) {
state.phase = 'needs-login'
state.error = db.getSetting('tg_session_bad')
return
}
const wait = BOOT_GRACE_MS - process.uptime() * 1000
if (wait > 0) {
state.phase = 'waiting'
await new Promise((resolve) => setTimeout(resolve, wait))
}
state.phase = 'connecting'
const { apiId, apiHash } = credentials()
const c = new TelegramClient(new StringSession(session), apiId, apiHash, {
connectionRetries: 10,
retryDelay: 3000,
autoReconnect: true,
deviceModel: 'Surf Gift Tracker',
systemVersion: 'Linux',
appVersion: '2.0',
useWSS: USE_WSS,
})
c.setLogLevel('error')
try {
await c.connect()
await attach(c)
} catch (err) {
await c.disconnect().catch(() => {})
if (!handleFatal(err)) {
state.phase = 'error'
state.error = friendly(err).message
log.fail('telegram', state.error)
}
}
}
/** Count what actually arrives on the wire, so "no realtime updates" can be told apart from "updates we can't decode". */
function instrument(c) {
state.wire = { messages: 0, types: {}, notes: [] }
const sender = c._sender
if (sender && typeof sender._processMessage === 'function') {
const orig = sender._processMessage.bind(sender)
sender._processMessage = async (message) => {
try {
const obj = await message.obj
const name = obj?.className || obj?.constructor?.name || 'unknown'
state.wire.messages += 1
state.wire.types[name] = (state.wire.types[name] || 0) + 1
} catch {}
return orig(message)
}
}
for (const level of ['info', 'warn']) {
const orig = c._log[level]?.bind(c._log)
c._log[level] = (msg, ...rest) => {
const text = String(msg)
if (/not found|Security error|Invalid buffer|Broken auth/i.test(text)) {
state.wire.notes.unshift(`${new Date().toISOString().slice(11, 19)} ${text.slice(0, 160)}`)
state.wire.notes.length = Math.min(state.wire.notes.length, 15)
}
return orig?.(msg, ...rest)
}
}
}
/** Make `c` the live client: identity, dialog cache, event handlers. */
async function attach(c) {
client = c
instrument(c)
const me = await c.getMe()
state.me = { name: [me.firstName, me.lastName].filter(Boolean).join(' ') || me.username || '', username: me.username || null }
await loadDialogs()
c.addEventHandler(onRaw, new Raw({}))
await c.invoke(new Api.updates.GetState()).catch(() => {})
state.phase = 'live'
state.error = null
state.connectedAt = log.now()
log.ok('telegram', { state: 'live' })
log.info('telegram', `已连接 ${state.me.username ? '@' + state.me.username : state.me.name},实时监听 ${chats.size} 个对话`)
catchup().catch(() => {})
}
function start() {
if (!enabled()) {
state.phase = 'off'
return Promise.resolve()
}
if (!connecting) connecting = startClient().finally(() => (connecting = null))
return connecting
}
async function stop() {
const c = client
client = null
if (state.phase === 'live') state.phase = 'off'
if (c) await c.disconnect().catch(() => {})
}
/** Keep the connection alive; reconnect when GramJS gave up. */
async function watchdog() {
if (!enabled() || connecting) return
if (state.phase === 'live' && client && !client.connected) {
log.warn('telegram', '连接断开,正在重连')
await stop()
return start()
}
if (state.phase === 'error') return start()
if (state.phase === 'live' && client) {
// A cheap call that fails fast when the session died silently.
await client.invoke(new Api.updates.GetState()).catch((err) => handleFatal(err))
}
}
/* ---------------------------------------------------------- dialog poll -- */
/**
* Safety net for realtime: Telegram's update stream can go quiet without any
* error. Every minute the dialog list (one request) tells us the newest message
* id in every chat; anything newer than last time is read directly. If those
* messages never arrived as realtime events, the update stream is restarted.
*/
const tops = new Map()
const seenEvents = new Set()
let pollBaselined = false
let lastReset = 0
let polling = null
function markSeen(chatId, msgId) {
seenEvents.add(`${chatId}:${msgId}`)
if (seenEvents.size > 5000) {
const first = seenEvents.values().next().value
seenEvents.delete(first)
}
}
function pollDialogs() {
if (!polling) polling = pollNow().finally(() => (polling = null))
return polling
}
async function pollNow() {
if (!ready()) return { skipped: true }
const dialogs = await client.getDialogs({ limit: 300 })
let changed = 0
let read = 0
let fresh = 0
let missed = 0
for (const dialog of dialogs) {
if (!dialog.entity || !ready()) continue
const info = remember(dialog.entity)
if (!info) continue
const top = Number(dialog.message?.id || 0)
const prev = tops.get(info.id)
tops.set(info.id, top)
if (!pollBaselined || prev === undefined || top <= prev) continue
changed += 1
if (info.type === 'user') {
// Private chats: only count them to judge whether realtime is alive.
if (!seenEvents.has(`${info.id}:${top}`)) missed += 1
continue
}
try {
const messages = await client.getMessages(dialog.entity, { minId: prev, limit: Math.min(100, top - prev) })
for (const message of [...messages].reverse()) {
if (message?.className !== 'Message') continue
read += 1
if (!seenEvents.has(`${info.id}:${message.id}`)) missed += 1
markSeen(info.id, message.id)
const result = await handleMessage(message, info, { source: 'poll' })
if (result?.isNew) fresh += 1
}
} catch (err) {
if (handleFatal(err)) break
}
}
pollBaselined = true
state.lastPoll = log.now()
state.polled += read
state.missedByRealtime += missed
if (fresh) log.info('telegram', `轮询补到 ${fresh} 条相关消息`)
// Telegram rarely pushes big-channel posts to user accounts, so polling is the main path for
// channels. Re-subscribing once in a while is harmless and helps for small groups / DMs.
if (missed >= 3 && Date.now() - lastReset > 60 * 60000) {
lastReset = Date.now()
state.realtimeResets += 1
restartUpdates().catch(() => {})
}
log.ok('tg-poll', { dialogs: dialogs.length, changed, read, fresh, missed })
return { dialogs: dialogs.length, changed, read, fresh, missed }
}
/** Re-subscribe to the update stream without logging out. */
async function restartUpdates() {
if (!client) return
await client.invoke(new Api.updates.GetState()).catch(() => {})
await client.invoke(new Api.account.UpdateStatus({ offline: false })).catch(() => {})
}
/* -------------------------------------------------------------- catch-up -- */
function ready() {
return state.phase === 'live' && client && state.floodUntil <= Date.now()
}
let catching = null
/** Read every tracked chat from its last seen message id. */
function catchup() {
if (!catching) catching = catchupNow().finally(() => (catching = null))
return catching
}
async function catchupNow() {
if (!ready()) return publicFallback()
const rows = db.all('SELECT * FROM tg_chats ORDER BY hits DESC')
let read = 0
let kept = 0
const errors = []
for (const row of rows) {
if (!ready()) break
try {
const entity = await entityFor(row)
const info = chats.get(row.id) || describe(entity)
let maxId = Number(row.last_id || 0)
const messages =
maxId > 0
? client.iterMessages(entity, { minId: maxId, reverse: true, limit: MAX_CATCHUP })
: (await client.getMessages(entity, { limit: FIRST_READ })).reverse()
for await (const message of messages) {
read += 1
maxId = Math.max(maxId, Number(message.id || 0))
const r = await handleMessage(message, info, { source: 'catchup' })
if (r?.isNew) kept += 1
}
if (maxId > Number(row.last_id || 0)) {
db.run('UPDATE tg_chats SET last_id = $last, title = $title WHERE id = $id', {
id: row.id,
last: maxId,
title: info.title || row.title,
})
}
} catch (err) {
if (handleFatal(err)) break
errors.push(`${row.title || row.id}:${friendly(err).message}`)
}
await new Promise((resolve) => setTimeout(resolve, 250))
}
state.lastCatchup = log.now()
if (errors.length && errors.length === rows.length) log.fail('tg-catchup', errors[0])
else log.ok('tg-catchup', { chats: rows.length, read, fresh: kept, errors: errors.slice(0, 5) })
return { chats: rows.length, read, fresh: kept, errors }
}
/** Telegram's own search across every chat the account is in. */
async function globalSearch() {
if (!ready()) return { skipped: true }
try {
const res = await client.invoke(
new Api.messages.SearchGlobal({
q: 'asksurf',
filter: new Api.InputMessagesFilterEmpty(),
minDate: log.now() - 6 * 3600,
maxDate: 0,
offsetRate: 0,
offsetPeer: new Api.InputPeerEmpty(),
offsetId: 0,
limit: 50,
})
)
for (const entity of [...(res.chats || []), ...(res.users || [])]) remember(entity)
let fresh = 0
for (const message of res.messages || []) {
const info = chats.get(peerId(message.peerId))
const r = await handleMessage(message, info, { source: 'global' })
if (r?.isNew) fresh += 1
}
state.lastGlobal = log.now()
state.globalHits = (res.messages || []).length
log.ok('tg-global', { hits: state.globalHits, fresh })
return { hits: state.globalHits, fresh }
} catch (err) {
if (!handleFatal(err)) log.fail('tg-global', friendly(err).message)
return { error: err.message }
}
}
/** While logged out / broken: read public chats through the t.me web preview. */
async function publicFallback() {
const rows = db.all(`SELECT * FROM tg_chats WHERE username IS NOT NULL AND username <> ''`)
if (!rows.length) return { skipped: true }
let fresh = 0
for (const row of rows) {
try {
const { title, messages } = await tgPublic.readChannel(row.username)
for (const m of messages) {
const full = Boolean(row.full)
if (!detect.maybeRelevant(`${m.text} ${m.links.join(' ')}`, full)) continue
const r = await pipeline.ingest(
{
id: `tg:${row.id}:${m.id}`,
source: 'telegram',
via: title,
chat_id: row.id,
author: row.username,
author_name: title,
text: m.text,
url: `https://t.me/${row.username}/${m.id}`,
created_at: m.date,
views: m.views,
links: m.links,
},
{ full }
)
if (r.isNew) fresh += 1
}
} catch {
/* next chat */
}
}
log.ok('tg-public', { chats: rows.length, fresh })
return { public: rows.length, fresh }
}
/* ------------------------------------------------------------------ login -- */
async function startLogin(phone) {
const clean = String(phone || '').replace(/[\s-]/g, '')
if (!/^\+\d{6,16}$/.test(clean)) throw Object.assign(new Error('请输入带国家码的手机号,例如 +8613800138000'), { status: 400 })
if (!enabled()) throw Object.assign(new Error('这台服务器没有开启 Telegram 读取'), { status: 409 })
if (pendingLogin) await pendingLogin.client.disconnect().catch(() => {})
const { apiId, apiHash } = credentials()
const c = new TelegramClient(new StringSession(''), apiId, apiHash, { connectionRetries: 3, deviceModel: 'Surf Gift Tracker', useWSS: USE_WSS })
c.setLogLevel('error')
await c.connect()
try {
const sent = await c.invoke(
new Api.auth.SendCode({ phoneNumber: clean, apiId, apiHash, settings: new Api.CodeSettings({}) })
)
pendingLogin = { client: c, phone: clean, hash: sent.phoneCodeHash, needsPassword: false }
return { ok: true }
} catch (err) {
await c.disconnect().catch(() => {})
throw friendly(err)
}
}
async function submitCode({ code, password }) {
const login = pendingLogin
if (!login) throw Object.assign(new Error('请先发送验证码'), { status: 400 })
const c = login.client
if (!login.needsPassword) {
if (!code) throw Object.assign(new Error('请输入验证码'), { status: 400 })
try {
await c.invoke(new Api.auth.SignIn({ phoneNumber: login.phone, phoneCodeHash: login.hash, phoneCode: String(code).trim() }))
} catch (err) {
if (!String(err?.errorMessage || err?.message).includes('SESSION_PASSWORD_NEEDED')) throw friendly(err)
login.needsPassword = true
if (!password) return { ok: false, needPassword: true }
}
}
if (login.needsPassword) {
if (!password) return { ok: false, needPassword: true }
try {
const info = await c.invoke(new Api.account.GetPassword())
await c.invoke(new Api.auth.CheckPassword({ password: await computeCheck(info, String(password)) }))
} catch (err) {
throw friendly(err)
}
}
pendingLogin = null
// Replace whatever was running with the freshly logged-in client.
await stop()
db.setSetting('tg_session', c.session.save())
db.clearSetting('tg_session_bad')
db.changed(true)
await attach(c)
return { ok: true, me: state.me }
}
async function logout() {
if (client) await client.invoke(new Api.auth.LogOut()).catch(() => {})
await stop()
db.clearSetting('tg_session')
db.clearSetting('tg_session_bad')
state.phase = 'needs-login'
state.me = null
return status()
}
async function reconnect() {
db.clearSetting('tg_session_bad')
await stop()
state.floodUntil = 0
await start()
return status()
}
/** Logged-in devices on this account (helps spot a duplicate copy stealing realtime updates). */
async function sessions() {
requireLive()
const res = await client.invoke(new Api.account.GetAuthorizations())
return (res.authorizations || []).map((a) => ({
current: Boolean(a.current),
device: a.deviceModel,
app: `${a.appName || ''} ${a.appVersion || ''}`.trim(),
platform: a.platform,
country: a.country,
created: a.dateCreated,
active: a.dateActive,
}))
}
/* ------------------------------------------------------------ chat list -- */
function requireLive() {
if (state.phase !== 'live' || !client) throw Object.assign(new Error('Telegram 还没有连上(请先登录)'), { status: 409 })
}
async function dialogs() {
requireLive()
await loadDialogs()
const tracked = new Set(db.all('SELECT id FROM tg_chats').map((r) => r.id))
return [...chats.values()]
.filter((info) => info.type !== 'user')
.map(({ entity, ...info }) => ({ ...info, tracked: tracked.has(info.id) }))
.sort((a, b) => Number(b.tracked) - Number(a.tracked) || (b.members || 0) - (a.members || 0))
}
function addRows(items, auto = 0) {
let added = 0
for (const item of items) {
if (!item?.id) continue
const res = db.run(
`INSERT INTO tg_chats (id, username, title, type, auto, added_at) VALUES ($id, $username, $title, $type, $auto, $now)
ON CONFLICT (id) DO UPDATE SET auto = 0, title = excluded.title`,
{ id: String(item.id), username: item.username || null, title: item.title || String(item.id), type: item.type || null, auto, now: log.now() }
)
added += res.changes
}
db.changed(true)
return added
}
/** Add by @name, t.me link or private invite link. */
async function addByLink(input) {
requireLive()
const raw = String(input || '').trim()
const hash = /(?:t\.me|telegram\.me)\/(?:\+|joinchat\/)([A-Za-z0-9_-]+)/i.exec(raw)?.[1]
let entity = null
try {
if (hash) {
try {
const invite = await client.invoke(new Api.messages.CheckChatInvite({ hash }))
entity = invite?.chat || null
if (!entity) entity = (await client.invoke(new Api.messages.ImportChatInvite({ hash })))?.chats?.[0] || null
} catch (err) {
if (!String(err?.errorMessage || '').includes('USER_ALREADY_PARTICIPANT')) throw err
entity = (await client.invoke(new Api.messages.CheckChatInvite({ hash })))?.chat || null
}
} else {
const username = raw.replace(/^https?:\/\/(t\.me|telegram\.me)\//i, '').replace(/^s\//, '').replace(/^@/, '').split(/[/?#]/)[0]
if (!username) throw new Error('请输入群/频道用户名或链接')
entity = await client.getEntity(username)
}
} catch (err) {
throw friendly(err)
}
if (!entity) throw Object.assign(new Error('没能识别这个群/频道'), { status: 400 })
const info = remember(entity)
addRows([info])
return info && { id: info.id, title: info.title, username: info.username, type: info.type }
}
function removeChat(id) {
db.run('DELETE FROM tg_chats WHERE id = $id', { id: String(id) })
db.changed()
}
function setFull(id, full) {
db.run('UPDATE tg_chats SET full = $full WHERE id = $id', { id: String(id), full: full ? 1 : 0 })
db.changed()
}
function trackedChats() {
return db.all('SELECT id, username, title, type, full, hits, auto, last_id FROM tg_chats ORDER BY auto ASC, hits DESC, title')
}
function status() {
return {
enabled: enabled(),
loggedIn: Boolean(db.getSetting('tg_session')) && !db.getSetting('tg_session_bad'),
pendingCode: Boolean(pendingLogin),
needsPassword: Boolean(pendingLogin?.needsPassword),
phase: state.phase,
error: state.error,
me: state.me,
dialogs: chats.size,
events: state.events,
kept: state.kept,
lastEventAt: state.lastEventAt,
lastKeptAt: state.lastKeptAt,
lastCatchup: state.lastCatchup,
lastGlobal: state.lastGlobal,
lastPoll: state.lastPoll,
polled: state.polled,
missedByRealtime: state.missedByRealtime,
realtimeResets: state.realtimeResets,
raw: state.raw,
rawTypes: state.rawTypes,
wire: state.wire || null,
globalHits: state.globalHits,
floodUntil: state.floodUntil > Date.now() ? Math.floor(state.floodUntil / 1000) : null,
connectedAt: state.connectedAt,
}
}
// GramJS's internal ping loop can reject with a bare TIMEOUT while reconnecting.
process.on('unhandledRejection', (reason) => {
const message = String(reason?.message || reason || '')
if (message === 'TIMEOUT' || /Not connected|Cannot send requests while disconnected/i.test(message)) return
console.error('[unhandledRejection]', reason)
})
module.exports = {
enabled,
start,
stop,
watchdog,
catchup,
pollDialogs,
globalSearch,
startLogin,
submitCode,
logout,
reconnect,
dialogs,
sessions,
addRows,
addByLink,
removeChat,
setFull,
trackedChats,
status,
// for tests
toPost,
messageLinks,
}