For my IRC bot when I try to use the `db addcol command I will get that Index error but I got no idea what is wrong with it.
#hook.command(adminonly=True, autohelp=False)
def db(inp,db=None):
split = inp.split(' ')
action = split[0]
if "init" in action:
result = db.execute("create table if not exists users(nick primary key, host, location, greeting, lastfm, fines, battlestation, desktop, horoscope, version)")
db.commit()
return result
elif "addcol" in action:
table = split[1]
col = split[2]
if table is not None and col is not None:
db.execute("ALTER TABLE {} ADD COLUMN {}".format(table,col))
db.commit
return "Added Column"
That is the command I am trying to execute and here is the error:
Unhandled exeption in thread started by <function run at 0xb70d6844
Traceback (most recent call last):
File "core/main.py", line 68, in run
out = func(input.inp, **kw)
File "plugins/core_admin_global.py", :ine 308, in db
col = split[2]
IndexError: list index out of range
You will find the whole code at my GIT repository.
Edit: This bot is just a little thing I have been playing around with while learning python so don't expect me to be too knowledgeable about this.
Yet another edit:
The command I am trying to add, just replace desktop with mom.
#hook.command(autohelp=False)
def desktop(inp, nick=None, conn=None, chan=None,db=None, notice=None):
"desktop http://url.to/desktop | # nick -- Shows a users Desktop."
if inp:
if "http" in inp:
database.set(db,'users','desktop',inp.strip(),'nick',nick)
notice("Saved your desktop.")
return
elif 'del' in inp:
database.set(db,'users','desktop','','nick',nick)
notice("Deleted your desktop.")
return
else:
if '#' in inp: nick = inp.split('#')[1].strip()
else: nick = inp.strip()
result = database.get(db,'users','desktop','nick',nick)
if result:
return '{}: {}'.format(nick,result)
else:
if not '#' in inp: notice(desktop.__doc__)
return 'No desktop saved for {}.'.format(nick)
Related
Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == input_mic:
m = Microphone(device_index=i)
while True:
"""
Commands will be entered in the specific format explained here:
- the first word will be one of: 'album', 'artist', 'play'
- then the name of whatever item is wanted
"""
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'album':
uri = get_album_uri(spotify=spotify, name=name)
play_album(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "album", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
the exact error is:
Traceback (most recent call last):
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
with m as source:
AttributeError: __enter__
__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
The error here is caused because m = None, and None cannot be used in a with statement.
>>> with None as a:
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__
The below function parses the cisco command output,stores the output in dictionary and returns the value for a given key. This function works as expected when the dictionary contains the output. However, if the command returns no output at all the length of dictionary is 0 and the function returns a key error . I have used exception KeyError: But this doesn't seem to work.
from qa.ssh import Ssh
import re
class crypto:
def __init__(self, username, ip, password, machinetype):
self.user_name = username
self.ip_address = ip
self.pass_word = password
self.machine_type = machinetype
self.router_ssh = Ssh(ip=self.ip_address,
user=self.user_name,
password=self.pass_word,
machine_type=self.machine_type
)
def session_status(self, interface):
command = 'show crypto session interface '+interface
result = self.router_ssh.cmd(command)
try:
resultDict = dict(map(str.strip, line.split(':', 1))
for line in result.split('\n') if ':' in line)
return resultDict
except KeyError:
return False
test script :
obj = crypto('uname', 'ipaddr', 'password', 'router')
out = obj.session_status('tunnel0')
status = out['Peer']
print(status)
Error
Traceback (most recent call last):
File "./test_parser.py", line 16, in <module>
status = out['Peer']
KeyError: 'Peer'
The KeyError did not happend in the function session_status,it is happend in your script at status = out['Peer'].So your try and except in session_status will not work.you should make a try and except for status = out['Peer']:
try:
status = out['Peer']
except KeyError:
print 'no Peer'
or :
status = out.get('Peer', None)
Your exception is not in the right place. As you said you just return an empty dictionary with your function. The exception is trying to lookup the key on empty dictionary object that is returned status = outertunnel['Peer']. It might be easier to check it with the dict get function. status = outertunnel.get('Peer',False) or improve the test within the function session_status, like testing the length to decide what to return False if len(resultDict) == 0
This explains the problem you're seeing.
The exception happens when you reference out['Peer'] because out is an empty dict. To see where the KeyError exception can come into play, this is how it operates on an empty dict:
out = {}
status = out['Peer']
Throws the error you're seeing. The following shows how to deal with an unfound key in out:
out = {}
try:
status = out['Peer']
except KeyError:
status = False
print('The key you asked for is not here status has been set to False')
Even if the returned object was False, out['Peer'] still fails:
>>> out = False
>>> out['Peer']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
out['Peer']
TypeError: 'bool' object is not subscriptable
I'm not sure how you should proceed, but dealing with the result of session_status not having the values you need is the way forward, and the try: except: block inside the session_status function isn't doing anything at the moment.
I've got a weird problem. I've made a vba code in excel, that calls a python code that get information from the excel sheet and put it into a database. Yesterday there was no problem. Today I start my computer and tried the vba code and it errors in the python file.
The error:
testchipnr = TC104
Traceback (most recent call last):
testchipID = 108
File "S:/3 - Technical/13 - Reports & Templates/13 - Description/DescriptionToDatabase/DescriptionToDatabase.py", line 40, in <module>
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
TypeError: 'NoneType' object has no attribute '__getitem__'
The weird thing is that there is a value in the database -> testchipID ...
My code:
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
print "testchipID = ", cursorOpenShark.fetchone()[0]
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
As you are saying, it was working fine but now it is not, the only reason that I can think of is when your query is returning Zero results.
Looking at your code, if your query is returning only one result, then it will print the result and the next time you are making the call to cursorOpenShark.fetchone() to store in TestchipID it would return None.
Instead, can you try the following code
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
if TestchipID:
print "testchipID = ", TestchipID[0]
else:
print "Returned nothing"
Let me know if this works.
This is my code snippet for where the traceback call shows an error:
def categorize(title):
with conn:
cur= conn.cursor()
title_str= str(title)
title_words= re.split('; |, |\*|\n',title_str)
key_list= list(dictionary.keys())
flag2= 1
for word in title_words:
title_letters= list(word)
flag1= 1
for key in key_list:
if key==title_letters[0]:
flag1= 0
break
if flag1== 0:
start=dictionary.get(title_letters[0])
end= next_val(title_letters[0])
for i in xrange (start,end):
if word==transfer_bag_of_words[i]:
flag2= 0
break
if flag2== 0:
cur.execute("select Id from articles where title=title")
row_id= cur.fetchone()
value= (row_id,'1')
s= str(value)
f.write(s)
f.write("\n")
break
return
def next_val(text):
for i,v in enumerate(keyList):
if text=='t':
return len(transfer_bag_of_words)
elif v==text:
return dictionary[keyList[i+1]]
This is the traceback call:
Traceback (most recent call last):
File "categorize_words.py", line 93, in <module>
query_database()
File "categorize_words.py", line 45, in query_database
categorize(row)
File "categorize_words.py", line 67, in categorize
for i in xrange (start,end):
TypeError: an integer is required
I have not given the whole code here. But I will explain what I am trying to do. I am trying to import a particular field from a sqlite database and checking if a single word of the field matches with a particular bag of words I already have in my program. I have sorted the bag of words aphabetically and assigned every starting of a new letter to it's index using python dictionary. This I have done so that everytime I check a word of the field being present in the bag of words, I do not have to loop through the entire bag of words. Rather I can just start looping from the index of the first letter of the word.
I have checked that the return type of get() in dictionary is int and the function nextVal also should return an int since both len() and dictionary[keylist[i+1]] are int types.
Please help.
EDIT
This is my entire code:
import sqlite3 as sql
import re
conn= sql.connect('football_corpus/corpus2.db')
transfer_bag_of_words=['transfer','Transfer','transfers','Transfers','deal','signs','contract','rejects','bid','rumours','swap','moves',
'negotiation','negotiations','fee','subject','signings','agreement','personal','terms','pens','agent','in','for',
'joins','sell','buy','confirms','confirm','confirmed','signing','renew','joined','hunt','excited','move','sign',
'loan','loaned','loans','switch','complete','offer','offered','interest','price','tag','miss','signed','sniffing',
'remain','plug','pull','race','targeting','targets','target','eye','sale','clause','rejected',
'interested']
dictionary={}
dictionary['a']=0;
keyList=[]
f= open('/home/surya/Twitter/corpus-builder/transfer.txt','w')
def map_letter_to_pos():
pos=0
transfer_bag_of_words.sort()
for word in transfer_bag_of_words:
flag=1
letters= list(word)
key_list= list(dictionary.keys())
for key in key_list:
if key==letters[0]:
flag=0
break
if flag==1:
dictionary[letters[0]]=pos
pos+=1
else:
pos+=1
keyList= sorted(dictionary.keys())
def query_database():
with conn:
cur= conn.cursor()
cur.execute("select title from articles")
row_titles= cur.fetchall()
for row in row_titles:
categorize(row)
def categorize(title):
with conn:
cur= conn.cursor()
title_str= str(title)
title_words= re.split('; |, |\*|\n',title_str)
key_list= list(dictionary.keys())
flag2= 1
for word in title_words:
title_letters= list(word)
flag1= 1
for key in key_list:
if key==title_letters[0]:
flag1= 0
break
if flag1== 0:
start=dictionary.get(title_letters[0])
end= next_val(title_letters[0])
for i in xrange (start,end):
if word==transfer_bag_of_words[i]:
flag2= 0
break
if flag2== 0:
cur.execute("select Id from articles where title=title")
row_id= cur.fetchone()
value= (row_id,'1')
s= str(value)
f.write(s)
f.write("\n")
break
return
def next_val(text):
for i,v in enumerate(keyList):
if text=='t':
return len(transfer_bag_of_words)
elif v==text:
return dictionary[keyList[i+1]]
if __name__=='__main__':
map_letter_to_pos()
query_database()
And this is the downloadable link to the database file http://wikisend.com/download/702374/corpus2.db
map_letter_to_pos attempts to modify the global variable keyList without specifying it as a global variable, therefore it only modifies a local copy of keyList and then discards it. This causes next_val to have nothing to iterate, so it never reaches the if elif, and returns None.
end = None
range(start,end) # None is not an int
So basically, I have an api from which i have several dictionaries/arrays. (http://dev.c0l.in:5984/income_statements/_all_docs)
When getting the financial information for each company from the api (e.g. sector = technology and statement = income) python is supposed to return 614 technology companies, however i get this error:
Traceback (most recent call last):
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 83, in <module>
user_input1()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 75, in user_input1
income_statement_fn()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 51, in income_statement_fn
if is_response ['sector'] == user_input3:
KeyError: 'sector'
on a random company (usually on one of the 550-600th ones)
Here is the function for income statements
def income_statement_fn():
user_input3 = raw_input("Which sector would you like to iterate through in Income Statement?: ")
print 'Starting...'
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id']
is_request = urllib2.urlopen(is_url).read()
is_response = json.loads(is_request)
if is_response ['sector'] == user_input3:
csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']])
print 'loading...'
print 'done!'
print end - start
Any idea what could be causing this error?
(I don't believe that it is the api itself)
Cheers
Well, on testing the url you pass in the urlopen call, with a random number, I got this:
{"error":"not_found","reason":"missing"}
In that case, your function will return exactly the error you get. If you want your program to handle the error nicely and add a "missing" line instead of actual data, you could do that for instance:
def income_statement_fn():
user_input3 = raw_input("Which sector would you like to iterate through in Income Statement?: ")
print 'Starting...'
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id']
is_request = urllib2.urlopen(is_url).read()
is_response = json.loads(is_request)
if is_response.get('sector', False) == user_input3:
csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']])
print 'loading...'
else:
csv.writerow(['missing data'])
print 'done!'
print end - start
The problem seems to be with the final row of your income_response data
{"id":"_design/auth","key":"_design/auth","value":{"rev":"1-3d8f282ec7c26779194caf1d62114dc7"}}
This does not have a sector value. You need to alter your code to handle this line, for example by ignoring any line where the sector key is not present.
You could easily have debugged this with a few print statements - for example insert
print item['id'], is_response.get('sector', None)
into your code before the part that outputs the CSV.
A KeyError means that the key you tried to use does not exist in the dictionary. When checking for a key, it is much safer to use .get(). So you would replace this line:
if is_response['sector'] == user_input3:
With this:
if is_response.get('sector') == user_input3: