This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 2 years ago.
IndentationError: unexpected unindent WHY? Here's my code:
from praw.models import MoreComments
import praw
import giris
import time
import os
def bot_login():
print("Loggin in...")
r = praw.Reddit(username = giris.username,
password = giris.password,
client_id = giris.client_id,
client_secret = giris.client_secret,
user_agent = "karton_bardak_bot")
print("Logged in!")
return r
info="""
\n
\n
\n
^(ben bot) \n
\n
^(bruh)
"""
subreddit=r.subreddit("shithikayeler")
def run_bot(r, comments_replied_to):
print("Obtaining 25 comments...")
for submission in subreddit.new():
toReply=True
for top_level_comment in submission.comments:
if isinstance(top_level_comment, MoreComments):
continue
if not submission.is_self:
toReply=False
if top_level_comment.author=="karton_bardak_bot" or submission.selftext=='':
toReply=False
print("PASSED "+ submission.url)
log.write("PASSED "+ submission.url+"\n")
if toReply:
try:
new=reply(submission.selftext, info)
submission.reply(new)
except Exception as e:
log.write("ERROR: " + str(e) + " on submission " + submission.url)
print("REPLIED "+ submission.url)
log.write("REPLIED "+submission.url+"\n")
try:
time.sleep(60)
r = bot_login
while True:
run_bot(r)
It says:
File "bot.py", line 57
r = bot_login
^
IndentationError: unexpected unindent
Why? I have checked a thousands times and I can't find the problem. Pls help.
Because you start a
try:
block with out giving it the needed
except:
part... exactly here:
try:
time.sleep(60)
r = bot_login
so it complains about r = bot_login being maliciously wrong indented.
The code either expects you to stay inside the try: indentation to add more code or ex-dent once and add the except ... : part of the statement followed by another indent for it`s code.
See python.org tutorial about handling exceptions
Related
I'm trying to create a reddit bot that checks the latest comments in a subreddit, and if the comment contains a misquote, I want the bot to reply with the actual quote. My problem is that after my bot waits for a couple minutes due to the reddit timeout, after the wait is over, it throws an exception error.
I've tried to make it only handle one exception at a time by making an exc variable, and setting it to 0 or 1, but that hasn't worked.
Here is my code (excluding identifying info) :
import praw
import re
import time
import os
reddit = praw.Reddit(client_id= 'id',
client_secret= 'secret',
user_agent='<console: reddit_bot: 0.0.1 (by /u/username)>',
username= 'username',
password= 'password'
)
if not os.path.isfile("comments_replied_to.txt"):
comments_replied_to = []
else:
with open("comments_replied_to.txt", "r") as f:
comments_replied_to = f.read()
comments_replied_to = comments_replied_to.split("\n")
comments_replied_to = filter(None, comments_replied_to)
subreddit = reddit.subreddit('subreddit')
pos=0
exc = 0
keywords = [ 'Luke, I am your father', 'Do you feel lucky, punk?']
for comment in subreddit.stream.comments():
for keyword in keywords:
if keyword in comment.body and comment.id not in comments_replied_to and comment.author != 'thatotteraccount':
print("String with " + keyword + " found in comment " + comment.id)
if keyword == 'Luke, I am your father':
if exc==0:
try:
comment.reply('* "No, I am your Father."')
except praw.exceptions.APIException as e:
exc=1
if (e.error_type == "RATELIMIT"):
delay = re.search("(\d+) minutes", e.message)
if delay:
delay_seconds = float(int(delay.group(1)) * 60)
time.sleep(delay_seconds)
comment.reply('* "No, I am your Father."')
exc=0
else:
delay = re.search("(\d+) seconds", e.message)
delay_seconds = float(delay.group(1))
time.sleep(delay_seconds)
comment.reply('* "No, I am your Father."')
exc=0
if keyword == 'Do you feel lucky, punk?':
if exc==0:
try:
comment.reply('* "Youve got to ask yourself one question: Do I feel lucky? Well, do ya punk?" ')
except praw.exceptions.APIException as e:
exc=1
if (e.error_type == "RATELIMIT"):
delay = re.search("(\d+) minutes?", e.message)
if delay:
delay_seconds = float(int(delay.group(1)) * 60)
time.sleep(delay_seconds)
comment.reply('* "Youve got to ask yourself one question: Do I feel lucky? Well, do ya punk?" ')
exc=0
else:
delay = re.search("(\d+) seconds", e.message)
delay_seconds = float(delay.group(1))
time.sleep(delay_seconds)
comment.reply('* "Youve got to ask yourself one question: Do I feel lucky? Well, do ya punk?" ')
exc=0
print("Replied to comment" + comment.id)
list(comments_replied_to).append(comment.id)
with open ("comments_replied_to.txt", "a") as f:
f.write(comment.id + "\n")
the error that it throws out is:
File "C:\Users\Blaze\Desktop\reddit_bot2.py", line 56, in <module>
comment.reply('* "Youve got to ask yourself one question: Do I feel lucky? Well, do ya punk?" ')
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\models\reddit\mixins\replyable.py", line 26, in reply
return self._reddit.post(API_PATH['comment'], data=data)[0]
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\reddit.py", line 483, in post
return self._objector.objectify(data)
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\objector.py", line 149, in objectify
raise APIException(*errors[0])
praw.exceptions.APIException: RATELIMIT: 'you are doing that too much. try again in 8 minutes.' on field 'ratelimit'
__During handling of the above exception, another exception occurred:__
Traceback (most recent call last):
File "C:\Users\Blaze\Desktop\reddit_bot2.py", line 65, in <module>
comment.reply('* "Youve got to ask yourself one question: Do I feel lucky? Well, do ya punk?" ')
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\models\reddit\mixins\replyable.py", line 26, in reply
return self._reddit.post(API_PATH['comment'], data=data)[0]
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\reddit.py", line 483, in post
return self._objector.objectify(data)
File "C:\Users\Blaze\AppData\Local\Programs\Python\Python37-32\lib\site-packages\praw\objector.py", line 149, in objectify
raise APIException(*errors[0])
praw.exceptions.APIException: RATELIMIT: 'you are doing that too much. try again in 6 seconds.' on field 'ratelimit'
Any and all help is appreciated, thank you.
It seems to me like you are waiting exactly the amount of time that it tells you to wait, but that Reddit has not finished cooling down. You should probably add like 10-30 seconds to your sleep time.
EDIT to format:
This is the original code
from __future__ import print_function
import socket
import sys
def socket_accept():
conn, address = s.accept()
print("Connection has been established | " + "IP " + address[0] + "| Port " + str(address[1]))
send_commands(conn)
conn.close()
def send_commands(conn):
while True:
cmd = raw_input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end ="")
def main():
socket_accept()
main()
I am getting this error “TypeError: str() takes at most 1 argument (2 given)” at “client_response” variable
You have your error here:
client_response = str(conn.recv(1024), "utf-8")
Just change it to:
client_response = str(conn.recv(1024)).encode("utf-8")
On the second to last line you're passing two arguments to the str function, although the str function only takes a single argument in Python 2. It does in fact take up to three arguments in python 3
https://docs.python.org/2.7/library/functions.html?highlight=str#str
https://docs.python.org/3.6/library/functions.html?highlight=str#str
So you're either trying to inadvertaetly run python 3 code in a python 2 interpreter or you're looking at the wrong language documentation.
So either use #franciscosolimas's answer, if you're using python 2, or make sure you're using python 3, if the latter you might also want to add a keyword argument just to make sure you know what's happening in the future
client_response = str(conn.recv(1024), encoding="utf-8")
3 arguments, 5 given
I got a similar error, may not be the same here (as the op) but, it was simple enough fix and wanted to share, since I ended up here from my searches on the error.
Traceback (most recent call last):
File "queries.py", line 50, in <module>
"WHERE ao.type='u';")
TypeError: str() takes at most 3 arguments (5 given)`
What fixed it for me in python3 was converting my ,'s to +
Error:
str("SELECT s.name + '.' + ao.name, s.name"
"FROM sys.all_objects ao",
"INNER JOIN sys.schemas s",
"ON s.schema_id = ao.schema_id",
"WHERE ao.type='u';"))
Fixed:
str("SELECT s.name + '.' + ao.name, s.name " +
"FROM sys.all_objects ao " +
"INNER JOIN sys.schemas s " +
"ON s.schema_id = ao.schema_id " +
"WHERE ao.type='u';")
I had to add my own spaces so the passed query would work.
As the commas were doing that in python...
Thoughts & my educated guess:
looks like in my case it got caught up trying to evaluate in bash/python a litteral u'
To my knowledge this break could be in bash because there is no command called u and/or in python u' is you trying to unicode an incomplete string. Either way it broke and wanted to share my fix.
Cheers!
~JayRizzo
I have two lists that have user name and password. I want to check which one is correct by iterating through two zipped lists but it isn't working.
Below is the traceback
Traceback (most recent call last):
File "C:\Users\mohamed\Downloads\second_PassWD_Test.py", line 27, in <module>
mme=tn.write(j,i)
TypeError: write() takes exactly 2 arguments (3 given)
Below is the code throwing the exception.
import telnetlib
import re
HOST = "192.168.1.1"
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
try:
tn = telnetlib.Telnet(HOST)
except:
print "Oops! there is a connection error"
frist_log = tn.read_until(":")
if "log" in frist_log:
while 1:
for i,j in zip(USER,PASS):
tn.write(j,i)
break
Telnet.write(buffer) only takes two arguments first is the telnet object and the other is a buffer to send to your session, hence your solution will throw an exception. One way to solve the problem is like a except script using the expect api and use a list of expected output as shown in example below
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
prompt = "#" ## or your system prompt
tn = telnetlib.Telnet(HOST)
first_log = tn.read_until(":")
for user,password in zip(USER,PASS):
try:
tn.write(user)
tn.expect([":"],timeout = 3) # 3 second timeout for password prompt
tn.write(password+"\n")
index,obj,string = tn.expect([":",prompt],timeout = 3)
found = string.find(prompt)
if found >= 0:
break # found the username password match break
###else continue for next user/password match
except:
print "exception",sys.exc_info()[0]
This question already has an answer here:
Python try except else invalid syntax?
(1 answer)
Closed 6 years ago.
Im just sitting for 10 minutes staring at a simple piece of code, which I have copied from a guide and I can't understand why I am getting an error.
def transformation(x):
date_format = "%d/%m/%Y"
try:
a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
else:
a = dt.datetime.strptime(x, date_format)
finally:
return a
File "<ipython-input-91-f1f6fe70d542>", line 5
else:
^
SyntaxError: invalid syntax
Maybe this is just me... Whats wrong?
After adding except:
def transformation(x):
date_format = "%d/%m/%Y"
try:
a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
except pass
else:
a = dt.datetime.strptime(x, date_format)
finally:
return a
File "<ipython-input-93-c2285c857574>", line 5
except pass
^
SyntaxError: invalid syntax
You need an except clause to use else:
The try ... except statement has an optional else clause, which, when
present, must follow all except clauses
[Emphasis mine]
I just saw it from the python document page, so I'm just gonna quote what it says to you:
The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
This question already has answers here:
Python print statement “Syntax Error: invalid syntax” [duplicate]
(2 answers)
Closed 8 years ago.
I am new to Python and I am trying to run the following lines in Python 3.4. The file is downloaded from Yelp.com and is ready-to-use:
url_params = url_params or {}
url = 'http://{0}{1}?'.format(host, path)
consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)
oauth_request.update(
{
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': TOKEN,
'oauth_consumer_key': CONSUMER_KEY
}
)
token = oauth2.Token(TOKEN, TOKEN_SECRET)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
print 'Querying {0} ...'.format(url)
In the last line:
print 'Querying {0} ...'.format(url) I get an error message: SyntaxError: invalid syntax
In Python 3 and up the argument to print has to be inside parenthesis:
print('Querying {0} ...'.format(url))
In Python 3x you have to put paranthesis in print function.
print ('Querying {0} ...'.format(url))
For example you can't do this;
print "hello"
You have to write that like;
print ("hello")