Twilio retrieve message history from recipient only via Python - python

Suppose I have this code which places all the message history between a twilio number and its recipients in an array. Is there a way to retrieve only the message history from all the recipients and not the sender (whom is I)
from twilio.rest import Client
account_sid = 'xxxx'
auth_token = 'xxxx'
client = Client(account_sid, auth_token)
text=[]
messages = client.messages.list()
for record in messages:
print(record.body)
text.append(record.body)
print(text)

There are some examples of filter criteria with the above command, you can filter on to: to your specific Twilio number to just see that side of the conversation (via body key).
# Download the helper library from https://www.twilio.com/docs/python/install
from datetime import datetime
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
messages = client.messages.list(
to='+15558675310',
limit=20
)
for record in messages:
print(record.sid)

Related

How to send a text message using the Twilio API

I am working on a Python project to send a text message to a specific phone number. The code below should load the api credentials into the Twilio REST client then send a message to RECIPIENT.
# Download the helper library from https://www.twilio.com/docs/python/install
from email import message
import os
from twilio.rest import Client
from dotenv import load_dotenv
import logging
import os
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Set environment variables
ACCOUNT_SID = os.getenv("ACCOUNT_SID")
AUTH_TOKEN = os.getenv("AUTH_TOKEN")
PHONE = os.getenv("PHONE")
RECIPIENT = os.getenv("RECIPIENT")
# Load environment variables
load_dotenv()
accountSID = ACCOUNT_SID
authToken = AUTH_TOKEN
myNumber = RECIPIENT
twilioNumber = PHONE
twilioCli = Client(accountSID,authToken)
messages = twilioCli.messages.create(body="The boring task is finished",from_=twilioNumber, to=myNumber)
logging.debug(f"{message.sid}")
Expected:
The message should be sent and the message SID should be printed out.
Actual:
File "C:\Users\EvanGertis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\twilio\rest\__init__.py", line 58, in __init__
raise TwilioException("Credentials are required to create a TwilioClient")
twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient
Why is this not working?
Looks like the: # Load environment variables is below your assignments, put it at thr top before assignment.
Look at that "# Set environment variables" section,
Try to put these in things
ACCOUNT_SID = os.getenv("# Put your account Sid here")
AUTH_TOKEN = os.getenv("# your auth token here")
PHONE = os.getenv("# your phone you registered on twilio")
RECIPIENT = os.getenv("# the number you got from twilio")
this will help you to run the code &
if this doesn't work then there a trick:
look at the "# Load environment variables" section,
Try to put these in things
accountSID = # Put your account Sid here
authToken = # your auth token here
myNumber = # your phone you registered on twilio
twilioNumber = # the number you got from twilio

How to send to a list of numbers in a text file using twilio python script?

this code below sends an sms text to one number :
import os
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body="Message Here",
from_='Sender Name',
to='+123456789'
)
But I don't want to send number by number, how can i send to a list of numbers which are in a text file called num.txt as an example ?
You can open a file with Python's open function and then iterate over the lines in the file with a for loop. So, if your numbers are all on different lines in your file, then you can accomplish this like so:
import os
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
with open("num.txt") as file:
for number in file:
message = client.messages \
.create(
body="Message Here",
from_='Sender Name',
to=number
)

"unauthorized_client" error when using google API to send an email

