Skip to content

पाइथन एकीकरण

तपाईंको पाइथन अनुप्रयोगमा SMSBAT एपीआईलाई एकीकृत गर्नु सरल रूपमा निर्मित urllib वा लोकप्रिय अनुरोध पुस्तकालय प्रयोग गरेर हो।

अनुरोधहरू प्रयोग गर्दै (सिफारिस गरिएको)

पहिले, 'अनुरोध' पुस्तकालय स्थापना गर्नुहोस्:

pip install requests

त्यसपछि, सन्देश पठाउन निम्न कोड प्रयोग गर्नुहोस्:

import requests
import json

url = 'https://api.smsbat.com/bat/messagelist'
api_key = 'YOUR_API_KEY_HERE'

headers = {
    'Content-Type': 'application/json',
    'X-Authorization-Key': api_key
}

payload = {
    "messages": [
        {
            "from": "ALPHANAME",
            "to": "380501234567",
            "text": "Hello from Python and SMSBAT!",
            "type": "sms"
        }
    ]
}

try:
    response = requests.post(url, headers=headers, json=payload, timeout=10)
    response.raise_for_status() # Raise an exception for HTTP errors

    print(f"Status Code: {response.status_code}")
    print(f"Response: {response.json()}")

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
    if hasattr(e, 'response') and e.response is not None:
        print(f"Error Details: {e.response.text}")

aiohttp (एसिन्क्रोनस) प्रयोग गर्दै

यदि तपाइँ एक async एप्लिकेसन निर्माण गर्दै हुनुहुन्छ (जस्तै, FastAPI वा asyncio प्रयोग गरेर), तपाइँ aiohttp प्रयोग गर्न सक्नुहुन्छ:

pip install aiohttp
import aiohttp
import asyncio

async def send_message():
    url = 'https://api.smsbat.com/bat/messagelist'
    api_key = 'YOUR_API_KEY_HERE'

    headers = {
        'Content-Type': 'application/json',
        'X-Authorization-Key': api_key
    }

    payload = {
        "messages": [
            {
                "from": "ALPHANAME",
                "to": "380501234567",
                "text": "Hello from Async Python!",
                "type": "sms"
            }
        ]
    }

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, headers=headers, json=payload) as response:
                print(f"Status Code: {response.status}")
                result = await response.json()
                print(f"Response: {result}")
        except Exception as e:
            print(f"An error occurred: {e}")

# Run the async function
if __name__ == '__main__':
    asyncio.run(send_message())