SNS publish to topic with phone number is not working - amazon-web-services

I have boto3 code that creates a topic and creates a subscription to that topic and publishes the message to the topic.
The code was working fine. I tried to add a US number to the mix of Indian phone number subscribed group and everything went south. I don't get any errors all the responses are successful but I don't receive any messages.
Then I tried with normal console publish a message, even the console publish is not working.
TO cross-verify it the issue was with the region I tried publishing in us-east-1 and all worked fine.
Here is my code:
def lambda_handler(event, context):
sns = boto3.client("sns")
number = ['+91xxxxxxxx','+1xxxxxxxxxxxx','+91xxxxxxxxxx']
response = sns.create_topic(
Name='loadeo-demo',
Attributes={
}
)
arn = response['TopicArn']
print ("arn: " + arn)
for phno in number:
response = sns.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint=phno,
Attributes={
},
ReturnSubscriptionArn=False
)
# print(response)
response = sns.list_subscriptions_by_topic(
TopicArn=arn
)
print (response)
response = sns.publish(
topicArn=arn,
Message="A Load of your interest has been placed.\n" + "Please visit the web for more details.\n" + "Thank you",
)

Related

AWS SES python sqs.receive_message returning only one message output

I am using amazon ses python sdk to see how many messages are there in the queue for a given queue URL. in amazon GUI console i can see there are 3 messages within the queue for the queue URL. However i do not get more than 1 message as output everytime i run the command. Below is my code
import boto3
import json
from botocore.exceptions import ClientError
def GetSecretKeyAndAccesskey():
#code to pull secretkey and access key
return(aws_access_key,aws_secret_key)
# Create SQS client
aws_access_key_id,aws_secret_access_key = GetSecretKeyAndAccesskey()
sqs = boto3.client('sqs',aws_access_key_id=str(aws_access_key_id),aws_secret_access_key=str(aws_secret_access_key) ,region_name='eu-west-1')
response = sqs.receive_message(
QueueUrl='my_queue_url',
AttributeNames=[
'All',
],
MaxNumberOfMessages=10,
)
print(response["Messages"][0])
Every time i run the code i get a different message id, and if i change my print code to check for the next list i get list index out of bound meaning that there is only one message
print(response["Messages"][1])
C:\>python testing.py
d4e57e1d-db62-4fc5-8233-c5576cb2603d
C:\>python testing.py
857858e9-55dc-4d23-aead-3c6622feccc5
First, you need to add "WaitTimeSeconds" to turn on long polling and collect more messages during a single connection.
The other issue is that if you only put 3 messages on the queue, they get separated on the backend systems as part of the redundancy of the AWS SQS service. So when you call to SQS, it connects you to one of the systems and delivers the single message that's available. If you increase the number of total messages, you'll get more messages per request.
I wrote this code to demonstrate the functionality of SQS and allow you to play around with the concept and test.
import json
session = boto3.Session(region_name="us-east-2", profile_name="dev")
sqs = session.client('sqs')
def get_message():
response = sqs.receive_message(QueueUrl='test-queue', MaxNumberOfMessages=10, WaitTimeSeconds=10)
return len(response["Messages"])
def put_messages(seed):
for message_number in range(seed):
body = {"test": "message {}".format(message_number)}
sqs.send_message(QueueUrl='test-queue', MessageBody=json.dumps(body))
if __name__ == '__main__':
put_messages(2)
print(get_message())

AWS Lambda, SNS and Python - "Missing final '#domain'"

