Africa's Talking Python SDK

repository·develop·Indexed 41 days ago

https://github.com/africastalkingltd/africastalking-python

SDK for Python 3.8.x+ to interact with Africa's Talking APIs. Provides interfaces for SMS, Voice, Airtime, WhatsApp, Mobile Data, USSD, Insights, Token, and Application services, supporting both synchronous and asynchronous operation.

Tokens
1.9K
Snippets
4
Records
12
Agent score
1%

What's inside Africa's Talking

  1. Available Services in the SDK

    develop

    After calling africastalking.initialize(), you can access the following service instances:

    • africastalking.SMS
    • africastalking.Airtime
    • africastalking.Voice
    • africastalking.Token
    • africastalking.Application
    • africastalking.MobileData
    • africastalking.Insights
    • africastalking.Whatsapp
    • africastalking.Ussd (Refer to official docs for USSD implementation)
  2. Initialize the Africa's Talking SDK

    develop

    Before using any services, you must initialize the SDK with your credentials.

    For production apps, use your actual username and API key from the Africa's Talking dashboard. For sandbox (development) apps, the username must ALWAYS be sandbox.

    import africastalking
    
    # For sandbox/development
    username = "sandbox"
    api_key = "YOUR_SANDBOX_API_KEY"
    
    # For production
    # username = "YOUR_USERNAME"
    # api_key = "YOUR_API_KEY"
    
    africastalking.initialize(username, api_key)
  3. How to use services synchronously and asynchronously

    develop

    Once initialized, you can access services via africastalking.<ServiceName>.

    • Synchronous usage: Call the method directly and wait for the response.
    • Asynchronous usage: Provide a callback function. The callback accepts two arguments: error and response.
    import africastalking
    
    africastalking.initialize("sandbox", "YOUR_API_KEY")
    sms = africastalking.SMS
    
    # Synchronous
    response = sms.send("Hello Message!", ["+2547xxxxxx"])
    print(response)
    
    # Asynchronous
    def on_finish(error, response):
        if error is not None:
            raise error
        print(response)
    
    sms.send("Hello Message!", ["+2547xxxxxx"], callback=on_finish, timeout=(3, 6))
  4. Use the Whatsapp service

    develop

    The Whatsapp service allows sending messages and templates via WhatsApp.

    Method: send(body: dict, wa_number: str, phone_number: str)

    • wa_number: The WhatsApp number associated with your account. (Required)
    • phone_number: The recipient's phone number. (Required)
    • body: A dictionary containing:
      • message: Text content. (Optional)
      • mediaType: Image, Video, Audio, Voice, Sticker, or Document. (Optional)
      • url: Hosted URL of the media. (Optional)
      • caption: Caption for images/videos. (Optional)
      • action, body, header, footer: Dictionaries for interactive elements. (Optional)

    Method: send_template(component: dict, wa_number: str, name: str, language: str, category: str)

    • wa_number: Your WhatsApp number. (Required)
    • name: Unique template name. (Required)
    • language: Language code. (Required)
    • category: Template category. (Required)
    • component: Dictionary containing header, body, footer, or buttons.
  5. Use the Airtime service

    develop

    The Airtime service allows you to send airtime to recipients.

    Method: send(recipients: [dict])

    recipients is an array of objects, where each object contains:

    • phone_number: Recipient's phone number.
    • amount: Amount to send (e.g., 100).
    • currency_code: 3-digit ISO format currency code (e.g., KES, USD, UGX).

    Optional Parameter:

    • max_num_retry: Specifies the maximum number of retries for failed deliveries. The default retry period is 8 hours with retries every 60 seconds. Setting max_num_retry=4 means the transaction will be retried every 60 seconds for the next 4 hours.
    # Example structure for recipients
    recipients = [
        {
            "phone_number": "+2547xxxxxx",
            "amount": "100",
            "currency_code": "KES"
        }
    ]
    airtime = africastalking.Airtime
    airtime.send(recipients, max_num_retry=4)
  6. Use the Voice service

    develop

    The Voice service allows for initiating calls and managing media.

    Method: call(callFrom: str, callTo: [str])

    • callFrom: Your Africa's Talking phone number (international format). (Required)
    • callTo: Array of destination phone numbers (international format). (Required)

    Method: fetch_queued_calls(phone_number: str)

    • phone_number: Your Africa's Talking phone number (international format). (Required)

    Method: upload_media_file(phone_number: str, url: str)

    • phone_number: Your Africa's Talking phone number (international format). (Required)
    • url: The http(s):// URL of the file to upload. (Required)
  7. Use the Mobile Data service

    develop

    The MobileData service manages mobile data transactions.

    Method: send(product_name: str, recipients: dict)

    • product_name: Africa's Talking payment product name. (Required)
    • recipients: A list of recipient objects, each containing:
      • phoneNumber: Customer phone number (international format). (Required)
      • quantity: Data amount. (Required)
      • unit: MB or GB. (Required)
      • validity: Day, Week, or Month. (Required)
      • metadata: Additional transaction data. (Optional)

    Method: find_transaction(transaction_id: str)

    • Finds a specific mobile data transaction.

    Method: fetch_wallet_balance()

    • Fetches the balance for a mobile data product.
  8. Use the SMS service

    develop

    The SMS service provides multiple ways to send messages and manage subscriptions.

    Method: send(message: str, recipients: [str], sender_id: str = None, enqueue: bool = False)

    • message: SMS content. (Required)
    • recipients: Array of phone numbers. (Required)
    • sender_id: Registered shortcode or alphanumeric ID.
    • enqueue: If True, delivers messages without waiting for telco acknowledgement.

    Method: send_premium(message: str, short_code: str, recipients: [str], link_id: [str] = None, retry_duration_in_hours [int] = None)

    • message: SMS content. (Required)
    • short_code: Your premium product shortCode. (Required)
    • recipients: Array of phone numbers. (Required)
    • keyword: Your premium product keyword.
    • link_id: Forwarded to your app when a user sends a message to your on-demand service.
    • retry_duration_in_hours: Hours to retry subscription messages if undelivered.

    Method: fetch_messages(last_received_id: int = 0)

    • last_received_id: The ID of the last processed message. Defaults to 0.

    Method: create_safaricom_subscription(...) Creates a premium Safaricom subscription with parameters including short_code, keyword, phone_number, request_id, redirect_url, source_ip, and user_agent.