Hello there im trying to send a message with yowsup but i have not been successful can you please help me im getting IndentationError: unexpected indent Thank you
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.common.tools import Jid
class EchoLayer(YowInterfaceLayer):
#ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
if messageProtocolEntity.getType() == 'text':
self.onTextMessage(messageProtocolEntity)
reply = 1
messageEntity = TextMessageProtocolEntity(reply,to = messageProtocolEntity.getFrom())
self.toLower(messageEntity)
self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom()))
self.toLower(messageProtocolEntity.ack())
self.toLower(messageProtocolEntity.ack(True))
#ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
self.toLower(entity.ack())
def onTextMessage(self,messageProtocolEntity):
# just print info
print("Echoing %s to %s" % (messageProtocolEntity.getBody(), messageProtocolEntity.getFrom(False)))
IndentationError: unexpected indent
This is a common kind of problem every pythoner has hit with. your code has some extra space or any tab is used.so basically you have to check every line and manually remove the excess gaps(shortcuts) and replace them with spaces insted.
The Unexpected indent error message will always tell you what line the problem is detected on.
In your case, it's obviously due to the fact that the if and reply lines don't match up.
Related
I'm pretty new to python and just learning to ropes. In the code bellow I have a function taking several inputs from a json string. I'm attempting to have a return output in the specified strings. Problem? when I run the file I get nothing... I'm sure I'm missing something incredibly simply, but for the life of me I can't figure out what. I've attempted to use return as well as print at the end of the function. No cheese.
Help?
Here's what I've got so far:
import datetime, json
def jeeves(request): #defines the function
message=''
if request['type']=='maintainance':
message='Thank you tenant at unit'+str(request['unit'])+', your request for maintenance to deal with '+'"'+str(request['issue'])+'"'+' has been received #2 input'
elif request['type']=='purchase':
message='Thank you tenant at unit'+str(request['unit'])+'your request to purchase a'+str(request['commodity'])+ ' has been received'
elif request['type']=='reservation':
startTime=request['date'].split(" ")[1]
startTime=startTime.split('')
time=0;
num=[]
for item in startTime:
if isdigit(item):
num.append(item)
for index in range(len(num)):
time+=num[index]*10**(len(num)-index)
endTime=0
daySplit=''.join(startTime[-2:])
if time+int(request['duration'].split(' ')[0])>12:
endTime=time+int(request['duration'].split(' ')[0])-12
if daySplit=='AM':
endTime=str(endTime)+'PM'
else:
endTime=str(endTime)+'AM'
else:
endTime=endTime+int(request['duration'].split(' ')[0])
endTime=str(endTime)+daySplit
message='Thank you tenant at unit'+str(request['unit'])+'your request to reserve our '+str(request['location'])+' on '+str(request['date'].split(' ')[0])+' from '+str(request['date'].split(' ')[1])+' to '+ endTime+' has been received'
elif request['type']=='complaint':
message='Thank you tenant at unit'+str(request['unit'])+' we will have someone follow up on '+'"'+request['issue']+'"'+' in regards to our '+request['location']
return message
print message
json.dumps(jeeves({"type":"maintenance", "unit":221, "issue":"Air filter needs replacing"}))
ps: I'm new to coding in general. If there is a better, more productive way for me to ask questions, I'm open to feedback. Thank you in advanced.
You have to put return before the print function because when you use return it ends a function. You might also want to check out what return actually does here
I am attempting to use Brickman to use Python coding on a LEGO EV3. When I try to run my code I get the following error
>>robot#ev3dev:~$ python3 CoffeePi_Test/Main.py
File "CoffeePi_Test/Main.py", line 14
tags=[‘coffeepi’]
^
SyntaxError: invalid character in identifier
Here is my code. I am not sure what is triggering this error.
#!/usr/bin/env python3
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import time
import vending
import ev3dev.ev3 as ev3
from ev3dev.auto import *
tags=[legovend]
words=[]
#Variables that contains the user credentials to access Twitter API
#Two versions, redudancy if the first fails...
access_token = # redacted
access_token_secret = # redacted
consumer_key = # redacted
consumer_secret = # redacted
access_token2 = # redacted
access_token_secret2 = # redacted
consumer_key2 = # redacted
consumer_secret2 = # redacted
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
global mA,mB,home,cs, lastVend
try:
tweet = json.loads(data)
tw
except:
pass
if tags:
if all(tag in tweet['text'].lower() for tag in tags):
print (tweet['user']['screen_name'], ' - ', tweet['text'])
if int(tweet['timestamp_ms'])>lastVend:
ev3.Leds.set_color(ev3.Leds.LEFT, ev3.Leds.RED)
ev3.Leds.set_color(ev3.Leds.RIGHT, ev3.Leds.RED)
vending.onTweet(mA, mB, cs, home)
time.sleep(2)
lastVend = int(round(time.time() * 1000))+1000
ev3.Leds.set_color(ev3.Leds.LEFT, ev3.Leds.GREEN)
ev3.Leds.set_color(ev3.Leds.RIGHT, ev3.Leds.GREEN)
return True
def on_error(self, status):
print( status)
return False
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
print( 'here')
global mA,mB,home,cs, lastVend
mA = ev3.MediumMotor('outA')
mB = ev3.MediumMotor('outB')
home = mA.position - 40
cs=ColorSensor()
lastVend = int(round(time.time() * 1000))
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
auth2 = OAuthHandler(consumer_key2, consumer_secret2)
auth2.set_access_token(access_token2, access_token_secret2)
stream2 = Stream(auth2, l)
try:
Sound.speak('Ready to go').wait()
print ('trying 1')
stream.filter(track=tags)
print('trying 2')
stream2.filter(track=tags)
Sound.speak('Could not connect').wait()
except Exception as e:
print( e)
Humor is usually not welcome on stackoverflow, but there are exceptions from this rule so let's this answer be such exception.
But let's go back to answering the actual question:
Can't determine cause of SyntaxError: invalid character in identifier
I am not sure what is triggering this error.
I have to admit that I write this fully correct answer with a chuckle :) :
The cause of the SyntaxError is an invalid character in identifier.
The invalid character in the identifier is the character:
[ ’ ]
U+2019 ’ e2 80 99 RIGHT SINGLE QUOTATION MARK
Here Python code with which you can find out for yourself details about the "character" which is causing the trouble:
#!/usr/bin/ python3
# -*- coding: <utf8> -*-
# tags=[’coffeepi’]
coffeepi = "’"
print(ord(coffeepi), hex(ord(coffeepi)), bin(ord(coffeepi)))
what prints:
8217, 0x2019 , 0b10000000011001
Check out this here
http://www.utf8-chartable.de/unicode-utf8-table.pl
where I have got the information about the character from, and this here
https://docs.python.org/3/reference/lexical_analysis.html#identifiers
for more detailed information about which characters are allowed in an indentifier, because not all are and apparently this one does not belong to the range of allowed characters.
By the way: this "character" is NOT a one byte character like it is for ASCII characters. How this character is encoded in UTF-8 is specified in the Unicode table (e2 80 99).
AND ... in the entire code you have provided in the question there is no trace of what you have specified to cause the error message.
How you can fix that?
Just replace these strange quotes with standard quotes " "
ADDENDUM: The strange quotes should be probably standard quotes around a string with a word put into the list. As the Python interpreter is running into this strange quotes it assumes they are part of a variable name (identifier) and not part of a string specification. That is the reason for the confusing error message as you don't see from the code at the first glance WHY the Python interpreter thinks it deals with an variable name (identifier) and not a quoted section of text which should be turned into a Python string.
I'm quite new with ARI scripting for Asterisk, and I've been trying to make some script to handle a 1 to 1 communication with ari-py in python. I've been following the example that provided in the asterisk wiki and so far so good. But when I try to create a call, the recipient always keep ringing, even if I have answered it. Is there something wrong with how I handle the call? Here's my script
def stasis_start_cb(self, channel, ev):
"""Handler for StasisStart event"""
chan = channel.get('channel')
chan.answer()
print "Channel %s has entered the application" % chan.json.get('name')
outgoing = client.channels.originate(endpoint="SIP/1002", extension='1002', callerId='Tes', app='channel-dump', appArgs='dialed')
I tried using OOP to simplify the function usage, are there anything wrong with that script? And here's another script trying to make a call by using a bridge:
def outgoing_call(self,channel):
try:
outgoing = client.channels.originate(endpoint="SIP/1002", app='channel-dump', appArgs='dialed')
except requests.HTTPError:
channel.hangup()
return
def outgoing_start(self, bri, channel):
channel.answer()
self.addChan(channel, bridge)
def stasis_start(self, channel, ev):
chan = channel.get('channel')
name = chan.json.get('name')
"""ars = ev.get('args')
if not ars:
print "Error: {} didn't provide any arguments!".format(name)
return
if ars and ars[0] != 'inbound':
return
if len(ars) != 2:
print "Error: {} didn't tell us who to dial".format(name)
chan.hangup()"""
print "Channel {} entered the application".format(name)
chan.ring()
self.outgoing_call(chan)
self.outgoing_start(bridge, chan)
Both the client is able to be added in the bridge, and I can make a call, but the problem still persist, the recipient keep saying they are ringing despite I have answered the call
Turns out, the problem is in here
def outgoing_call(self,channel):
try:
outgoing = client.channels.originate(endpoint="SIP/1002", app='channel-dump', appArgs='dialed')
except requests.HTTPError:
channel.hangup()
return
As the dialed number answer the call, they uses the same script, so they ended up calling themselves again. A simple if condition to make the dialed number not call to itself again is all that is needed
Recently I've deployed a python bot on Heroku and every time I try to run it, this error pops up.
2016-12-28 T04:32:08.770156+00:00 app[worker.1]:File "bot.py", line 43
2016-12-28 T04:32:08.770168+00:00 app[worker.1]: else:
2016-12-28 T04:32:08.770171+00:00 app[worker.1]:^
2016-12-28 T04:32:08.770172+00:00 app[worker.1]: IndentationError: expected an indented block
Here's the code block it refers to. I do understand the error they throwing but can't see the cause? (Code was from a Git repository.)
class listener(StreamListener):
def on_data(self, raw_data):
try:
retweet_ed = raw_data.lower().split('"retweeted":')[1].split(',"possibly_sensitive"')[0].replace(",", "")
tweet_text = raw_data.lower().split('"text":"')[1].split('","source":"')[0].replace(",", "") #tweet's text
screen_name = raw_data.lower().split('"screen_name":"')[1].split('","location"')[0].replace(",", "") #tweet's authors screen name
tweet_sid = raw_data.split('"id":')[1].split('"id_str":')[0].replace(",", "") #tweet's id
if not any(a_acc == screen_name.lower() for a_acc in whitelist_acc):
if not any(acc == screen_name.lower() for acc in banned_accs):
if not any(a_wrds in screen_name.lower() for a_wrds in whitelist_words):
if not any(word in tweet_text.lower() for word in banned_words):
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
else:
pass
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
return True
except Exception as e:
print(str(e)) # prints the error msg, if u dont want it comment it out
pass
Can someone help? Give me an eye? or do roast me XD
First, you cannot have no code under the if statement. That is the most likely culprit and you can fix this by adding pass in that block. If you want to test this for yourself, you can run the following very simple example and verify that the interpreter gives an error when you try to run it.
if 1 == 1:
else:
print "This will never print."
Second, it is difficult to tell because of re-encoding on SO, but you may also have mixed spaces and tabs incorrectly. If you are using vim, you can do set list to show the invisible characters and make sure you are consistent.
Your code has an if statement with no instructions:
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
Python expects an indent, but since everything is commented out, there is none.
This is basically what the error indicates:
2016-12-28 T04:32:08.770168+00:00 app[worker.1]: else:
2016-12-28 T04:32:08.770171+00:00 app[worker.1]:^
2016-12-28 T04:32:08.770172+00:00 app[worker.1]: IndentationError:
expected an indented block
You cannot have an else statement that is not following an indented block (that is, an if block, or even a for).
If you want to keep the if in plain code, add a pass statement, as for the following else:
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
pass
Then, the code will not raise any IndentationError.
You need to include something in the if statement. Just type
pass
Or set a useless variable for now.
And also, indent everything by one indent I think (because of the first line, correct me if I'm wrong.)
name = form.getvalue('name')
age = form.getvalue('age') + 1
next_age1 = int(form["age"].value
print "Content-type: text/html"
print
print "<html><head>"
print "<p> Hello, %s</p>" % (name)
print "<p> Next year, you will be %s years old.</p>" % next_age1
Having trouble understanding why this doesn't work.
Can someone please help me?
Thank you!
You are missing a closing parenthesis:
next_age1 = int(form["age"].value
# ----^ -------^ nothing here
Rule of thumb: when you get a syntax error you cannot immediately spot on that line, look at the previous line to see if you balanced your parenthesis and braces properly.