GithubHelp home page GithubHelp logo

africastalkingltd / africastalking-python Goto Github PK

View Code? Open in Web Editor NEW
133.0 21.0 118.0 172 KB

Official Python SDK

Home Page: https://developers.africastalking.com

License: MIT License

Python 80.03% CSS 4.15% HTML 7.41% JavaScript 8.41%
sms-api ussd voice callback-url payments mpesa-api mpesa shortcode sms-gateway sms

africastalking-python's Introduction

africastalking-python

The SDK provides convenient access to the Africa's Talking APIs to python apps.

Documentation

Take a look at the API docs here.

Install

$ pip  install africastalking # python 2.7.x

OR

$ python -m pip install africastalking # python 2.7.x

OR

$ pip3 install africastalking # python 3.6.x

OR

$ python3 -m pip install africastalking # python 3.6.x

Usage

The package needs to be configured with your app username and API key, which you can get from the dashboard.

You can use this SDK for either production or sandbox apps. For sandbox, the app username is ALWAYS sandbox

# import package
import africastalking


# Initialize SDK
username = "YOUR_USERNAME"    # use 'sandbox' for development in the test environment
api_key = "YOUR_API_KEY"      # use your sandbox app API key for development in the test environment
africastalking.initialize(username, api_key)


# Initialize a service e.g. SMS
sms = africastalking.SMS


# Use the service synchronously
response = sms.send("Hello Message!", ["+2547xxxxxx"])
print(response)

# Or use it asynchronously
def on_finish(error, response):
    if error is not None:
        raise error
    print(response)

sms.send("Hello Message!", ["+2547xxxxxx"], callback=on_finish)    

See example for more usage examples.

Initialization

Initialize the SDK by calling africastalking.initialize(username, api_key). After initialization, you can get instances of offered services as follows:

Application

  • fetch_application_data(): Get app information. e.g balance.

Airtime

  • send(recipients: [dict]): Send airtime

    • recipients: Contains an array of arrays containing the following keys

      • phone_number: Recipient of airtime
      • amount: Amount to send with currency e.g 100
      • currency_code: 3-digit ISO format currency code (e.g KES, USD, UGX etc).
  • max_num_retry: This allows you to specify the maximum number of retries in case of failed airtime deliveries due to various reasons such as telco unavailability. The default retry period is 8 hours and retries occur every 60 seconds. For example, setting max_num_retry=4 means the transaction will be retried every 60 seconds for the next 4 hours. OPTIONAL.

Sms

  • send(message: str, recipients: [str], sender_id: str = None, enqueue: bool = False): Send a message.

    • message: SMS content. REQUIRED
    • recipients: An array of phone numbers. REQUIRED
    • sender_id: Shortcode or alphanumeric ID that is registered with your Africa's Talking account.
    • enqueue: Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.
  • send_premium(message: str, short_code: str, recipients: [str], link_id: [str] = None, retry_duration_in_hours [int] = None): Send a premium SMS

    • message: SMS content. REQUIRED
    • short_code: Your premium product shortCode. REQUIRED
    • recipients: An array of phone numbers. REQUIRED
    • keyword: Your premium product keyword.
    • link_id: We forward the linkId to your application when a user sends a message to your onDemand service
    • retry_duration_in_hours: This specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber
  • fetch_messages(last_received_id: int = 0): Fetch your messages

    • last_received_id: This is the id of the message you last processed. Defaults to 0
  • create_subscription(short_code: str, keyword: str, phone_number: str): Create a premium subscription

    • short_code: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and is also mapped to your account. REQUIRED
    • phone_number: PhoneNumber to be subscribed REQUIRED
  • fetch_subscriptions(short_code: str, keyword: str, last_received_id: int = 0): Fetch your premium subscription data

    • short_code: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and mapped to your account. REQUIRED
    • last_received_id: ID of the subscription you believe to be your last. Defaults to 0
  • delete_subscription(short_code: str, keyword: str, phone_number: str): Delete a phone number from a premium subscription

    • short_code: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and is also mapped to your account. REQUIRED
    • phone_number: PhoneNumber to be subscribed REQUIRED

