Receiving an SMS with Azure Communication Services using python - python

Trying to understand how to receive an SMS in python using ACS.
ACS is able to send and receive messages according to their own page.
I've already managed to send a message. I sent a msg from my phone number to a public free phone on the page https://www.receivesms.co/
The code I used to send an msg is the following:
from azure.communication.sms import SmsClient
sms_client = SmsClient.from_connection_string("my_secret")
def send_message(sms_client, text):
sms_responses = sms_client.send(
from_="my_number",
to=["receiving_mumber"],
message=text,
enable_delivery_report=True,
tag="custom-tag",
)
print("sent!")
try:
send_message(sms_client, "Random msg")
except Exception as ex:
print("Exception:")
print(ex)
This was fairly simple because of the instructions on the ACS website however I haven't managed to find any info on how to receive an SMS using python.
Or how do receive incoming texts in python, is it even possible?
EDIT 1: As much as I've researched and found there is no specific way to work with received SMS directly through any programming language.

Related

Google's "Unusual Traffic" Error When Send The Same Google Link In Python Request Library

I'm Coding an Assistant with Python. And There Is A Section In The User Interface Of This Assistant Indicating The Location:
def get_location_for_gui():
try:
web_site = "https://www.google.com/search?q=my+location"
web_site_html = requests.get(web_site, headers=headers)
web_site_regular_html = BeautifulSoup(web_site_html.text, "html.parser")
web_site_html.close()
global country_location
global city_location
country_location = web_site_regular_html.find("span", attrs={"class": "Q8LRLc"}).text
city_location = web_site_regular_html.find("span", attrs={"class": "dfB0uf"}).text
location_label.configure(text=f"Location: {city_location}, {country_location}")
location_label.after(360000, get_location_for_gui)
except Exception as error:
print(error)
print("An Error Has Been Detected. Please Restart The App.")
That's why every time I launch the Assistant, it sends a request to Google via the same link. After a while I started to get the following error by google:
"Our systems have detected unusual traffic from your computer network. This page checks to see if it's really you sending the requests, and not a robot."
I will publish this application when it is ready and I do not want downloaders to deal with this error. Even though I verify, people who download will not deal with this error and will delete my application. So I Want A Method That I Won't Get This Error Without Verifying. Please Help Me!

How to get (feedback)acknowledgments for messages sent to a device from IoT Hub in python?

I am able to send messages and reported-properties from iot hub to a simulated device through azure-iot-sdk-python.
Now i wanna get acknowledgments (success,expired,rejected,purjed,DeliveryCountexceeded) for messages sent to the device/module from IoT Hub
ServiceClient.GetFeedbackReceiver method is available for .Net but i am not able to find a python sdk for getting message delivery feedback.
below is code used for sending c2d message
from azure.iot.hub import IoTHubRegistryManager
CONNECTION_STRING = ""
DEVICE_ID = ""
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
data = "Hello.. message from cloud"
props={}
registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
i want to get a feedback when the message sending is failed.. please suggest me a solution.
Thanks in advance.. :)
ServiceClient.GetFeedbackReceiver method is available for .Net but i am not able to find a python sdk for getting message delivery feedback.
You can try receive_feedback_notification() as available on cloud_to_device_messages_operations.py
def receive_feedback_notification(self, custom_headers=None, raw=False, **operation_config):
Gets the feedback for cloud-to-device messages.
See https://learn.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for
more information. This capability is only available in the standard tier IoT Hub. For more information, see Choose the right IoT Hubtier.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation
configuration overrides<msrest:optionsforoperations>`.
:return: None
or ClientRawResponse if raw=true
:rtype: None or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
#Construct URL
url = self.receive_feedback_notification.metadata["url"]
If you want to test feedback notification, refer to test_iothub_http_runtime_manager.py

Verify message was sent with Twilio - Python

I have a small script that sends text messages with Twilio using Python.
This is my code:
import os
from twilio.rest import Client
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
cell_number = os.environ.get('CELL_PHONE_NUMBER')
text_message = input("Enter a message to send: ")
send_message = client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
to=cell_number,
body=text_message
print(send_message)
And this is the response I get back:
<Twilio.Api.V2010.MessageInstance account_sid=MY_ACCOUNT_SID sid=SMc5e8f335198144b4b3c7f401af511f11>
I was wondering what the best way was to validate that the message was actually sent in code.
I thought of doing something like this:
if send_message:
print("Message sent.")
else:
print("Message not sent.")
And I was just wondering if there was a better way to do that.
I understand that this is a relatively old question and you might have figured out a way to achieve the desired behavior, but just wanted to post my thoughts so that it may help other learners like me in the future.
So basically, twilio provides developers with a functionality of webhooks using which the status of messages can be tracked. You will have to provide an extra parameter while creating the message wherein you will have to pass the callback url pointing to a server which will be logging the status of the sent messages.
When your python script sends a SMS by doing a POST request to twilio server, twilio will send the status of the message to the callback URL as a parameter by making a post or a get request.
This document describes how to achieve the above behavior with the help of example code snippets. In case you used another method to track the status of the messages, let us know so that it will help the community.

How to send myself an email notification when a suds job is done?

I'm learning to use suds in a python script to send SQL queries to a database. I'd like to able to send myself an email when the query job is finished (it has a job ID so I'm able to check its status). How do I do that?
This is how you send an email via python just fill in the blanks and input it to your code:
import smtplib
content = ("Content to send")
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('your_email#gmail.com','123your_password')
mail.sendmail('your_email#gmail.com','destination_email#gmail.com',content)
mail.close()
print("Sent")
(you dont have to use gmail as most addresses will still work through the gmail smtp)
If email is not required, you can also send chat messages to yourself.
Two projects achieving this :
Nimrod, for Facebook Messenger : https://www.nimrod-messenger.io/
Telegram Middleman, for Telegram : https://github.com/n1try/telegram-middleman-bot
I just wrote a Python decorator for this purpose. You can realize it in one line.
https://github.com/Wenzhi-Ding/py_reminder
from py_reminder import monitor
#monitor('SQL Query of xxx')
def query(sql):
...send your query...
query()
Once this function finishes / or is caught an error, you will get an email notification with some brief information.

Select mails from inbox alone via poplib

I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too.
How do I select emails only from inbox?
I dont want to use any gmail specific libraries.
POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email.
Perhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server.
I assume you have enabled POP3/IMAP access to your GMail account.
This is sample code:
import imaplib
conn= imaplib.IMAP4_SSL('imap.googlemail.com')
conn.login('yourusername', 'yourpassword')
code, dummy= conn.select('INBOX')
if code != 'OK':
raise RuntimeError, "Failed to select inbox"
code, data= self.conn.search(None, ALL)
if code == 'OK':
msgid_list= data[0].split()
else:
raise RuntimeError, "Failed to get message IDs"
for msgid in msgid_list:
code, data= conn.fetch(msgid, '(RFC822)')
# you can also use '(RFC822.HEADER)' only for headers
if code == 'OK':
pass # your code here
else:
raise RuntimeError, "could not retrieve msgid %r" % msgid
conn.close()
conn.logout()
or something like this.
This Java code would suggest that you can select a particular "folder" to download, even when using POP3. Again, this is using Java, not Python so YMMV.
How to download message from GMail using Java (blog post discusses pushing content into a Lucene search engine locally)

Categories

Resources