I have developed a python script that allows users to create trackers, assign them, and change their URLs very quickly and automatically. When I tried to develop further into banners, I have faced several issues that were all resolved except for 2
The first error is: Required parameter: profileID
The second error is: the creative must have "Include in Rotation" set to "Yes' - even though I have the parameter "active": True literally everywhere in the code
The below is a snippet of the code if anyone can help.. Thanks in advance
ad_tracker = [{
"active": "true",
"archived": False,
"campaignId": campaign_id,
"creativeRotation": creative_rotation_tracker,
"deliverySchedule": delivery_schedule,
"endTime": datetime.datetime.strftime(
datetime.datetime.strptime(
"%sT04:59:59Z" % campaign["endDate"], "%Y-%m-%dT%H:%M:%SZ"
)
+ datetime.timedelta(days=1),
"%Y-%m-%dT%H:%M:%SZ",
),
"name": f"{creative_names_ids_URLs[0][0]}-{placement_name}"[0:255],
"placementAssignments": [placement_assignment],
"startTime": "%sT05:00:00Z" % time.strftime("%Y-%m-%d"),
"type": "AD_SERVING_TRACKING",
}]
ad_non_tracker = [{
"active": True,
"archived": False,
"campaignId": campaign_id,
"creativeRotation": creative_rotation_non_tracker,
"deliverySchedule": delivery_schedule_non_tracker,
"endTime": datetime.datetime.strftime(
datetime.datetime.strptime(
"%sT04:59:59Z" % campaign["endDate"], "%Y-%m-%dT%H:%M:%SZ"
)
+ datetime.timedelta(days=1),
"%Y-%m-%dT%H:%M:%SZ",
),
"name": f"{creative_names_ids_URLs[0][0]}-{placement_name}"[0:255],
"placementAssignments": [placement_assignment],
"startTime": "%sT05:00:00Z" % time.strftime("%Y-%m-%d"),
"type": "AD_SERVING_STANDARD_AD",
}]
request = service.ads().insert(profileId=profile_id, body=ad_tracker)
request = service.ads().insert(profileId=profile_id, body=ad_non_tracker)
Note: Profile ID, Advertiser ID and Campaign ID are all inputs
I am looping on an excel sheet to get them altogether at once.. if any additional information is needed, it will surely be provided
Thanks a lot
Related
customer_data.json (loaded as customer_data)
{
"customers": [
{
"username": "anonymous",
"id": "1234",
"password": "12341234",
"email": "1234#gmail.com",
"status": false,
"books": [
"Things Fall Apart",
"Fairy Tales",
"Divine Comedy"
]
}
]
}
Example post in new_catalog.json. (loaded as posts)
{
"books": [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958,
"hold": false
}
}
Necessary code in Flask_practice.py
for customer in customer_data['customers']:
if len(customer['books']) > 0:
for book in customer['books']:
holds.append(book)
for post in posts['books']:
if post['title'] == holds[range(len(holds))]:
matching_posts['books'].append(post)
holds[range(len(holds))] doesn't work.
I am trying to go through each of the books in holds using holds[0], holds[1] etc and test to see if the title is equal to a book title in new_catalog.json.
I'm still new to Flask, Stack Overflow and coding in general so there may be a really simple solution to this problem.
I am trying to go through each of the books in holds using holds[0], holds[1] etc and test to see if the title is equal to a book title
Translated almost literally to Python:
# For each post...
for post in posts['books']:
# ...go through each of the books in `holds`...
for hold in holds:
# ...and see if the title is equal to a book title
if post['title'] == hold:
matching_posts['books'].append(post)
Or, if you don't want to append(post) for each item in holds:
for post in posts['books']:
if post['title'] in holds:
matching_posts['books'].append(post)
I want to find id and options in this JSON data.
Here's What I did so far.
data = """
"list": null,
"promotionID": "",
"isFreeShippingApplicable": true,
"html": "\n\n\n<div class=\"b-product-tile-price\">\n \n \n\n\n\n<span class=\"b-product-tile-price-outer\">\n <span class=\"b-product-tile-price-item\">\n 1200 €\n\n\n </span>\n</span>\n\n</div>\n\n"
},
"longDescription": "<ul>\n\t<li>STYLE: BQ4420-100</li>\n\t<li>Laufsohle: Gummi</li>\n\t<li>Obermaterial: beschichtetes Leder, Textil</li>\n\t<li>Innenmaterial: Textil</li>\n</ul>\n",
"shortDescription": null,
"availability": {
"messages": [
"Sofort lieferbar"
],
"inStockDate": null,
"custom": {
"code": null,
"label": null,
"orderable": true,
"sizeSelectable": true,
"badge": false
"""
find_values = json.loads(data)
id = find_values["id"]
variables = find_product_data["variables"]
print(id, variables)
The output is an erro but when I try to get the values of first the attribute action, it gets returned but not the others.
You can't access the id directly, because it is nested inside another dictionary. What you have to do is get that dict first and then access the id.
find_values = json.loads(data)
product = find_values["product"]
id_value = product("id")
If you are working with an IDE it could help to debug your code and see how the dict is actually nested.
So basically, I have a set of data (domain name, severity score) that is in string format as post, and I am trying to get it to post in slack and It keeps throwing errors out and I don't know why. I appreciate the help.
I have tried changing the JSON portion a bit to see if it was that as well as changing what is being sent to the function in general, and nothing helps.
def slackHook(post):
webhook_url = #Ommited
slack_content = {"channel": "#brian", "user": "Awesom-O", "attachment": [{
"type": "section",
"text": {
"text": "Random message before domains",
"type": "mrkdwn",
},
"fields": [
{
"type": "mrkdwn",
"text": "Domain Severity Score"
},
{
"type": "plain_text",
"text": post
}
]
}]}
string_payload = json.dumps(slack_content)
r = requests.post(webhook_url, data=string_payload)
if r.status_code != 200:
raise ValueError('Request to slack.com returned an error %s, the response is:\n%s' % (r.status_code, r.text))
domains = db_query()
domains = str(domains)
slackHook(domains)
Happy Path: I would just like to take my string and post it to my slack channel using the fields that I've given for context.
The current error:
raise ValueError('Request to slack.com returned an error %s, the response is:\n%s' % (r.status_code, r.text))
ValueError: Request to slack.com returned an error 400, the response is:
no_text
Your main issue is that you where mixing the syntax for attachments and blocks which are different concepts. attachments are outdated and should no longer be used.
Just replace "attachment" with "blocks" like so:
slack_content = {"channel": "#brian", "user": "Awesom-O", "blocks": [{
I am using StackAPI to get the most voted questions and the most voted answers to those questions:-
from stackapi import StackAPI
SITE = StackAPI('stackoverflow')
SITE.max_pages=1
SITE.page_size=10
questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')
for quest in questions['items']:
if 'title' not in quest or quest['is_answered'] == False:
continue
title = quest['title']
print('Question :- {0}'.format(title))
question_id = quest['question_id']
print('Question ID :- {0}'.format(question_id))
top_answer = SITE.fetch('questions/' + str(question_id) + '/answers', order = 'desc', sort='votes')
print('Most Voted Answer ID :- {0}'.format(top_answer['items'][0]['answer_id']))
Now using this answer_id I would like to get the body of that answer.
I can get the rest of the details by using this API link.
Refer to these posts on Stack Apps:
Get questions with body and answers
How to get Question/Answer body in the API response using filters?
My filter is not returning any results. How to create a minimal filter?
You need to use a custom filter to get question/answer/post bodies.
The good news is that you can also use the custom filter to get the answer data at the same time as you get the questions -- eliminating the need for later API calls.
For example, if you call the /questions route with the filter:
!*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*
You get results like:
"items": [ {
"tags": ["python", "iterator", "generator", "yield", "coroutine"],
"answers": [ {
"owner": {"user_id": 8458, "display_name": "Douglas Mayle"},
"is_accepted": false,
"score": 248,
"creation_date": 1224800643,
"answer_id": 231778,
"body": "<p><code>yield</code> is just like <code>return</code> - it returns what..."
}, {
"owner": {"user_id": 22656, "display_name": "Jon Skeet"},
"is_accepted": false,
"score": 139,
"creation_date": 1224800766,
"answer_id": 231788,
"body": "<p>It's returning a generator. I'm not particularly familiar with Python, ..."
}, {
...
} ],
"owner": {"user_id": 18300, "display_name": "Alex. S."},
"is_answered": true,
"accepted_answer_id": 231855,
"answer_count": 40,
"score": 8742,
"creation_date": 1224800471,
"question_id": 231767,
"title": "What does the "yield" keyword do?"
},
...
So, change this:
questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')
To something like this:
questions = SITE.fetch('questions', min=20, tagged='python', sort='votes', filter='!*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*')
then adjust your for loop accordingly.
I'm trying to create a wave robot, and I have the basic stuff working. I'm trying to create a new blip with help text when someone types #help but for some reason it doesnt create it. I'm getting no errors in the log console, and I'm seeing the info log 'in #log'
def OnBlipSubmitted(properties, context):
# Get the blip that was just submitted.
blip = context.GetBlipById(properties['blipId'])
text = blip.GetDocument().GetText()
if text.startswith('#help') == True:
logging.info('in #help')
blip.CreateChild().GetDocument().SetText('help text')
if it just started working, I have two suggestions...
-->Have you been updating the Robot Version in the constructor? You should change the values as you update changes so that the caches can be updated.
if __name__ == '__main__':
myRobot = robot.Robot('waverobotdev',
image_url = baseurl + 'assets/wave_robot_icon.png',
version = '61', # <-------------HERE
profile_url = baseurl)
-->The server connection between Wave and AppSpot has recently been extremely variable. Sometimes it takes 10+ minutes for the AppSpot server to receive my event, othertimes a few seconds. Verify you're receiving the events you expect.
Edit:
The code you provided looks good, so I wouldn't expect you're doing anything wrong in that respect.
Have you tried using Append() instead of SetText()? That's what I'd do in my C# API - I haven't used the Python API, but I'd imagine it's similar. Here's a sample from my demo robot:
protected override void OnBlipSubmitted(IEvent e)
{
if (e.Blip.Document.Text.Contains("robot"))
{
IBlip blip = e.Blip.CreateChild();
ITextView textView = blip.Document;
textView.Append("Are you talking to me?");
}
}
That works fine.
EDIT: Here's the resulting JSON from the above code:
{
"javaClass": "com.google.wave.api.impl.OperationMessageBundle",
"version": "173784133",
"operations": {
"javaClass": "java.util.ArrayList",
"list": [
{
"javaClass": "com.google.wave.api.impl.OperationImpl",
"type": "BLIP_CREATE_CHILD",
"waveId": "googlewave.com!w+PHAstGbKC",
"waveletId": "googlewave.com!conv+root",
"blipId": "b+Iw_Xw7FCC",
"index": -1,
"property": {
"javaClass": "com.google.wave.api.impl.BlipData",
"annotations": {
"javaClass": "java.util.ArrayList",
"list": []
},
"lastModifiedTime": -1,
"contributors": {
"javaClass": "java.util.ArrayList",
"list": []
},
"waveId": "googlewave.com!w+PHAstGbKC",
"waveletId": "googlewave.com!conv+root",
"version": -1,
"parentBlipId": null,
"creator": null,
"content": "\nAre you talking to me?",
"blipId": "410621dc-d7a1-4be5-876c-0a9d313858bb",
"elements": {
"map": {},
"javaClass": "java.util.HashMap"
},
"childBlipIds": {
"javaClass": "java.util.ArrayList",
"list": []
}
}
},
{
"javaClass": "com.google.wave.api.impl.OperationImpl",
"type": "DOCUMENT_APPEND",
"waveId": "googlewave.com!w+PHAstGbKC",
"waveletId": "googlewave.com!conv+root",
"blipId": "410621dc-d7a1-4be5-876c-0a9d313858bb",
"index": 0,
"property": "Are you talking to me?"
}
]
}
}
How does that compare with the JSON which comes out of your robot?
For some reason it just started working. I think the google wave is spotty.