Voice

  • call(callFrom: str, callTo: [str]): Initiate a phone call

    • callFrom: Phone number on Africa's Talking (in international format). REQUIRED
    • callTo: An array of phone numbers that you wish to dial (in international format). REQUIRED
  • fetch_queued_calls(phone_number: str): Get queued calls

    • phone_number: Phone number mapped to your Africa's Talking account (in international format). REQUIRED
  • upload_media_file(phone_number: str, url: str): Upload voice media file

    • phone_number: phone number mapped to your Africa's Talking account (in international format). REQUIRED
    • url: The url of the file to upload. Should start with http(s)://. REQUIRED

MobileData

  • send(product_name: str, recipients: dict): Send mobile data to customers.

    • product_name: Payment product on Africa's Talking. REQUIRED
    • recipients: A list of recipients. Each recipient has:
      • phoneNumber: Customer phone number (in international format). REQUIRED
      • quantity: Mobile data amount. REQUIRED
      • unit: Mobile data unit. Can either be MB or GB. REQUIRED
      • validity: How long the mobile data is valid for. Must be one of Day, Week and Month. REQUIRED
      • metadata: Additional data to associate with the transaction. OPTIONAL
  • find_transaction(transaction_id: str): Find a mobile data transaction.

  • fetch_wallet_balance(): Fetch a mobile data product balance.

Token

  • generate_auth_token(): Generate an auth token to use for authentication instead of an API key.

Ussd

For more information, please read https://developers.africastalking.com/docs/ussd

Development

$ git clone https://github.com/AfricasTalkingLtd/africastalking-python.git
$ cd africastalking-python
$ touch .env

Make sure your .env file has the following content then run python -m unittest discover -v

# AT API
USERNAME=sandbox
API_KEY=some_key

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

africastalking-python's People

Contributors

aksalj avatar anthonylimo avatar geoffmahugu avatar ianjuma avatar jnyoike avatar kanyikennedy avatar kevokevoh avatar mattgathu avatar mrteey avatar ngash avatar nicholas-ngatia avatar rawplutonium avatar zlyxero avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

africastalking-python's Issues

USSD service using Python

Is there any documentation or sample code for implementing USSD using Python? I can only see a PHP example on the website.

Update the file on the website

The Gateway file on the official website is an older version and would give problems to a new user if that was the first place they checked (since it does not support py3).

BAD STATUS LINE

I had raised this issue with your support team but I feel the response was not correct.

The exception is really been caused by bad response from your servers which the AfricasTalking Module should handle If am not wrong and quoting this.

Any gateway errors will be captured by our custom Exception class below,

so wrap the call in a try-catch block

What worries is it does not happen all of the time. Actually we worked around this by waiting for some seconds and sending the payload again if this exemption is raised.

Here is the issue I had filed.

Bug Report

According to your documention this will catch all errors.

Any gateway errors will be captured by our custom Exception class below,

so wrap the call in a try-catch block

try:
    # Thats it, hit send and we'll take care of the rest.
    
    results = gateway.sendMessage(to, message)
    
    for recipient in results:
        # status is either "Success" or "error message"
        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)

However if am not lost a custom exception will only capture exceptions of its type hence this BAD REQUEST EXCEPTION WILL BE IGNORED by this AfricasTalkingGatewayException.

proof:

try this

class AfricasTalkingGatewayException(Exception):
pass

def bug():
try:
12/0
except AfricasTalking as e:
print("Code will not reach here. Exception will not be caught")

I raised this because it got us in trouble though not serious.

Python 3 Support?

Does this library support Python 3?
Tried to import the library in python 3 script using pip and it through a syntax error due to the print statements without parentheses.

Failed to connect to voice.sandbox.africastalking.com

Error when testing Voice in a sandbox. Code is directly from the Tutorial docs.
Note: +256123456789 is a registered phone number in my sandbox app.

