I have this cloudflare workers code which sends video to my telegram bot. I want to make…
- User
I have this cloudflare workers code which sends video to my telegram bot. I want to make this function instantly return response while the video is being sent in the background.
"addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) })
async function handleRequest(request) { const formData = await request.formData() const videoUrl = formData.get('video_url') const chatId = formData.get('chat_id')
// Return a success response to the Python request immediately event.waitUntil(sendVideoToTelegram(chatId, videoUrl))
return new Response('Video sending process initiated', { status: 200 }) }
async function sendVideoToTelegram(chatId, videoUrl) { // Download the video from the provided URL const videoResponse = await fetch(videoUrl) const videoBuffer = await videoResponse.arrayBuffer()
// Send the video to the Telegram bot using the Telegram API endpoint const telegramApiUrl =
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendVideoconst formDataTelegram = new FormData() formDataTelegram.append('chat_id', chatId) formDataTelegram.append('video', new Blob([videoBuffer]), 'video.mp4')await fetch(telegramApiUrl, { method: 'POST', body: formDataTelegram }) } "
- Assistant
In the code snippet you provided, it looks like you were on the right track with using
event.waitUntilto handle the video upload in the background. However, theeventobject isn't available within thehandleRequestfunction by default, since it's a parameter for thefetchevent listener but isn't passed as an argument tohandleRequest.To fix the issue, you should pass the
eventobject to thehandleRequestfunction so that it can access thewaitUntilmethod. Adjust your code like this:addEventListener('fetch', event => { event.respondWith(handleRequest(event)) }) async function handleRequest(event) { const request = event.request; const formData = await request.formData() const videoUrl = formData.get('video_url') const chatId = formData.get('chat_id') // Use waitUntil on the event to execute the sendVideoToTelegram function event.waitUntil(sendVideoToTelegram(chatId, videoUrl)) // Return a success response to the Python request immediately return new Response('Video sending process initiated', { status: 200 }) } async function sendVideoToTelegram(chatId, videoUrl) { // ... Your existing sendVideoToTelegram code ... }In this updated code, we're passing the
eventreceived from the'fetch'listener to thehandleRequestfunction, so inside that function, it can now correctly useevent.waitUntilto run thesendVideoToTelegrammethod in the background after sending the immediate success response back to the caller.Make sure you keep your
<YOUR_BOT_TOKEN>securely placed in your code (not shared publicly) and replace it in thetelegramApiUrlwith your actual bot token provided by Telegram.