Can't print a json value - python

i have this code in python whoose purpose is to send a text file .c .txt (whatever, i've been sending a helloworld.c) through a websocket.
The problem is when i test it, the code doesn't go beyond print("I'm here!")
def onMessage_function(self, client_id, message):
print("Here's the message I received " + message + "\n\n\n")
dumpedMSG = json.dumps(message)
loadedMSG = json.loads(dumpedMSG)
if 'file_name' in loadedMSG:
print("I'm here!")
print(loadedMSG['file_name'])
else:
# do something else here.
Thank you!

It's hard to tell, but does this work?
def onMessage_function(self, client_id, message):
print("Here's the message I received " + message + "\n\n\n")
loadedMSG = json.loads(message)
if 'file_name' in loadedMSG:
print("I'm here!")
print(loadedMSG['file_name'])
else:
# do something else here.
In the original loadedMSG would be the same as message, so 'file_name' in loadedMSG would be a substring check rather than a check for a dictionary key. The print after "I'm here!" would then throw an exception, which you might not see if you're only receiving what is sent over the socket.

Related

How to send notification email when Exception Is Raised?

I have try except block inside for loop. If error happened I want to send an email saying "Error", if not, I need to send an email saying "Success".
code example:
for file in files:
try:
if file.endswith('.csv'):
# converting source variable to str because shutil has some bugs
shutil.move(str(source) + "/" + file, dest_fs01 / current_year_folder / current_year_month_folder)
break
except Exception as e:
error = str(e)
I tried something like this, but if there is no error, the variable error will not be existing
for file in files:
try:
if file.endswith('.csv'):
# converting source variable to str because shutil has some bugs
shutil.move(str(source) + "/" + file, dest_fs01 / current_year_folder / current_year_month_folder)
break
except Exception as e:
error = str(e)
if len(error) > 0:
# sending email notifying about error
message4 = """From: <from#email.com>
To: <to#email.com>
Subject: Error
""" + error
smtpObj.sendmail(sender, receivers, message4)
else:
# sending email notifying about successful completion
message3 = """From: <from#email.com>
To: <to#email.com>
Subject: Success

Python IRC Bot, distinguish from channel messages and private messages

I'm coding a simple IRC bot in Python. Actually, It can connect to a specific channel, read messages and send response, but it can't distinguish between channel messages and private messages.
Example:
John, connected to the same channel, send a private message to the Bot's chat, like "!say hello";
Bot have to send "hello" to the same private chat, only to John.
Instead, when bot read "!say hello" in channel's board, have to send "hello" to the channel.
My code:
ircmsg = connection.ircsock.recv(2048)
ircmsg_clean = ircmsg.strip(str.encode('\n\r'))
if ircmsg.find(str.encode("!say")) != -1:
try:
parts = ircmsg_clean.split()
content = parts[4]
connection.sendMsg(channel, content)
except IndexError:
connection.sendMsg(channel, "Invalid syntax")
Connection file:
def sendmsg(channel, msg):
ircsock.send(str.encode("PRIVMSG " + channel +" :" + msg + "\n"))
I know how to send a message to a specific user:
def sendPrivateMsg(username, msg):
ircsock.send(str.encode("PRIVMSG " + username + " :" + msg + "\n"))
But have to know from where the message came, channel or user, and send appropriate response.
Sorry for my bad english.
The source of the message is included in the protocol message, now you are just not using it.
In the part where you do this
parts = ircmsg_clean.split()
you get it in to the list parts.
If I remember correctly, and understand the RFQ right, the irc message you receive from the server looks something like this:
:John!something#something.org PRIVMSG BotName :Are you receiving this message ?
so splitting that would result in this:
[':John!something#something.org', 'PRIVMSG', 'BotName', ':Are', 'you', 'receiving', 'this', 'message', '?']
The sender of the message is that the first element parts, so parts[0]. You would need to strip away the extra ':'.
The target of the message is at parts[2], and that can be your name or the channel name, and you then need to compare the target to your own name to know if it is a message to you or to a channel.
If that is true, you can then do something like this:
source = parts[0].strip(':')
content = ' '.join(parts[3:]).strip(':')
connection.sendMsg(source, content)
Notice that the actual content of the message is also splitted, so you need to rejoin that into a string if you are doing it like that. If you are hitting that IndexError it means that you received a message that had only one word, since the first word is at index 3, not 4.

bot.polling funciton in a try-except block, do not run the rest of the code

In my python code, the polling function is in a try-except block
bot = telebot.TeleBot(TOKEN)
while True:
try:
status = "Conected"
bot.polling(none_stop=False, interval=1)
except:
status = "failure"
print status
#do something..
time.sleep(1)
but when bot.polling is executed, the script never print a status and do not run the rest of the code.
i try adding "block=True" bot.polling(none_stop=False, interval=1, block=True), but in that case, the polling dont get the telegram messages.
Apologies, my last answer wasn't as clear as it could have been.
So when working with try/except you'll want to make sure that you've got the indentation under the While look and the Try: and Except: (and Else, Finally if you're using them too).
Next, you want the action that you're looking for to take place in the try or except. So, here's what I'd do:
This would run and continuously loop once per second. If the loop's status was successful it would show connected, otherwise it would print "failure" then try the loop again one second later. If it returns an error it will print that it has an error. However, if you encounter an error it will then loop back to the top of the while True: loop. This is why you were not getting a print since the except instruction didn't include to print. Once the exception happens your code goes back to the top and tries again.
while True:
try:
status = "Connected"
bot.polling(none_stop=False, interval=1)
pass
except:
status = "failure"
print status
else:
print status
#do something..
time.sleep(1)
This tutorial is extremely helpful for getting up and running with these try catch loops.
https://docs.python.org/2/tutorial/errors.html
Here's an example of a try except I use that works:
token = 0
while token == 0:
print("Welcome to the back office.\nYou will need to log in to contine.")
sleep(1)
print("="*5 + " Please log in " +"="*5)
print(" ")
email = raw_input("Email: ")
print(" ")
password = getpass.getpass("Password: ")
authpayload = "grant_type=password&username=" + email + "&password=" + password
login = requests.post(url+'/token', data=authpayload) #testing
token = login.json()
try:
token = token["access_token"]
pass
except:
print(" ")
print("="*5 + " ERROR " +"="*5)
print(token)
print("Sorry please try logging in again.")
logging.info("user login failed " + str(token))
logging.info("user tried email: " + email)
token = 0
sleep(1)
else:
print(" ")
print("="*5 + " You're now logged in " +"="*5)
print(" ")
logging.info("user login succeeded")
logging.info("user email: " + email)
sleep(.5)
pass
In my case, I'm "Try"ing to see if the json response has an object with the key "access_token" if not, then I know something has gone wrong and I don't let the user continue. This then sends them back to the top since in the except area I make sure the token is set back to 0. Meaning this loop will run until my program receives a value for the access token.
I truly hope this helps! If it solves your problem please accept it!

How can I retrieve a Google Talk users Status Message

I'd like to be able to retrieve a users Google Talk Status Message with Python, it's really hard to find documentation on how to use some of the libraries out there.
I don't have anything to hand with xmpp installed, but here's some old code I had lying around that might help you. You'll want to update the USERNAME/PASSWORD to your own values for test purposes.
Things to note: users logged in to Google Talk get a random presence string on their userid: that doesn't matter if you are trying to get the status of some other user, but if you want to write some code so want to communicate with yourself you need to distinguish the user logged in from GMail or a GTalk client from the test program. Hence the code searches through the userids.
Also, if you read the status immediately after logging in you probably won't get anything. There's a delay in the code because it takes a little while for the status to become available.
"""Send a single GTalk message to myself"""
import xmpp
import time
_SERVER = 'talk.google.com', 5223
USERNAME = 'someuser#gmail.com'
PASSWORD = 'whatever'
def sendMessage(tojid, text, username=USERNAME, password=PASSWORD):
jid = xmpp.protocol.JID(username)
client = xmpp.Client(jid.getDomain(), debug=[])
#self.client.RegisterHandler('message', self.message_cb)
if not client:
print 'Connection failed!'
return
con = client.connect(server=_SERVER)
print 'connected with', con
auth = client.auth(jid.getNode(), password, 'botty')
if not auth:
print 'Authentication failed!'
return
client.RegisterHandler('message', message_cb)
roster = client.getRoster()
client.sendInitPresence()
if '/' in tojid:
tail = tojid.split('/')[-1]
t = time.time() + 1
while time.time() < t:
client.Process(1)
time.sleep(0.1)
if [ res for res in roster.getResources(tojid) if res.startswith(tail) ]:
break
for res in roster.getResources(tojid):
if res.startswith(tail):
tojid = tojid.split('/', 1)[0] + '/' + res
print "sending to", tojid
id = client.send(xmpp.protocol.Message(tojid, text))
t = time.time() + 1
while time.time() < t:
client.Process(1)
time.sleep(0.1)
print "status", roster.getStatus(tojid)
print "show", roster.getShow(tojid)
print "resources", roster.getResources(tojid)
client.disconnect()
def message_cb(session, message):
print ">", message
sendMessage(USERNAME + '/Talk', "This is an automatically generated gtalk message: did you get it?")

tweepy stream.filter() method doesn't work properly

i've got some problems with the tweepy api.
I'm just tryin to write a little app that gets me a stream of statuses of one user (ore more), but one would be fine to start with ;-)
now: my code is like that:
def main():
config = ConfigParser.ConfigParser()
config.read('twitter.cfg')
username = config.get('Twitter', 'username')
password = config.get('Twitter', 'password')
listener = StreamWatcherListener()
stream = tweepy.Stream(username, password, listener, timeout=None)
stream.filter('132897940')
in StreamWatcherListener I have a method "on_status" that prints the text of a status, whenever a new one arrives (everything seems to work, when I try stream.sample() instead of stream.filter())
the given ID is my testaccount, so whenever I tweet I should get some response in the console....but nothing happens.
when I try
curl -d #following http://stream.twitter.com/1/statuses/filter.json -uAnyTwitterUser:Password
in the terminal as I could find in the twitter api, everything runs fine.
So maybe I make wrong use of the filter()-method?
any suggestions?
-andy
I found it out myself
the stream.filter() method needs an array
so i had to code
stream.filter(['1234567'])
et voilĂ 
class TweetListener(StreamListener):
def on_status(self,status):
print "TWEET ARRIVED!!!"
print "Tweet Text : %s" % status.text
print "Author's name : %s" % status.author.screen_name
print "Time of creation : %s" % status.created_at
print "Source of Tweet : %s" % status.source
time.sleep(10)
return True
def on_error(self, status):
print status
if status == 420:
print "Too soon reconnected, Exiting!!"
return False
sys.exit()
def search_tweets():
twitterStream = Stream(connect().auth, TweetListener())
twitterStream.filter(track=['Cricket','Maths','Army','Sports'],languages = ["en"],async=True)
Here I used the async parameter, it runs each stream on a different thread.
Refer this link for documentation or more details.

Categories

Resources