Code:

import africastalking
import settings

class VOICE:
    def __init__(self):
        # Set app credentials

        # Sandbox
        self.username = settings.AT_USERNAME_DEMO
        self.api_key = settings.AT_TOKEN_DEMO

        # Initialize the SDK
        africastalking.initialize(self.username, self.api_key)
        # Get the voice service
        self.voice = africastalking.Voice

    def call(self):
        # Set your Africa's Talking phone number in international format
        callFrom = "+256123456789"
        # Set the numbers you want to call to in a comma-separated list
        callTo   = ["+256777123456"]
        try:
            # Make the call
            result = self.voice.call(callFrom, callTo)
            print (result)
        except Exception as e:
            print ("Encountered an error while making the call:%s" %str(e))

if __name__ == '__main__':
    VOICE().call()

Output:

Encountered an error while making the call:HTTPSConnectionPool(host='voice.sandbox.africastalking.com', port=443): Max retries exceeded with url: /call (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10c5e3a30>: Failed to establish a new connection: [Errno 60] Operation timed out'))

Python 3.8.5
africastalking 1.2.7

from Token import TokenService, ModuleNotFoundError: No module named 'Token'

Good morning Africastalking.
While following your docs, I did
pip3 install africastalking # python 3.6.x
which printed on console
Requirement already satisfied: africastalking in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages Requirement already satisfied: schema>=0.6.7 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from africastalking) Requirement already satisfied: requests>=v2.18.4 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from africastalking) Requirement already satisfied: certifi>=2017.4.17 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from requests>=v2.18.4->africastalking) Requirement already satisfied: idna<2.7,>=2.5 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from requests>=v2.18.4->africastalking) Requirement already satisfied: urllib3<1.23,>=1.21.1 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from requests>=v2.18.4->africastalking) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages (from requests>=v2.18.4->africastalking)
Running my application from virtualenv afchallege printed
File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/media/jason/challege/prototype/logics/urls.py", line 3, in <module> from logics import views as V File "/media/jason/challege/prototype/logics/views.py", line 16, in <module> from logics.algorithms import assemble_sms File "/media/jason/challege/prototype/logics/algorithms.py", line 8, in <module> File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/africastalking/__init__.py", line 1, in <module> from Token import TokenService ModuleNotFoundError: No module named 'Token'

'Being clueless of what this means', I went back to your site and downloaded AfricasTalkingGateway.py which also didn't spare me. This is what i got on running the app again using Python gateway class above.
execute_from_command_line(sys.argv) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/media/jason/challege/prototype/logics/urls.py", line 3, in <module> from logics import views as V File "/media/jason/challege/prototype/logics/views.py", line 16, in <module> from logics.algorithms import assemble_sms File "/media/jason/challege/prototype/logics/algorithms.py", line 8, in <module> from logics.AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException File "/media/jason/challege/prototype/logics/AfricasTalkingGateway.py", line 592 print "Raw response: " + response ^ SyntaxError: Missing parentheses in call to 'print'
Now I had idea of the bug fix needed, calling print with parentheses. I did fix the bug ad tried again. This run reported :
File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/virtual/.virtualenvs/afchallege/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/media/jason/challege/prototype/logics/urls.py", line 3, in <module> from logics import views as V File "/media/jason/challege/prototype/logics/views.py", line 16, in <module> from logics.algorithms import assemble_sms File "/media/jason/challege/prototype/logics/algorithms.py", line 8, in <module> from logics.AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException File "/media/jason/challege/prototype/logics/AfricasTalkingGateway.py", line 16, in <module> import urllib2 ModuleNotFoundError: No module named 'urllib2'

Kindly check on this. Am inconvenienced.

[BUG]: `getUserData` method is broken.

The getUserData method always returns AfricasTalkingGatewayException.

On further probing, it turns out the method makes a POST requests instead of a GET request to the api endpoint. This is because of how the sendRequest method is implemented.

How to reproduce:

