Python code in Zapier (invalid syntax (usercode.py, line 42)) - python

This code is pre-made in a Zapier forum to pull failed responses from another piece of software called iAuditor. When I plug in the code and update the API token and webhook URL this error pops up:
Traceback (most recent call last):
SyntaxError: invalid syntax (usercode.py, line 42)
Here is the code:
[code]
import json
import requests
auth_header = {'Authorization': 'a4fca847d3f203bd7306ef5d1857ba67a2b3d66aa455e06fac0ad0be87b9d226'}
webhook_url = 'https://hooks.zapier.com/hooks/catch/3950922/efka9n/'
api_url = 'https://api.safetyculture.io/audits/'
audit_id = input['audit_id']
audit_doc = requests.get(api_url + audit_id, headers=auth_header).json()
failed_items = []
audit_author = audit_doc['audit_data']['authorship']['author']
conducted_on = audit_doc['audit_data']['date_completed']
conducted_on = conducted_on[:conducted_on.index('T')]
audit_title = audit_doc['template_data']['metadata']['name']
for item in audit_doc['items']:
if item.get('responses') and item['responses'].get('failed') == True:
label = item.get('label')
if label is None:
label = 'no_label'
responses = item['responses']
response_label = responses['selected'][0]['label']
notes = responses.get('text')
if notes is None:
notes = ''
failed_items.append({'label': label,
'response_label': response_label,
'conducted_on': conducted_on,
'notes': notes,
'author': audit_author
})
for item in failed_items:
r = requests.post(webhook_url, data = item)
return response.json()
[/code]

This looks like an error from the platform. It looks like Zapier uses a script called usercode.py to bootstrap launching your script and the error seems to be coming from that part.

Related

KeyError in Weather API Response

I was making a python program which tells about weather but facing the following error
Please tell how to correct it?
CODE
import requests
import json
api = "<MY_API_KEY>"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
print("for which city?")
CITY = input("city?: ")
URL = BASE_URL + "q=" + CITY + "&appid=" + api
response = requests.get(URL)
if __name__ == "__main__":
data = response.json()
main = data['main']
temperature = main['temp']
humidity = main['humidity']
pressure = main['pressure']
report = data['weather']
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {report[0]['description']}")
TERMINAL
PS C:\Users\mamta\Documents\PythonPanti\JARVISprj> c:; cd 'c:\Users\mamta\Documents\PythonPanti\JARVISprj'; & 'C:\Users\mamta\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\mamta\.vscode\extensions\ms-python.python-2021.5.842923320\pythonFiles\lib\python\debugpy\launcher'
'53873' '--' 'c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py'
for which city?
city?: Delhi
Traceback (most recent call last):
File "c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py", line 13, in <module>
main = data['main']
KeyError: 'main'
Your code is perfectly fine only problem here I see is when you enter any garbage value. You need to do error handling.

KeyError in Python Code even though Key is present

I am trying to create a Channel Separator code to separate the transcribe that is printed in a JSON file.
I have the following code:
import json
import boto3
def lambda_handler(event, context):
if event:
s3 = boto3.client("s3")
s3_object = event["Records"][0]["s3"]
bucket_name = s3_object["bucket"]["name"]
file_name = s3_object["object"]["key"]
file_obj = s3.get_object(Bucket=bucket_name, Key=file_name)
transcript_result = json.loads(file_obj["Body"].read())
segmented_transcript = transcript_result["results"]["channel_labels"]
items = transcript_result["results"]["items"]
channel_text = []
flag = False
channel_json = {}
for no_of_channel in range (segmented_transcript["number_of_channels"]):
for word in items:
for cha in segmented_transcript["channels"]:
if cha["channel_label"] == "ch_"+str(no_of_channel):
end_time = cha["end_time"]
if "start_time" in word:
if cha["items"]:
for cha_item in cha["items"]:
if word["end_time"] == cha_item["end_time"] and word["start_time"] == cha_item["start_time"]:
channel_text.append(word["alternatives"][0]["content"])
flag = True
elif word["type"] == "punctuation":
if flag and channel_text:
temp = channel_text[-1]
temp += word["alternatives"][0]["content"]
channel_text[-1] = temp
flag = False
break
channel_json["ch_"+str(no_of_channel)] = ' '.join(channel_text)
channel_text = []
print(channel_json)
s3.put_object(Bucket="aws-speaker-separation", Key=file_name, Body=json.dumps(channel_json))
return{
'statusCode': 200,
'body': json.dumps('Channel transcript separated successfully!')
}
However, when I run it, I get an error on line 23 saying:
[ERROR] KeyError: 'end_time'
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 23, in lambda_handler
end_time = cha["end_time"]
I am confused as to why this error is happening as in my JSON code, the things to read are as follows:
JSON Code Parameters
Any ideas why this error is appearing?
cha is a channel, the end_time is a layer deeper in the items of your channel. To access the items of your channel do:
for item in cha["items"]:
print(item["end_time"])

