export class Bot
{
private server!: Deno.HttpServer;
constructor()
{
this.handleExit();
this.server = Deno.serve( { port: 3333, hostname: '127.0.0.1' }, this.handleServerRequests );
}
handleServerRequests = async ( req: Request ): Promise<Response> =>
{
const url = new URL( req.url );
switch ( true )
{
case url.pathname.startsWith( '/websocket' ):
return new Response( null, { status: 204 } );
case url.pathname.startsWith( '/api' ):
return await this.handleApi( req );
case url.pathname.startsWith( '/webhook' ):
return new Response( null, { status: 204 } );
default:
return new Response( null, { status: 204 } );
}
};
private async handleApi( req: Request ): Promise<Response>
{
const body = await req.json();
const response = await this.processApiCall( body );
return new Response(
JSON.stringify( response ),
{
status: 200,
headers: {
'content-type': 'application/json',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, OPTIONS',
'access-control-allow-headers': 'Content-Type, Authorization'
}
}
);
}
async processApiCall( apiRequest: any ): Promise<any>
{
const response = { data: true };
switch ( apiRequest.request )
{
case 'isStreamActive':
response.data = await Promise.resolve( false );
break;
}
return response;
}
private handleExit()
{
Deno.addSignalListener( 'SIGINT', async () =>
{
await this.server.shutdown();
console.log( 'SIGINT Shutdown 🔻' );
Deno.exit();
} );
}
public async simulateApiCall()
{
const response = await fetch( 'http://127.0.0.1:3333/api', {
body: '{"request":"isStreamActive"}',
method: 'post'
} );
setTimeout( function()
{}, 150 );
const json = await response.json();
console.log( json );
return json;
}
}
const bot = new Bot();
setInterval( () => bot.simulateApiCall(), 750 );
Code-Sprache: PHP (php)