url = 'https://api.africastalking.com/version1/user?username=your-username'
headers = { 'Accept' : 'application/json',  'apikey' : XXXX}
r = requests.post(url, headers)
print(r.status_code) # status code: 405
print(r.test) # text: HTTP method not allowed, supported methods: GET

I apologize I have used requests to reproduce the error instead of the AfricasTalkingGateway class. This because the error gets masked by the AfricasTalkingGatewayException I'm using requests to simulate this line in sendRequest.

Changing the http method from POST to GET fixes this:

url = 'https://api.africastalking.com/version1/user?username=your-username'
headers = { 'Accept' : 'application/json',  'apikey' : XXXX}
r = requests.get(url, headers)
print(r.status_code) # status code: 200
print(r.test) # text:{'UserData': {'balance': 'KES XXX'}}

Support

Hi,

Can the code work with python 3.7

It sure would be nice to be able to send dynamic messages.

Can one send messages to a list of people, but the message being sent be dynamic?

From what I understand, the only way I would be able to do so is by making multiple requests. That is not a good use case for me as I need the response immediately for the tasks being done otherwise I would push the work to a worker.

An example of how it would look is something as follows.

sms.send("Hello {first_name} {lastname}!", [{"first_name": "Grishon", "last_name": "Gikima"}, {"first_name":"Kelvin", "last_name": "Ng'ang'a"}], ["+2547xxxxxx", "+2547xxxxxx"])

AfricasTalkingGateWay

Hi AfricasTalking
I'm unable to use your api key
I get the following error wherever i try to run my script.Kindly help

Traceback (most recent call last):
File "routes.py", line 2, in
from send_message import send_the_message
File "C:\Users\admn\Desktop\Dream_Team\BulkySMS\send_message.py", line 2, in
from africas_talking_api import send_the_sms
File "C:\Users\admn\Desktop\Dream_Team\BulkySMS\africas_talking_api.py", line 1, in
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException
ModuleNotFoundError: No module named 'AfricasTalkingGateway'

ImportError no module token

Python 3 package has an import error.

from Token import TokenService ImportError: No module named 'Token'

Python3 AfricasTalkingGateway.py Changes

AfricastalkingGateway.py Fixes

  • line 227 of AfricasTalkingGateway.py - changed print(response) instead of print response.

  • import urllib2 is depracted in python3. The urllib2 and urllib in python2.x were combined and split across various modules in python3. Instead of:
    import urllib2
    import urllib
    `

For python3:
from urllib.request import Request, urlopen from urllib.parse import urlencode

You can try wrapping it in a try-except block to check for both. e.g
try: from urllib.request import urlopen except: from urllib2 import urlopen
After doing this, it works. Danke!

raised unexpected: AttributeError("'SchemaError' object has no attribute 'message'",)

Steps to reproduce the error

airtime.send(recipients=[{"phoneNumber": "+25472365vG01", "amount": "100", "currency_code":'KES'}])

Expected behaviour

Raise a ValueError

ValueError: Invalid recipients: Or({'phoneNumber': And(<class 'str'>, <function AirtimeServiceWrapper.send.<locals>.<lambda> at 0x7fa7bc06a6a8>), 'amount': And(<class 'str'>, <function AirtimeServiceWrapper.send.<locals>.<lambda> at 0x7fa7bc076d08>)}) did not validate {'phoneNumber': '+25472365vG01', 'amount': 'KES 100'}
Key 'phoneNumber' error:
<lambda>('+25472365vG01') should evaluate to True

Current behavior

raised unexpected: AttributeError("'SchemaError' object has no attribute 'message'",)

Probable Issue

africastalking-python/africastalking/Airtime.py on Line 36

except SchemaError as err:
            raise ValueError('Invalid recipients: ' + err.message)

SchemaError object has no attribute message

Support for Async calls in SMS services

import africastalking

africastalking.initialize(username, api_key)
sms = africastalking.SMS

async def send_message(message, mobile_no):
    response = await (sms.send_async(message, [mobile_no]))
    return response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.