Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import requests
- import time
- import threading
- from queue import Queue
- api_url = "https://repy.in/send-media"
- jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFscGhhQGdtYWlsLmNvbSIsImNsaW5lSWQiOiJkcmI2ZGxjdTYzdHBoenMiLCJpYXQiOjE2OTg5ODk2OTJ9.Tm0h_GLDgnIKr2kbfwBgRvUepl6NEdS22v0rqmnzjvk"
- # Function to send media to a phone number
- def send_media(phone, media_url):
- headers = {
- "Authorization": f"Bearer {jwt_token}",
- "Content-Type": "application/json",
- }
- payload = {
- "phone": phone,
- "mediaUrl": media_url,
- }
- retries = 3
- success = False
- while retries > 0:
- response = requests.post(api_url, json=payload, headers=headers)
- if response.status_code == 200:
- success = True
- print(f"Media sent to {phone} successfully")
- break
- else:
- try:
- error_message = response.json()["message"]
- print(f"Failed to send media to {phone}. Error message: {error_message}")
- except:
- print(f"Failed to send media to {phone}. Unable to parse error message.")
- retries -= 1
- time.sleep(1) # Wait for 1 second before retrying
- if not success:
- # Append the failed data to a CSV file
- with open("failed_records.csv", "a", newline="") as file:
- writer = csv.writer(file)
- writer.writerow([phone, media_url])
- # Function to process the CSV file
- def process_csv():
- processed_phones = set() # To keep track of processed phone numbers
- while not csv_queue.empty():
- phone, media_url = csv_queue.get()
- if phone not in processed_phones:
- send_media(phone, media_url)
- processed_phones.add(phone)
- csv_queue.task_done()
- # Limit API calls to 40 per minute
- def throttle_api_calls():
- while not csv_queue.empty():
- for _ in range(40):
- if not csv_queue.empty():
- phone, media_url = csv_queue.get()
- send_media(phone, media_url)
- csv_queue.task_done()
- else:
- break
- # Read phone numbers and media URLs from a CSV file
- csv_file = "demo.csv"
- csv_queue = Queue()
- with open(csv_file, "r") as file:
- reader = csv.DictReader(file)
- for row in reader:
- phone = row["phone"]
- media_url = row["mediaUrl"]
- csv_queue.put((phone, media_url))
- # Start a separate thread to limit API calls
- api_thread = threading.Thread(target=throttle_api_calls)
- api_thread.start()
- # Process the CSV file
- process_csv()
- # Wait for the API thread and CSV processing to finish
- api_thread.join()
- csv_queue.join()
Advertisement
Add Comment
Please, Sign In to add comment