Building Nested Arrays Python - python

I am trying to create an array to send emails in Mailchimps API. I am following their documentation and I got the following error:
An exception occurred: {'status': 'error', 'code': -2, 'name': 'ValidationError', 'message': 'Validation error: {"message":{"to":["Please enter an array"]}}'}
So I've updated my array as follows:
message = {"from_email": "test1#email.com","from_name":"Test","message":{"to":["email":"test2#email.com"]}}
However, I'm getting an invalid syntax error under my nested array in messages and I can't quite seem to solve this. Could anyone quickly help?

Seems like you used list [] in place of {} for dictionary
..."message":{"to":["email":"test2#email.com"]}}
^ ^
change it to
message = {"from_email": "test1#email.com","from_name":"Test","message":{"to":{"email":"test2#email.com"}}}

As per the documentation of Mail-Chimp and as you tagged with Python, you may use their Python SDK and sending a mail is as simple as below -
import mailchimp_transactional as MailchimpTransactional
from mailchimp_transactional.api_client import ApiClientError
try:
mailchimp = MailchimpTransactional.Client("YOUR_API_KEY")
response = client.messages.send({"message": {}})
print(response)
except ApiClientError as error:
print("An exception occurred: {}".format(error.text))
For Installation, use pip install mailchimp_transactional

Related

Youtube Python API LiveChatMessages insert ERROR_UNSPECIFIED

I'm working on writing a python script that utilizes the Youtube Live API. I can read messages using the liveChatMessages().list() method, but am getting a strange error about an invalid argument when I attempt to create a message with liveChatMessages().insert().
The below is the source code responsible for sending messages:
def send_message(self, message):
body = {
'snippet': {
'liveChatId': self.stream_id,
'type': 'textMessageEvent',
'textMessageDetails': {
'messageText': message
}
}
}
self.youtube.liveChatMessages().insert(part='snippet', body=body).execute()
The following is the errror that I'm getting
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/liveChat/messages?part=snippet&alt=json returned "Request contains an invalid argument.". Details: "[{'domain': 'youtube.api.v3.LiveChatMessageInsertResponse.Error', 'reason': 'ERROR_UNSPECIFIED'}]">
I have been following the API documentation found at https://developers.google.com/youtube/v3/live/docs/liveChatMessages/insert and https://developers.google.com/resources/api-libraries/documentation/youtube/v3/python/latest/youtube_v3.liveChatMessages.html#insert
I've had this same problem with Dart instead of Python:
await youTubeApi!.liveChatMessages.insert(
LiveChatMessage(
snippet: LiveChatMessageSnippet(
liveChatId: chatId,
type: "textMessageEvent",
textMessageDetails: LiveChatTextMessageDetails(messageText: message)))
Resulting in the "400 Request contains an invalid argument" error.
The solution was simple: I forgot to activate the YouTube channel of the account. Check whether you can write into the chat manually.

Using OpenStack Nova Exceptions

When I'm using nova.keypairs.create() and I pass it an invalid public key, I get the following:
BadRequest: Keypair data is invalid: failed to generate fingerprint (HTTP 400) (Request-ID: req-12bc6440-f042-4687-9ee9-d89e7edc260d)
I tried doing the following and for obvious reasons (it's a unique exception to OpenStack) it didn't work:
try:
nova.keypairs.create(name=keyname, public_key=key)
except BadRequest:
raise cherrypy.HTTPError(400, "Invalid public key")
How can I use OpenStack specific exceptions such as BadRequest within my own try and except statements?
You will need to import the exceptions for nova package. Going through github for the package, it looks like you will need to do:
from nova.exception import *
Note that the exception you are seeing is actually InvalidKeypair exception, which itself subclasses from exception class Invalid, the BadRequest message is just the template text for it.
So, your complete code would look something like:
from nova.exception import *
# You can import specific ones if you are confident about them
try:
nova.keypairs.create(name=keyname, public_key=key)
except InvalidKeypair:
raise cherrypy.HTTPError(400, "Invalid public key")

Python twitter package : get error code

I'm not yet very familiar with error handling in Python. I'd like to know how to retrieve the error code when I get an error using the python-twitter package :
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
print(twittererror)
Twitter sent status 403 for URL: 1.1/friendships/create.json using parameters: (follow=True&oauth_consumer_key=XXX&oauth_nonce=XXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=XXX&oauth_token=XXX&oauth_version=1.0&screen_name=someone_who_blocked_me&oauth_signature=XXX)
details: {'errors': [{'message': 'You have been blocked from following this account at the request of the user.', 'code': 162}]}
In this case, I'd like to retrieve the 'code': 162 part, or just the 162.
twittererror.args is a tuple with one element in it, which is a string, print(twittererror.args[0][0:10]) outputs Twitter se
How can I get the 162 ?
(Obviously, twittererror.args[0][582:585] is not the answer I'm looking for, as any other error message will be of a different length and the error code won't be at [582:585])
Looking at how the TwitterHTTPError is defined in this GitHub repo, you should obtain the dict with twittererror.response_data.
Therefore you can do something like that:
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
for error in twittererror.response_data.get("errors", []):
print(error.get("code", None))

Twitter follower app: "generated an exception: [{'message': 'Rate limit exceeded', 'code': 88}]"

I have some code that follows everyone in return when they follow me:
import twitter
from sets import Set
try:
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_key='',
access_token_secret='')
following = api.GetFriends()
friendNames = Set()
for friend in following:
friendNames.add(friend.screen_name)
followers = api.GetFollowers()
for follower in followers:
if (not follower.screen_name in friendNames):
api.CreateFriendship(follower.screen_name)
except Exception as exc:
print('generated an exception: %s' % (exc))
This is throwing up the following error:
generated an exception: [{'message': 'Rate limit exceeded', 'code': 88}]
I am aware that their is a restriction around how many followers you can follow back per hour using this code via the API, however I have manually followed all my followers back and still got the same error. Can anyone see what the issue is here?
Thanks

Py-appscript: How can I make message with Mail.app

I'm trying to create mail with py-appscript (AppleScript interface for python).
I tried following code,
from appscript import *
mail = app('Mail')
msg = mail.make(new=k.outgoing_message,
with_properties={'visible':True,
'content':"hello",
'subject':"appscript",
'sender':'taichino#gmail.com'
})
but got following error messages, and I couldn't find out any information for that...
CommandError: Command failed:
OSERROR: -1701
MESSAGE: Some parameter is missing for command.
COMMAND: app(u'/Applications/Mail.app').make('outgoing_message', with_properties={'content': 'hello', 'visible': True, 'sender': 'taichino#gmail.com', 'subject': 'appscript'})
Suggestions, please?
Problem solved by myself, following code works fine.
from appscript import *
mail = app('Mail')
msg = mail.make(new=k.outgoing_message)
msg.subject.set("hello"),
msg.content.set("appscript")
msg.to_recipients.end.make(
new=k.to_recipient,
with_properties={k.address: 'taichino#gmail.com'}
)
msg.send()
Insted of setting properties in constructor, set each property separately.

Categories