I get this error when running my code:
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})
Here is the code:
from __future__ import print_function
from googleapiclient import discovery, errors
from oauth2client import file, client, tools
from google.oauth2 import service_account
from email.mime.text import MIMEText
import base64
SERVICE_ACCOUNT_FILE = 'keys.json'
SCOPES = [' https://www.googleapis.com/auth/gmail.send']
# The user we want to "impersonate"
USER_EMAIL = "myName#myDomain.com"
def validationService():
# Set the crendentials
credentials = service_account.Credentials. \
from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# Delegate the credentials to the user you want to impersonate
delegated_credentials = credentials.with_subject(USER_EMAIL)
service = discovery.build('gmail', 'v1', credentials=delegated_credentials)
return service
def send_message(service):
gmail_from = 'myName#myDomain.com'
gmail_to = 'anotherName#gmail.com'
gmail_subject = 'Hello World'
gmail_content = 'test test'
message = MIMEText(gmail_content)
message['to'] = gmail_to
message['from'] = gmail_from
message['subject'] = gmail_subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
try:
message = (service.users().messages().send(userId='me', body=body)
.execute())
print('your message has been sent')
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
send_message(validationService())
I don't understand where in the code my email address "gmail_from" is connected to my email address. Apart from that i've given access to my IDE in gmail:
I've also created in the google console OAuth 2.0 Client IDs credentials and Service Accounts credentials but i don't really understand how/where to use these.
What am I missing?
On the google website: https://developers.google.com/identity/protocols/oauth2/service-account#error-codes I have found that I needed to "In the Domain-wide delegation page in the Admin console, remove the client, and re-add it with the numeric ID." but i don't understand how to do that nor how that would help.
There is an extra space in the scope:
SCOPES = [' https://www.googleapis.com/auth/gmail.send']
^ here

Gmail API - set sender name when sending mail from a g-suite service account

I want to dynamically change the name that shows up in the recipients mailbox (appears on the left of the subject + content of the email).
No matter what I try, the name always ends up as 'info', and the 'from' address is always 'info#g-suite-domain'
Following is the code I'm using.
import argparse
import base64
import os
import sys
from email.mime.text import MIMEText
from apiclient import errors
from google.oauth2 import service_account
from googleapiclient.discovery import build
from httplib2 import Http
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text, 'html')
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
def service_account_login():
SCOPES = [
'https://mail.google.com',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.readonly',
]
dirname = os.path.dirname(os.path.realpath(__file__))
SERVICE_ACCOUNT_FILE = dirname + '/service-key.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(
'info#g-suite-domain')
service = build('gmail', 'v1', credentials=delegated_credentials)
return service
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--to', required=True)
parser.add_argument('--subject', required=True)
args = parser.parse_args()
content = sys.stdin.read()
EMAIL_FROM = "service-acount-id#project-id.iam.gserviceaccount.com"
service = service_account_login()
# Call the Gmail API
message = create_message(EMAIL_FROM, args.to, args.subject, content)
sent = send_message(service, 'me', message)
I have tried...
relevant solutions I could find online but none helped.
setting both the EMAIL_FROM and with_subject address to the form of "Name <sender-address#domain>" which has no effect.
changing the 'Send mail as' option in gmail for 'info#g-suite-domain'
specifying the name for both email accounts in gmail, google admin, and google console.
creating a new project + service account
reading the googleapiclient.discovery library for problematic code but could not find anything.
I previously transferred the domain providers from Wix to Namecheap, and I didn't realize the MX records were not transferred. It seems, due to the lack of MX record, the from address would always rewrite to 'info#g-suite-domain' (ignoring the message['from'] value).
I have obtained the desired result with:
message["from"] = "info#g-suite-domain <info#g-suite-domain>"

How to transcribe audio in Twilio and using Python?

Hi everyone Im in a tangle as how to recorded, transcribe and retrieve the text from the transcription in Twilio. How do I do it? Example:
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC30bd8bdca7572344721eb96c15a5c0c7"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)
transcription = client.transcriptions.get("TR8c61027b709ffb038236612dc5af8723")
print(transcription.transcription_text)
in client.transcriptions.get, How do I get the latest transcription? I need the Uri (I believe) but have no idea how to access it/variable name.
On a side note, what alternatives to the Twilio transcription are there and how do I access the appropriate recordings in my script to transcribe?
Twilio developer evangelist here.
You can access all your transcriptions by listing them as follows:
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC30bd8bdca7572344721eb96c15a5c0c7"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)
for transcription in client.transcriptions.list():
print transcription.transcriptiontext
You can also set the TranscriptionUrl attribute so you get notified with a transcription ID when a transcription is complete. That way you can use the code snipped you posted above.

Categories