IRC feedparser index out of range mysterious error

I am trying to code rss news feeder bot for irc. So I search a bit on web a little and made out this code
#this code is for local testing
import feedparser
feed_list = {}
channel = '#hackingdefined'
class Feed:
def __init__(self, name, url):
self.name = name
self.url = url
self.feeds = {}
self.newest = ''
def update(self):
self.feeds = feedparser.parse(self.url)
if self.newest != self.feeds['items'][0].title:
self.newest = self.feeds['items'][0].title
say('{}: {} '.format(self.name,self.newest))
say('URL: {} '.format(self.feeds.entries[0].link))
def say(data=''):
print('PRIVMSG '+channel+' :'+ data+'\r\n')
def url_loader(txt):
f = open(txt, 'r')
for line in f:
name, url = line.split(':',1) # check how to spilt only once
print name+" "+url
feed_list[name] = Feed(name,url)
print feed_list
url_loader('feed_list.txt')
for feed in feed_list.values():
print feed
feed.update()
When I run the code I get this error
Traceback (most recent call last):
File "C:\Or\define\projects\rss feed\the progect\test.py", line 33, in <module>
feed.update()
File "C:\Or\define\projects\rss feed\the progect\test.py", line 14, in update
if self.newest != self.feeds['items'][0].title:
IndexError: list index out of range
Now the wierd thing is, if I create a new Feed class like test = Feed('example', 'http://rss.packetstormsecurity.com/')
and call test.update() Its all work fine, but the automation script raise an error.
So i checked my url_load and the test file,The test file is something like this:
packet storm:http://rss.packetstormsecurity.com/
sans:http://www.sans.org/rss.php/
...
And its all seems fine to me. Any one have a clue what this could be?
Thanks, Or
EDIT:
Its been solved, one of my url was wrong.
All seem clear after good night sleep :-)
Its been solved, one of my url that i post into the file was wrong.
The solution is use try on every url in the list.

Python Invalid Snytax

