convert this python code into javascript. I want it to work with cloudflare workers. I…
- User
convert this python code into javascript. I want it to work with cloudflare workers. I should be able to pass the input as query string to my cloudflare workers script and it should return this function's output in response :
"import requests import uuid import time as t def ytpubler(chat_id,fburl): url = "https://app.publer.io/hooks/media"
payload = { "url": f"{fburl}", "iphone": False } headers = { "authority": "app.publer.io", "accept": "*/*", "accept-language": "en-US,en;q=0.9", "content-type": "application/json;", "origin": "https://publer.io", "referer": "https://publer.io/", "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"', "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "Windows", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-site", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } response = requests.request("POST", url, json=payload, headers=headers) # print(response.json()) print(response.text) jobid = response.json()["job_id"] print(jobid) # import requests while True: url = f"https://app.publer.io/api/v1/job_status/{jobid}" t.sleep(2) payload = "" headers = { "authority": "app.publer.io", "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9", "if-none-match": 'W/"9ac8fcf21ca0fbac7a38c54e3a5c7fd9"', "origin": "https://publer.io", "referer": "https://publer.io/", "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"', "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "Windows", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-site", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } response = requests.request("GET", url, data=payload, headers=headers) result = response.json() status = response.json()["status"] if status == "complete": break jsonlink = response.json()["payload"] downloadlink = jsonlink[0]["path"] print(downloadlink) def download_video(url): response = requests.get(url) if response.status_code == 200: # Generate a random file name file_name = str(uuid.uuid4()) + '.mp4' # Save the video to the file with open(file_name, 'wb') as file: file.write(response.content) print(f"Video downloaded and saved as {file_name}") # sendv(chat_id, file_name) else: print("Failed to download the video") download_video(downloadlink) print("Video downloaded and sent successfully!")" - Assistant
- User
Besides returning the download link, also run this function. Please modify this python function to javascript to make it work with the above function : "def sendshortsvideo(video_url, chat_id): workers_endpoint_url = "https://downloandsendshortsvideo-9aaf.dhanasekarramesh77.workers.dev" data = { 'video_url': video_url, 'chat_id': chat_id }
# Make an HTTP POST request to the Cloudflare Workers endpoint with the Content-Type header response = requests.post(workers_endpoint_url, data=data, headers={'Content-Type': 'application/x-www-form-urlencoded'}) # Check the response status if response.status_code == 200: print('Cloudflare Workers endpoint called successfully. Video sending process initiated.') else: print('Failed to call Cloudflare Workers endpoint.')"As you can see, I'll also be passing the fburl as well as chat_id as query string which will be passed to this endpoint when called.
- Assistant
- User
Property 'status_code' does not exist on type 'Response'.ts(2339)
- Assistant
The error message you encountered,
Property 'status_code' does not exist on type 'Response'.ts(2339), indicates a slight mistake in referencing the response status code in JavaScript. Unlike Python'srequestslibrary, where the attribute isstatus_code, in JavaScript's Fetch API, you should useresponse.statusto get the HTTP status code of the response.Here's the corrected part of the function
sendshortsvideo:async function sendshortsvideo(video_url, chat_id) { const workers_endpoint_url = "https://downloandsendshortsvideo-9aaf.dhanasekarramesh77.workers.dev"; const data = { video_url: video_url, chat_id: chat_id }; const formData = new URLSearchParams(data).toString(); // Convert object to 'application/x-www-form-urlencoded' const response = await fetch(workers_endpoint_url, { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: formData }); if (response.status === 200) { // Corrected from response.status_code to response.status console.log('Cloudflare Workers endpoint called successfully. Video sending process initiated.'); } else { console.log('Failed to call Cloudflare Workers endpoint.'); } } - User
yeah but I always get Failed to call Cloudflare Workers endpoint. although I see the download link printed to the console when console.logging. Please check the code for sendshortsvideo function and make sure every thing is correct as I provided in my python code
- Assistant
- User
- Assistant
Your requirement to have the Cloudflare Worker return an immediate response while continuing to execute asynchronous processing in the background is a perfect use case for the
event.waitUntilmethod. You've already incorporated it in yourhandleRequestfunction when callingsendVideoToTelegram, which is exactly how you achieve running tasks in the background after sending out an initial response.This approach leverages the Service Workers API, which Cloudflare Workers are based on, allowing you to extend the event lifetime by passing a promise to . The Cloudflare runtime waits for this promise to settle before considering the worker completely finished, which means you can respond to the user immediately and continue processing or making additional requests without making the user wait.
- User
But the code doesn't work if I change const downloadLink = await ytpubler(fburl) to const downloadLink = event.waitUntil(ytpubler(fburl));
I want to code to call the ytpubler function and wait for the downloadlink and then call sendVideoToTelegram all in the background after immediately returning the response
- Assistant