twilio python cannot send dynamic messages - django

i am facing issues regarding sending twilio messages from python back-end code. I am able to send static messages to the phone but when i create dynamic messages the messages is send successfully but not able to received in the device.
customerName = request.data.get('fullName')
phoneNumber = "+91" + request.data.get('phoneNumber')
bodyM = f'Hey {customerName} worth'
print(bodyM)
serializer = UserSerializer(data=data)
if serializer.is_valid():
collection_name.save(data)
message = client.messages.create(to=phoneNumber , from_="+16104865966",
body=bodyM)
Adding code for better understanding of the issue i am facing

Related

update() got an unexpected keyword argument 'status' Deleting Whatsapp Message using Flask twilio

I created a WhatsApp Chatbot using Flask and Twilio. Then I wanted to be able to delete older messages that were already sent and received. I save message IDs in the table so that I should delete them later. On Twilio documentation delete-a-message-resource
They say it is possible to delete them but I am getting the above error
below is the code
select_cur = mysql.connection.cursor()
select_cur.execute(""" select * from message; """)
for row in select_cur.fetchall():
date_diff = datetime.datetime.now()-row[4]
date_diff_minutes = date_diff.total_seconds() / 60
print(date_diff_minutes)
if date_diff_minutes>30:
try:
#client.messages(row[1]).update(body="")
client.messages(row[1]).update(status='canceled')
except Exception as e:
print(e)
select_cur.close()
I tried to update the message ID using an empty body but it doesn't do anything to those older messages.

Django channel consumers of multiple channels send data to websocket clients but all data is sent to lastly connected websocket client

I use django channels 3.0.0 and websocket using angular.
But users connect to django websocket and they are in their own rooms respectively.
And when I want to send the event to connected users outside of consumers, I used the following code.
all_users = list(Member.objects.filter(is_active = True).values_list('id', flat = True))
for user_id in all_users:
async_to_sync(channel_layer.group_send)(
"chat_{}".format(user_id),
{ "type": "tweet_send", "message": "tweet created" }
)
And in consumers.py, my consumer class's chat_message function
async def tweet_send(self, event):
content = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
"type": "MESSAGE",
"data": content
}))
And this "self.send" function is meant to be sent to all connected users respectively, but when I run the code, the all data are sent to only one user who has connected the last time.
I don't know why. If anyone knows the reason, please help me.
This is indeed a bug in version 3.0.0. It was reported and fixed in 3.0.1.

Django ignore 500 errors

I have developed an ecommerce store in Django where I am using twilio sms functionality. Using twilio, sms only sends if number is in proper format and valid.
message = client.messages.create(
body="Dear customer, this is sample msg", to= number, from_= contact )
So I want a way through which if twilio raise an error in sending sms, this errors gets ignore [Don't raise Server Error 500 in prod]. And Website functionality remains normal.
Is there any way to cater it?
To cater such situation, this simply worked:
try:
message = client.messages.create(
body="Dear customer, this is sample msg", to= number, from_= contact )
except Exception as e:
pass

Is there any nicer way to get the full message from gmail with google-api

I'm working on a project where I, among other things, need to read the message in e-mails from my google account. I came up with a solution that works but wonder if there are any simpler ways?
The first part of the code is pretty standard to get access to the mailbox. But I post it so you can see what I did to get it to work.
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET ='A.json'
store =file.Storage('storage.json')
credz=store.get()
flags = tools.argparser.parse_args(args=[])
if not credz or credz.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET,SCOPES)
if flags:
credz = tools.run_flow(flow, store, flags)
GMAIL = build('gmail','v1',http=credz.authorize(Http()))
response = GMAIL.users().messages().list(userId='me',q='').execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
print len(messages)
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId='me', q=query,pageToken=page_token).execute()
messages.extend(response['messages'])
FromMeInd=0
for message in messages:
ReadMessage(GMAIL,'me',message['id'])
It is this part that I'm more interested to imporve. Is there any other way to more directly get the message with python and the gmail-api. I've looked through the api documentation but could not get any more efficient way to read it.
def ReadMessage(service,userID,messID):
message = service.users().messages().get(userId=userID, id=messID,format='full').execute()
decoded=base64.urlsafe_b64decode(message['payload']['body']['data'].encode('ASCII'))
print decoded
You can get the body as raw and then parse it using the standard Python email module
According to the official API: https://developers.google.com/gmail/api/v1/reference/users/messages/get:
import email
message = service.users().messages().get(userId='me', id=msg_id,
format='raw').execute()
print 'Message snippet: %s' % message['snippet']
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(msg_str)
You'll get a mime message with a payload containing mime parts, e.g. plain text, HTML, quoted printable, attachments, etc.

AppFabric Topic Subscription

I am trying to assemble a simple AppFabric Topic whereby messages are sent and received using the SessionId. The code does not abort, but brokeredMessage is always null. Here is the code:
// BTW, the topic already exists
var messagingFactory = MessagingFactory.Create(uri, credentials);
var topicClient = messagingFactory.CreateTopicClient(topicName);
var sender = topicClient.CreateSender();
var message = BrokeredMessage.CreateMessage("Top of the day!");
message.SessionId = "1";
sender.Send(message);
var subscription = topic.AddSubscription("1", new SubscriptionDescription { RequiresSession = true});
var mikeSubscriptionClient = messagingFactory.CreateSubscriptionClient(subscription);
var receiver = mikeSubscriptionClient.AcceptSessionReceiver("1");
BrokeredMessage brokeredMessage;
receiver.TryReceive(TimeSpan.FromMinutes(1), out brokeredMessage); // brokeredMessage always null
You have two problems in your code:
You create a subscription AFTER you send the message. You need to create a subscription before sending, because a subscription tells the topic to, in a sense, copy, the message to several different "buckets".
You are using TryReceive but are not checking for its result. It returns true, if a message was received, and false if not (e.g. Timeout has occured).
I am writing my sample application and will post it on our blog today. I will post the link here as well. But until then, move the subscription logic to before sending the message, and the receiver after it and you will start seeing results.
Update:
As promised, here is the link to my blog post on getting started with AppFabric Queues, Topics, Subscriptions.