@@ -10,6 +10,9 @@ import TelegramBot from './telegram_bot.js';
1010
1111/** Class representing the context of execution */
1212export default class TelegramExecutionContext {
13+ /** Cache for business connection owners */
14+ private static businessOwners = new Map < string , number > ( ) ;
15+
1316 /** an instance of the telegram bot */
1417 bot : TelegramBot ;
1518 /** an instance of the telegram update */
@@ -158,6 +161,33 @@ export default class TelegramExecutionContext {
158161 params : any ,
159162 apiMethod : ( botApi : string , data : any ) => Promise < T >
160163 ) : Promise < T | null > {
164+ // If we have a business connection, validate the peer first to avoid redundant retries
165+ if ( params . business_connection_id ) {
166+ const connectionId = params . business_connection_id . toString ( ) ;
167+ let ownerId = TelegramExecutionContext . businessOwners . get ( connectionId ) ;
168+
169+ if ( ownerId === undefined ) {
170+ try {
171+ const response = await this . api . getBusinessConnection ( this . bot . api . toString ( ) , connectionId ) ;
172+ if ( response . status === 200 ) {
173+ const json = await response . json ( ) as { ok : boolean , result : { user : { id : number } } } ;
174+ if ( json . ok && json . result ?. user ?. id ) {
175+ ownerId = json . result . user . id ;
176+ TelegramExecutionContext . businessOwners . set ( connectionId , ownerId ) ;
177+ }
178+ }
179+ } catch ( e ) {
180+ console . warn ( 'Failed to fetch business connection info:' , e ) ;
181+ }
182+ }
183+
184+ // If the chat_id is the owner of the connection, we cannot use the business connection
185+ if ( ownerId !== undefined && params . chat_id . toString ( ) === ownerId . toString ( ) ) {
186+ const { business_connection_id, ...retryParams } = params ;
187+ return await apiMethod ( this . bot . api . toString ( ) , retryParams ) ;
188+ }
189+ }
190+
161191 try {
162192 return await apiMethod ( this . bot . api . toString ( ) , params ) ;
163193 } catch ( e ) {
0 commit comments