I am trying to send SNS messages for old AWS access keys, but am getting the below error:
Response
null
Function Logs
START RequestId: a266bda6-2d17-4c24-a6d3-a0a05180025b Version: $LATEST
[ERROR] 2021-03-17T15:48:33.592Z a266bda6-2d17-4c24-a6d3-a0a05180025b Missing final '#domain'
I have tried Googling a bit, and the IAM user accounts are NOT email addresses - just people's first names. The SNS subscriber is already setup, so I'm not sure why it would care to know a user's email address.
Any ideas?
Python Script below:
import boto3, json, time, datetime, sys, re
iam_client = boto3.client('iam')
sns_client = boto3.client('sns')
users = iam_client.list_users()
user_list = []
for key in users['Users']:
user_list = key['UserName']
accesskeys = iam_client.list_access_keys(UserName=key['UserName'])
for items in user_list.split('\n'):
for key in accesskeys['AccessKeyMetadata']:
accesskeydate = accesskeys['AccessKeyMetadata'][0]['CreateDate']
accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
active_days = (currentd - accesskeyd)/60/60/24
message = (key['UserName'],int(round(active_days))),
message = re.sub(r'[^a-zA-Z0-9 ]', "", str(message))
message = re.sub(r' ', ' is ', str(message))
if active_days >= 1:
sns_client.publish(
TopicArn='<redacted SNS topic>',
Subject='User with Old Access Key Detected',
Message="The access key for " + str(message) + " days old. This user access key should be replaced ASAP.",
if active_days >= 1:
sns_client.publish(
TopicArn='<redacted SNS topic>',
Subject='User with Old Access Key Detected',
For Publishing the message you don't need Subject. You can send message as described as here
SNS Publish API Call
Subject
Optional parameter to be used as the "Subject" line when the message is delivered to email endpoints. This field will also be included, if present, in the standard JSON messages delivered to other endpoints.
To publish a message to a topic, we simply call the publish() function, passing the topic’s ARN, the desired message, and optionally a subject (it will only be used in email messages).
aws examples for sns operations using boto3

AWS SES failing with "Recipient count exceeds 50." on individual recipient emails

We are looping on 160 email addresses in AWS Lambda and calling SES' send_raw_email() API call with one address per call. After 50 loops we get the error "Recipient count exceeds 50." but there is only one recipient per call. The other information in the emails, other than "To:", are the same between calls. We do this to keep recipients from seeing the addresses of other recipients.
Are the emails being batched at SES? (How are we even hitting this limit?)
How can we get past this error?
Adding code:
for item in recipients['Items']:
RECIPIENT = item['email']['S']
msg['To'] = RECIPIENT
try:
#Provide the contents of the email.
response = ses.send_raw_email(
Source=SENDER,
Destinations=[
RECIPIENT
],
RawMessage={
'Data':msg.as_string(),
}
)
# Display an error if something goes wrong.
except ClientError as e:
print("failed to send email: ",e.response['Error']['Message'])
return {
'statusCode': 400,
'body': json.dumps(e.response['Error']['Message'])
}
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
The issue was that the library operates by adding to the "To" list when assigning, not replacing. So a "del msg['To']" was needed.
for item in recipients['Items']:
RECIPIENT = item['email']['S']
del msg['To']
msg['To'] = RECIPIENT
...

AWS SNS Endpoint not sending sms after 9 pm IST

I am using AWS SDK to send the sms to the mobile number for sending OTP through the SMS.
The Issue here I am facing is the SMS are only being sent during the day time according to Indian Standard Time (9 am to 9pm). If I try to send SMS request to the AWS SNS endpoint after 9 pm, then it will send the message after 9 am the next day.
The code is as below.
String ACCESS_KEY = env.getProperty("aws.access.key");
String SECRET_KEY = env.getProperty("aws.secret.access.key");
// Above we get the access and secret access key as credentials for the user.
String otp = getRandomNumberString(); // generates an OTP number of 4 digit
AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(ACCESS_KEY,
SECRET_KEY));
String message = "Your Connect OTP for Login/Signup is: " + otp
+ ".\nNote: Please DO NOT SHARE THIS OTP with anyone.\nThanks";
String phoneNumber = "+91" + String.valueOf(mobile); // Ex: +91XXX4374XX
String messageID = sendSMSMessage(snsClient, message, phoneNumber);
// The definition of method named "sendSMSMessage" as above is written below in next code block
//definition of method named "sendSMSMessage"
public static String sendSMSMessage(AmazonSNSClient snsClient, String message, String phoneNumber) {
PublishResult result = snsClient
.publish(new PublishRequest().withMessage(message).withPhoneNumber(phoneNumber));
return result.getMessageId();
}
There are two types of SMS that you can send.
-Promotional Messages
-Transaction Messages
Promotional messages are like Advertisment. These Messges will not be delivered to DND numbers and also these messages can only be delivered between 9Am to 9PM as per NCPR guidelines.
Transaction Messages are sent for Transaction purpose like sending OTP and sending Payment confirmation. These messages can be delivered to any number 24/7.
So the problem is you need to change your SMS type to Transaction SMS

boto3 - aws sns - specify Sender ID

The following code works to send a message but when it arrives, it displays the text 'VERIFY' for a sender id. How do I specific a sender ID? I think it's done with the message attributes but I cannot figure out the syntax.
session = boto3.session.Session(profile_name='Credentials',region_name='us-east-1')
theMessage='Now is the time for all good people to come to the aid of their party'
senderID='Godzilla'
snsclient = session.client('sns')
response = snsclient.publish(PhoneNumber='+84932575571', Message=theMessage)
pp = pprint.PrettyPrinter(indent=4)
print(pp.pprint(response))
Add a third parameter MessageAttributes to the publish method.
snsclient.publish(PhoneNumber='+84932575571', Message=theMessage,MessageAttributes={
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': 'Godzilla'
}})
The sender id is not supported in many countries. see AWS SNS SMS SenderId Supported Countries