Below is the code I have been working on.
The very last line write_csv('twitter_gmail.csv', messages, append=True) throws a
[ec2-user#ip-172-31-46-164 ~]$ ./twitter_test16.sh
Traceback (most recent call last):
File "./twitter_test16.sh", line 53, in
write_csv('twitter_gmail.csv', messages, append=True)
NameError: name 'messages' is not defined
I have messages defined so I dont understand why it would do that.
import csv
import json
import oauth2 as oauth
import urllib
import sys
import requests
import time
CONSUMER_KEY = "
CONSUMER_SECRET = "
ACCESS_KEY = "
ACCESS_SECRET = "
class TwitterSearch:
def __init__(self, ckey=CONSUMER_KEY, csecret=CONSUMER_SECRET,
akey=ACCESS_KEY, asecret=ACCESS_SECRET,
query='https://api.twitter.com/1.1/search/tweets.{mode}?{query}'
):
consumer = oauth.Consumer(key=ckey, secret=csecret)
access_token = oauth.Token(key=akey, secret=asecret)
self.client = oauth.Client(consumer, access_token)
self.query = query
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
return self.client.request(self.query.format(query=query, mode=mode))
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = TwitterSearch()
response, data = ts.search('#gmail.com', result_type='recent')
js = json.loads(data)
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] \
for msg in js.get('statuses', []))
write_csv('twitter_gmail.csv', messages, append=True)
The previous line is missing a parenthesis.
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', [])
Should be:
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
I'm surprised that it works when you change to print? Are you also changing the comprehension when you do that?
You asked why the line number of the error was after the bad syntax?
Try putting this in line one of a file and running it, and note the line of the SyntaxError.
a = (]
Then try this and check out the line number:
a = (
b = "some stuff"
Finally, try this:
a = (
b = "some stuff"
Think about when you would know that the programmer had made a python-illegal typo if you were reading the code and carrying it out via pen and paper.
Basically, a SyntaxError is raised as soon as it can be unambiguously determined that invalid syntax was used, which is often immediately after a statement where a mistake was made, not immediately at.
You'll frequently get line numbers on SyntaxErrors that are a line (or several lines if there's empty lines or a corner case) below the actual typo.

AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'

I'm currently trying to use the pjsip api pjsua in python and therefor studying this Hello World example: http://trac.pjsip.org/repos/wiki/Python_SIP/Hello_World
I copied the code over, integrated account configuration according to http://trac.pjsip.org/repos/wiki/Python_SIP/Accounts etc. But when I run the sample, I get the following output:
Traceback (most recent call last):
File "/home/dmeli/workspace/eit.cubiephone.sip_test/eit/cubiephone/sip_test/hello.py", line 48, in <module>
acc = lib.create_account(acc_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2300, in create_account
err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 900, in _cvt_to_pjsua
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Because I'm not really a python expert and never worked with PJSIP before, I can't really figure out the error. Too me, it looks like it's actually an error in the pjsip python wrapper. But what do I know?
Code:
lib = pj.Lib()
lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
transport = lib.create_transport(pj.TransportType.UDP)
lib.start()
acc_cfg = pj.AccountConfig("XXXXX", "XXXXXX", "XXXXXX")
acc_cfg.id = "sip:XXXXXXX#XXXXXXXX"
acc_cfg.reg_uri = "sip:XXXXXXXXX"
acc_cfg.proxy = [ "sip:XXXXXXXXX;lr" ]
acc = lib.create_account(acc_cfg)
# Make call
call = acc.make_call("XXXXXXXXXXX", MyCallCallback())
Line where the error happens in pjsua.py:
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
(rtp_transport_cfg doesn't seem to have a member _cvt_to_pjsua()??)
For further work correctly, look at the PJSIP api (pjsua.py) that he is waiting for the order and structure!!!
## start lib.
def start(self):
try:
self._start_lib()
self._start_acc()
except pj.Error:
print "Error starting lib."
def _bind(self):
try:
t = pj.TransportConfig()
t.bound_addr = '0.0.0.0'
t.port = 5060
acc_transport = "udp" # depend if you need.
if acc_transport == "tcp":
self.transport = self.lib.create_transport(pj.TransportType.TCP, t)
# or this pj.TransportConfig(0) is creating random port ...
#self.transport = self.lib.create_transport(pj.TransportType.TCP, pj.TransportConfig(0))
else:
self.transport = self.lib.create_transport(pj.TransportType.UDP, t)
#self.transport = self.lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
except pj.Error:
print "Error creating transport."
#you need create callbacks for app, to work incoming calls, check on the server that returns the error code 200, and such a way your program will know that you are logged on correctly
#from callback.acc_cb import acc_cb
#self.acc_t = self.lib.create_account_for_transport(self.transport, cb=acc_cb())
def _start_lib(self):
self.lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
self.lib.start()
self._bind()
#codecs.load_codecs()
def _start_acc(self):
#from callback.acc_cb import acc_cb
try:
proxy = "sip server ip" # or proxy = socket.gethostbyname(unicode("sip.serverdnsname.com")) is needed to import socket
login = "Atrotygma" # real username
password = "Atrotygma_password" # real username
lib.create_account(acc_config=pj.AccountConfig(proxy, login, password))
except Exception, e:
print "Error creating account", e

Categories

Resources