def _makeVoiceMessage(self, message, TO_NUMBER): # Makes a Voice Message # https://developers.messagebird.com/api/voice-messaging#send-a-voice-message # Prepare Args to send on a Voice Message voiceMessage = self._makeVoiceMessagePayload(message, TO_NUMBER) # DEBUGGING LOG.debug('Messagebird: Voice Message format {}'.format(voiceMessage)) # Make a Voice Message try: client = messagebird.Client(MB_APIKEY) voice_message = client.voice_message_create(**voiceMessage) # DEBUGGING LOG.debug('Messagebird: Voice Call information {}'.format( voiceMessage)) # For TESTING except messagebird.client.ErrorException as e: LOG.error('An error occurred while creating a Voice_Call:') for error in e.errors: LOG.error('code: {!s} | description:{!s}'.format( error.code, error.description))
def main(): load = load_config() for i in range(len(load['accounts'])): config = init_config(i) if not config: return logging.info("Checking %s server: USERNAME %s." % (config.auth_service, config.username)) try: if config.auth_service == 'cam': mail = imaplib.IMAP4_SSL('imap.hermes.cam.ac.uk', 993) else: mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login(config.username, config.password) # Out: list of "folders" aka labels in gmail. mail.select("inbox", readonly=True) # connect to inbox. date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%b-%Y") senderList = config.mybosses for sender in senderList: result, data = mail.uid( 'search', None, '(UNSEEN SENTSINCE {date} FROM {sender})'.format( date=date, sender=sender)) if len(data[0]) > 0: print data[0] latest_email_uid = data[0].split()[-1] result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') raw_email = data[0][1] # including headers and alternate payloads email_message = email.message_from_string(raw_email) boss = email.utils.parseaddr(email_message['From']) voicemessage = "You received an email from %s, %s" % ( boss[0], boss[1]) logging.info(voicemessage) client = messagebird.Client(config.messagebird_secret) for number in config.phonenumbers: message = client.voice_message_create( number, ' '.join([config.greetings, voicemessage]), { 'language': 'en-gb', 'voice': 'male' }) # you can overwrite the setting for message and voice. For details, please refer to # https://developers.messagebird.com/docs/voice logging.info("Check completed. No important email found.") except Exception as e: logging.error("Error in %s", e) pass
def unmatch_numbers(masked_receiver, sender): # Query database for sender conversations current_conversations = get_user(sender)["conversations"] # Get masked sender and real recipient masked_sender = current_conversations[masked_receiver]["masked_sender"] receiver = current_conversations[masked_receiver]["real_receiver"] # Update Conversations on Sender del current_conversations[masked_receiver] #TODO: Add Put of Current Conversations get_db().update_item( Key={"phonenumber": sender}, UpdateExpression='SET conversations = :new', ExpressionAttributeValues={':new': {current_conversations}}) # Query and Update Conversations on Receiver current_conversations = get_user(sender)[receiver]["conversations"] del current_conversations[masked_sender] # Add Put of Current Conversations on Database get_db().update_item( Key={"phonenumber": sender}, UpdateExpression='SET conversations = :new', ExpressionAttributeValues={':new': {current_conversations}}) client = messagebird.Client(PROD_ACCESS_KEY) client.message_create(masked_receiver, sender, "uandi - Your conversation has ended.", {}) client.message_create(masked_sender, receiver, "uandi - Your conversation has ended.", {})
def _makeCall(self, message, TO_NUMBER): # Not used for now # Makes a Voice Call # Instead we use Voice Message # https://developers.messagebird.com/api/voice-calling#calls callMessage = self._makeCallPayload(message, TO_NUMBER) try: client = messagebird.Client(MB_APIKEY) call = client.call_create(**callMessage) # DEBUGGING #LOG.debug('Messagebird: Information was returned as a {!r} object '.format(call)) # For TESTING """ info = "id: {id!r} | status: {status!r} | source: {source!r} | destination: {destination!r}" LOG.debug(info.format(id = call.data.id, status = call.data.status, source = call.data.source, destination = call.data.destination)) # For TESTING """ except messagebird.client.ErrorException as e: LOG.error('An error occurred while creating a call:') for error in e.errors: LOG.error('\tcode\t: {!s}\n\tdescription :\t{!s}'.format( error.code, error.description))
def inbound_sms(): # Get message from request message = app.current_request.json_body # Get real sender and masked recipient sender = message['originator'] masked_receiver = message['recipient'] if sender[0] != '+': sender = '+' + sender if masked_receiver[0] != '+': masked_receiver = '+' + masked_receiver # Message Content content = message['body'] if 'ENDCONVO' in content: unmatch_numbers(masked_receiver, sender) return # Query database for sender conversations # TODO: Create actual DB connection current_conversations = get_user(sender)["conversations"] # Get masked sender and real recipient masked_sender = current_conversations[masked_receiver]["masked_sender"] receiver = current_conversations[masked_receiver]["real_receiver"] print(receiver) client = messagebird.Client(PROD_ACCESS_KEY) result = client.message_create(masked_sender, receiver, content, {}) return {'status': 'success'}
def get_service(hass, config, discovery_info=None): """Get the MessageBird notification service.""" client = messagebird.Client(config[CONF_API_KEY]) try: # validates the api key client.balance() except messagebird.client.ErrorException: _LOGGER.error("The specified MessageBird API key is invalid") return None return MessageBirdNotificationService(config.get(CONF_SENDER), client)
def send_sms(title, price): client = messagebird.Client(api_key) try: msg = client.message_create( phone_number, phone_number, f'Hello Ludvig, the {title} is ready to be bought! the price is {price}' ) print(msg.__dict__) print('sms sent') except messagebird.client.ErrorException as e: for error in e.errors: print(error)
def send_message(message="test_message"): logger.info(f"Sending message: {message}") client = messagebird.Client(str(os.environ.get("MESSAGEBIRD_CLIENT"))) try: msg = client.message_create( str(os.environ.get("MESSAGEBIRD_ORIGINATOR")), str(os.environ.get("MESSAGEBIRD_DESTINATION")), message, ) except messagebird.client.ErrorException as e: for error in e.errors: logger.debug(error)
def _deliver_token(self, token): self._validate_config() client = messagebird.Client(settings.OTP_MESSAGEBIRD_ACCESS_KEY) try: client.message_create( originator=settings.OTP_MESSAGEBIRD_FROM, recipients=self.number.replace("+", ""), body=str(token), ) except messagebird.client.ErrorException as e: logger.exception("Error sending token by MessageBird SMS: {0}".format(e)) raise
def get(self, request, format=None): """ Send a message via MessagBird and return the status. """ self.user = EmergencyButtonClient.objects.first() current_time = datetime.datetime.now().time() family_members = FamilyMember.objects.filter(emergency_button_client=self.user) schedules = Schedule.objects.filter(family_member__in=family_members, start__lte=current_time, end__gte=current_time) recipients = [] for schedule in schedules: recipients.append(schedule.family_member.phone_number) if not len(recipients): raise NotFound # get lat long, randomize a little bit for demo purpose # lat = float(request.data.get('lat', 52.3862755)) + random.randint(-10, 10) * 0.0001 # long = float(request.data.get('long', 4.8728798)) + random.randint(-10, 10) * 0.0001 lat = 52.3862755 long = 4.8728798 self.coordinates = (lat, long) api_token = 'RTDWFuAIoGzINuBTRDl5uDOiO' client = messagebird.Client(api_token) # sent text message text_message = self._create_text_message() client.message_create( 'MessageBird', recipients, text_message, {'reference': 'quicklypress'}, ) # sent voice message voice_message = self._create_voice_message() client.voice_message_create( recipients, voice_message, {'language': 'en-gb', 'voice': 'female'}, ) return Response({'status': 'success'}, status=200)
def webhook(): client = messagebird.Client('NKLuEuNHL8H6uvFZreyIAkt1C', features=[messagebird.Feature.ENABLE_CONVERSATIONS_API_WHATSAPP_SANDBOX]) balance = client.balance() print('Your balance:\n') print(' amount : %d' % balance.amount) print(' type : %s' % balance.type) print(' payment : %s\n' % balance.payment) message = client.conversation_create_message(conversation.id, { 'channelId': 'a84cb9c1-674b-4784-be79-76d9ceb43ba0', 'type': 'text', 'content': { 'text': balance.type } }) return message
def send_message(self, message, sender, role): self.clean_last_messages() returnval = True message = sender + ": " + message if (not self.is_recent_duplicate(message)): client = messagebird.Client(self.apikey) phones = self.phoneParser.get_current_phones() phonenumber = phones[role] ## FETCH ROLE INFO msg = client.message_create(self.notifier, phonenumber, message) logging.info("Will not send duplicate message received from " + sender + ": " + message) logging.debug(self.debug_message(msg)) else: returnval = False logging.warning("Will not send duplicate message received from " + sender + ": " + message) return returnval
def __init__(self, fail_silently: bool = False, **kwargs) -> None: super().__init__(fail_silently=fail_silently, **kwargs) if not HAS_MESSAGEBIRD and not self.fail_silently: raise ImproperlyConfigured( "You're using the SMS backend " "'sms.backends.messagebird.SmsBackend' without having " "'messagebird' installed. Install 'messagebird' or use " "another SMS backend.") access_key: Optional[str] = getattr(settings, 'MESSAGEBIRD_ACCESS_KEY') if not access_key and not self.fail_silently: raise ImproperlyConfigured( "You're using the SMS backend " "'sms.backends.messagebird.SmsBackend' without having the " "setting 'MESSAGEBIRD_ACCESS_KEY' set.") self.client = None if HAS_MESSAGEBIRD: self.client = messagebird.Client(access_key)
def _makeSMS(self, message, TO_NUMBER): # Send a SMS # https://developers.messagebird.com/api/sms-messaging#send-outbound-sms smsMessage = self._makeSMSPayload(message, TO_NUMBER) try: client = messagebird.Client(MB_APIKEY) sms = client.message_create(**smsMessage) # DEBUGGING LOG.debug('Messagebird: SMS information {!r}'.format( smsMessage)) # For TESTING except messagebird.client.ErrorException as e: LOG.error('An error occurred while creating a sms:') for error in e.errors: LOG.error('\tcode\t: {!s}\n\tdescription :\t{!s}'.format( error.code, error.description))
def post(self, request, pk, *args, **kwargs): kuser = self.get_object(pk=pk) # Ensure that the user has a phone number, and has enabled # two-factor-auth error_msg = None if not hasattr(kuser, 'phone_num'): error_msg = 'user {} has no attribute `phone_num`.'.format( kuser.pk) if kuser.tfa_enabled is False: error_msg = 'user {} does not have two-factor authentication ' \ 'enabled.'.format(kuser.pk) if error_msg: user_exc = APIException(detail={'error': error_msg}) user_exc.status_code = 403 raise user_exc # Generate a two-factor auth code. tfa_code = self._generate_tfa_code() # Send an SMS message to the user's phone. client = messagebird.Client(settings.MESSAGEBIRD_ACCESS_KEY) try: message = client.message_create( originator=settings.MESSAGEBIRD_SENDER, recipients=kuser.phone_num, body=tfa_code, ) except messagebird.client.ErrorException as e: sms_exc = APIException( detail={'error': 'the SMS message failed to send.'}) sms_exc.status_code = 403 raise sms_exc # Set the user's TFA code, and reset its validation status. kuser.tfa_code = tfa_code kuser._tfa_code_validated = False kuser.save() return Response({'success': True}, status=status.HTTP_201_CREATED)
def emergency(): if "email" in session: email = session["email"] email_object = records.find_one({"email": email}) name = email_object["name"] #Get Link to Location using GeoLocation if no gps, uses IP link = "http://www.google.com/maps/place/" + lat + "," + log # Sending a call on a helpline number and leaving voice message client = messagebird.Client(credentials.CALL_API) try: voice_message = "I am " + name + ' It is Emergency, Help immediately' + " check my location on sms" msg = client.voice_message_create(credentials.Helpline_no, voice_message, {'voice': 'female'}) except messagebird.client.ErrorException as e: for error in e.errors: print(error) # Get Trusted Emails and Send an Email with Location list_emails = email_object["user_emails"].split(',') for contacts in list_emails: mail.send_email(name, contacts, link) #Sending SMS to stored contacts but since Testing API Key available only to your own number for now list_phones = email_object["user_phones"].split(',') for contacts in list_phones: try: message = "I am " + name + ' It is Emergency, Help immediately ' + " check my location- " + link msg = client.message_create(name, contacts, message) print(msg.__dict__) except messagebird.client.ErrorException as e: for error in e.errors: print(error) #SEE YOUR OWN LOCATION return render_template('Location.html')
def _deliver_token(self, token): self._validate_config() # If pure numeric token, split into separate numbers to improve the way it # sounds on the phone and repeat it twice in case the user missed it if token.isnumeric(): token = ", ".join(token) \ + '<break time="2s"/>' \ + ", ".join(token) \ + '<break time="2s"/>' \ + ", ".join(token) client = messagebird.Client(settings.OTP_MESSAGEBIRD_ACCESS_KEY) try: client.voice_message_create( recipients=self.number.replace("+", ""), body=str(token), params={"language": self.language}, ) except messagebird.client.ErrorException as e: logger.exception("Error sending token by MessageBird Voice: {0}".format(e)) raise
def get_service(hass, config): """Get the MessageBird notification service.""" import messagebird if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_API_KEY]}, _LOGGER): return None sender = config.get(CONF_SENDER, 'HA') if not is_valid_sender(sender): _LOGGER.error('Sender is invalid: It must be a phone number or ' 'a string not longer than 11 characters.') return None client = messagebird.Client(config[CONF_API_KEY]) try: # validates the api key client.balance() except messagebird.client.ErrorException: _LOGGER.error('The specified MessageBird API key is invalid.') return None return MessageBirdNotificationService(sender, client)
def sendSingleMessage(message, phoneNumber, blacklist="user_data/blacklist.txt"): """ Send the message {message} to the number {phoneNumber} If the number is in the blacklist, don't send the message """ black_list = open(blacklist, "r") black_listed_nums = black_list.readlines() for number in black_listed_nums: if phoneNumber in number or number in phoneNumber: print("Sorry, the number: {} is in the black list.".format(phoneNumber)) return print("Sending \"{}\" to {}".format(message, phoneNumber)) try: client = messagebird.Client(c.API_KEY) # send the message client.message_create('FromMe', phoneNumber, message, {'reference':'Foobar'}) except messagebird.client.ErrorException as err: print("An error occured while requesting a Message object.\n") for error in err.errors: print("Error:\nCode : {}".format(error.code)) print("Description: {}".format(error.description)) print("Parameter : {}\n".format(error.parameter))
def send_sms_to_user(user, answer): client = messagebird.Client(os.getenv('MBIRD')) try: # Fetch the Balance object. balance = client.balance() logger.info(' amount : %s' % balance.amount) msg = client.message_create('12028525940', user, answer) # Print the object information. logger.info('\nThe following information was returned as a Message object:\n') logger.info(' id : %s' % msg.id) logger.info(' href : %s' % msg.href) logger.info(' direction : %s' % msg.direction) logger.info(' type : %s' % msg.type) logger.info(' originator : %s' % msg.originator) except messagebird.client.ErrorException as e: logger.info('\nAn error occured while requesting a Message object:\n') for error in e.errors: logger.info(' code : %d' % error.code) logger.info(' description : %s' % error.description) logger.info(' parameter : %s\n' % error.parameter)
) # results = [phone.split('57')[-1] for (phone,) in cursor.fetchall()] results = [phone for (phone, ) in cursor.fetchall()] cursor.close() return results def send_sms(conn, client, phone): try: client.message_create('MessageBird', '+' + phone, os.getenv('MESSAGE_BODY')) cursor = conn.cursor() cursor.execute("UPDATE contacts SET sent = TRUE WHERE phone like ?", (phone, )) conn.commit() print('sms sent') except messagebird.client.ErrorException as e: print(e) print('Error sending the sms') if __name__ == '__main__': conn = sqlite3.connect('contacts.db', timeout=10) contacts = fetch_contacts(conn) key = os.getenv('MESSAGEBIRD_ACCESS_KEY') client = messagebird.Client(key) for contact in contacts: print(contact) send_sms(conn, client, contact)
#!/usr/bin/env python import argparse import messagebird parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) parser.add_argument('--webhookId', help='webhook that you want to update', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhook = client.voice_delete_webhook(args['webhookId']) # Print the object information. print('Webhook has been deleted') except messagebird.client.ErrorException as e: print('An error occured while deleting a Voice Webhook object:') for error in e.errors: print(' code : {}'.format(error.code)) print(' description : {}'.format(error.description)) print(' parameter : {}\n'.format(error.parameter))
def __init__(self, api_key, originator="ICUBAM"): self._api_key = api_key self._originator = originator self._client = messagebird.Client(api_key)
#!/usr/bin/env python import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import messagebird ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM' try: # Create a MessageBird client with the specified ACCESS_KEY. client = messagebird.Client(ACCESS_KEY) # Fetch the Balance object. balance = client.balance() # Print the object information. print('\nThe following information was returned as a Balance object:\n') print(' amount : %d' % balance.amount) print(' type : %s' % balance.type) print(' payment : %s\n' % balance.payment) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Balance object:\n') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
def send_call(src: str, dst: str, text: str, key: str): if (isInt(src)): src = fix_number(src) dst = fix_number(dst) if (isInt(src)): tempSrc = src[2:] else: tempSrc = src if (isInt(dst)): tempDst = dst[2:] else: tempDst = dst if (tempSrc.lower() in blocked_senders): if (isInt(src)): return format_number(src) + " is blocked from making calls." else: return src + " is blocked from making calls." if (tempDst.lower() in blocked_receivers): if (isInt(dst)): return format_number(dst) + " is blocked from receiving calls." else: return dst + " is blocked from receiving calls." if (len(dst) != 10): return "Destination number is not 8 numbers long." if (isInt(dst) == False): return "Destination number must be a number." if (len(src) != 10): return "Source number is not 8 numbers long." if (isInt(src) == False): return "Source number must be a number." if (len(text) == 0 or len(text) > 606): return "Message either too small or too long." if (key != None and len(key) == 0): return "No key entered." keys = redis.lrange("sms_keys", 0, -1) if (str(key).encode() in keys or key == None or DEBUG): if (DEBUG == False): try: call_obj = call_client.voice_message_create( [dst], text, params={ "originator": src, "language": alternative_country_code }) if (str(key).encode() in keys): redis.lrem("sms_keys", 0, key) sendLog( "From > " + str(src) + " to > " + str(dst)[2:] + " key > " + str(key) + " text > " + str(text) + " type > call", True) return call_obj except messagebird.ErrorException: return False else: try: print("Debug on: " + "From > " + str(src) + " to > " + str(dst)[2:] + " key > " + str(key) + " text > " + str(text)) call_client_testkey = messagebird.Client(message_testkey) call_obj = call_client_testkey.voice_message_create( [dst], text, params={ "originator": src, "language": alternative_country_code }) sendLog( "From > " + str(src) + " to > " + str(dst)[2:] + " key > " + str(key) + " text > " + str(text) + " type > call", True) return call_obj except messagebird.ErrorException: return False else: time.sleep(1) sendLog(f"Tried to use key that does not exist ({key})", True) return "Key does not exist or is already used."
"112", "114", "1813", "88888888", "40611950", "59456000" ] # Choose receivers which are blocked from being used on the site country_code = "45" # Country code alternative_country_code = "da-dk" formatter = phonenumbers.AsYouTypeFormatter("DA") DEBUG = False # Enable debug mode. No messages will actually be send in this mode but will simulate receipts for messages. #--- This is the actual code under this ---# load_dotenv() message_testkey = getenv("mbird_testkey") logkey = getenv("logkey") app = Flask(__name__) auth = HTTPBasicAuth() secret = getenv("secret") key = getenv("key") message_bird_livekey = getenv("messagebirdkey") call_client = messagebird.Client(message_bird_livekey) client = nexmo.Client(key=key, secret=secret) if (getenv('REDIS_URL') == None or message_bird_livekey == None or secret == None or key == None or logkey == None): print("Error state - " + str( getenv('REDIS_URL') == None or message_bird_livekey == None or secret == None or key == None or logkey == None)) @app.route('/') @app.route('/<path:path>') def catch_all(path): return render_template( "showtext.html", title="Error!", text="This project has not been setup correctly and is not working." )
return '' def trigger(self, *args, **kwargs): pass def trigger_batch(self, *args, **kwargs): pass pusher_client = PusherMock() def africas_talking_launcher(): africastalking.initialize(config.AT_USERNAME, config.AT_API_KEY) return africastalking.SMS twilio_client = none_if_exception(lambda: TwilioClient(config.TWILIO_SID, config.TWILIO_TOKEN)) messagebird_client = none_if_exception(lambda: messagebird.Client(config.MESSAGEBIRD_KEY)) africastalking_client = none_if_exception(africas_talking_launcher) from server.utils.blockchain_tasks import BlockchainTasker bt = BlockchainTasker() from server.utils.misc_tasks import MiscTasker mt = MiscTasker() from server.utils.ussd.ussd_tasks import UssdTasker ussd_tasker = UssdTasker() ge_w3 = Web3(HTTPProvider(config.GE_HTTP_PROVIDER))
def __init__(self, config): super().__init__(config) self._api_key = self.config.MB_KEY self._client = messagebird.Client(self._api_key)
from flask import Flask, render_template, request, flash, url_for, redirect #imports the two forms we have defined in forms.py from forms import SubmitPhoneNumber, EnterCode import messagebird #Configure the app as follows. app = Flask(__name__) app.config.from_pyfile('config_file.cfg') #create instance of messagebird.Client using API key client = messagebird.Client(app.config['SECRET_KEY']) #What happens when the user submits their phone number @app.route('/', methods=['GET', 'POST']) def submitPhone(): initial_form = SubmitPhoneNumber(request.form) code_form = EnterCode() #when form is posted, try to obtain server response if request.method=="POST": try: verify = client.verify_create(initial_form.number.data, {'type':'tts', 'template': 'Your security code is %token.'}) #on success we render verify.id on the hidden field on the verification page (/EnterCode) return redirect(url_for('enterCode', code_form=code_form, verify_id=verify.id)) #on failure, render description for error on same page. except messagebird.client.ErrorException as e: for error in e.errors: flash(' description : %s\n' % error.description)
def trigger(self, *args, **kwargs): pass def trigger_batch(self, *args, **kwargs): pass pusher_client = PusherMock() def africas_talking_launcher(): africastalking.initialize(config.AT_USERNAME, config.AT_API_KEY) return africastalking.SMS twilio_client = none_if_exception( lambda: TwilioClient(config.TWILIO_SID, config.TWILIO_TOKEN)) messagebird_client = none_if_exception( lambda: messagebird.Client(config.MESSAGEBIRD_KEY)) africastalking_client = none_if_exception(africas_talking_launcher) from server.utils.blockchain_tasks import BlockchainTasker bt = BlockchainTasker() from server.utils.misc_tasks import MiscTasker mt = MiscTasker() from server.utils.ussd.ussd_tasks import UssdTasker ussd_tasker = UssdTasker()