@@ -25,15 +25,69 @@ export class CopBot {
2525 return CopBot . instance ;
2626 }
2727 async start ( ) {
28- try {
28+ const port = Config . port || 3000 ;
29+ const isProduction = Config . environment === 'production' ;
30+ if ( isProduction ) {
31+ const server = http . createServer ( async ( req , res ) => {
32+ console . log ( 'method' , req . method ) ;
33+ console . log ( 'url' , req . url ) ;
34+
35+ if ( req . method === 'POST' && req . url === '/webhook' ) {
36+ let body = '' ;
37+ req . on ( 'data' , ( chunk ) => {
38+ body += chunk ;
39+ } ) ;
40+ req . on ( 'end' , async ( ) => {
41+ try {
42+ const update = JSON . parse ( body ) ;
43+ if ( ! update ) {
44+ console . error ( 'Received empty body or malformed JSON.' ) ;
45+ return ( res . statusCode = 400 ) ;
46+ }
47+
48+ console . log ( 'Received webhook body:' , update ) ;
49+ if ( ! update || ! update . id ) {
50+ throw new Error ( 'Missing required field: id' ) ;
51+ }
52+ await this . _bot . handleUpdate ( update ) ;
53+ res . statusCode = 200 ;
54+ res . end ( ) ;
55+ } catch ( error : any ) {
56+ console . error ( 'Error parsing JSON in webhook request:' , error . message || error . stack ) ;
57+ res . statusCode = 500 ;
58+ res . end ( 'Internal Server Error' ) ;
59+ }
60+ } ) ;
61+
62+ req . on ( 'error' , ( err ) => {
63+ console . error ( 'Request error:' , err ) ;
64+ res . statusCode = 400 ;
65+ res . end ( 'Bad Request' ) ;
66+ } ) ;
67+ } else {
68+ res . statusCode = 404 ;
69+ res . end ( ) ;
70+ }
71+ } ) ;
72+ server . listen ( port , '0.0.0.0' , ( ) => {
73+ console . log ( `Bot started on port ${ port } ` ) ;
74+ } ) ;
2975 await this . _bot . start ( {
3076 onStart : ( botInfo ) => {
31- console . log ( `Bot started in long-polling mode! Username: ${ botInfo . username } ` ) ;
77+ console . log ( `Bot started in web-hook mode! Username: ${ botInfo . username } ` ) ;
3278 } ,
3379 } ) ;
34- } catch ( error ) {
35- console . error ( 'Error starting bot in long-polling mode:' , error ) ;
36- process . exit ( 1 ) ;
80+ } else {
81+ try {
82+ await this . _bot . start ( {
83+ onStart : ( botInfo ) => {
84+ console . log ( `Bot started in long-polling mode! Username: ${ botInfo . username } ` ) ;
85+ } ,
86+ } ) ;
87+ } catch ( error ) {
88+ console . error ( 'Error starting bot in long-polling mode:' , error ) ;
89+ process . exit ( 1 ) ;
90+ }
3791 }
3892 }
3993 @Catch ( )
0 commit comments