How can I retrieve a Google Talk users Status Message - python

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?")

Related

How to parse credential args to a function handling imaplib protocols

I have a list of emails(mine) that I want to test against a list of passwords(All valid and some none valid of course) using imaplib library. Whenever I test the program ordinarily like in the code below, it works perfectly no errors.
import sys
import imaplib
# connect to host using SSL
imap_host = 'imap.server.com'
imap_port = '993'
imap_user = 'username#email'
imap_pass = 'RightPassword'
imap = imaplib.IMAP4_SSL(imap_host, imap_port)
## login to server
try:
login = imap.login(imap_user, imap_pass)
if login:
print login
except imaplib.IMAP4.error as error:
print error
#
But whenever I run the code such as to parsing credentials through a function to handle the authentication protocols such as the following code below, I get an error saying
"LOGIN command error: BAD ['Missing \'"\'']".
I have tried all sort of things I could find using google and non seem to handle it properly.
"""
E-mail Tester
NB: This is for educational purpose only.
"""
import sys
import imaplib
EMAILS_FILE = open('email_list.txt', 'r')
PASSWORD_FILE = open('pass_list.txt', 'r')
SUCCESS_FILE = open('success.txt', 'a')
EMAILS_FILE_LIST = []
def set_check(_emails):
email = str(_emails)
PASSWORD_FILE.seek(0)
for passwords in PASSWORD_FILE:
password = str(passwords)
# connect to host using SSL
imap_host = 'imap.server.com'
imap_port = '993'
imap = imaplib.IMAP4_SSL(imap_host, imap_port)
## login to server
try:
# print "%s%s" % (email,password)
# print "I got here so far"
# sys.exit()
print "Testing <--> E-mail: %s - Password: %s" % (email, password)
login = imap.login("%s","%s" % (email, password))
if login:
print login
print "OK <---> E-mail: %s\nPassword: %s" % (email, password)
except imaplib.IMAP4.error as error:
print error
for emails in EMAILS_FILE:
EMAILS_FILE_LIST.append(emails)
for email_count in range(0, len(EMAILS_FILE_LIST)):
set_check(EMAILS_FILE_LIST[email_count])
I have tried all kind of suggestions I could find on the internet but non has worked thus far.
I expect imap.login to handle the authentication without the mysterious error output
"LOGIN command error: BAD ['Missing \'"\'']"
login = imap.login("%s","%s" % (email, password))
does not work. It throws an error in Python: TypeError: not all arguments converted during string formatting, because you're providing two strings to one %s.
Why don't you just use imap.login(email, password)? It has the same effect as what you're trying to do.
And what does your password file look like? What is it actually sending? Please provide the log line before it crashes. (anonymizing if necessary, but leaving any punctuation in for help diagnosing)
Okay, so I actually got this fixed by removing trail lines from my strings.
email = str(_emails).rstrip()
PASSWORD_FILE.seek(0)
for passwords in PASSWORD_FILE:
password = str(passwords).rstrip()
the error is caused by trail lines in the strings.

Display DM sender's username (Twitter)

I've got this code, where it basically authenticates to Twitter and streams Direct Messages directly (as soon as I send/receive, the message sent/received gets printed).
from twitter import *
import os
APP_KEY,APP_SECRET = 'appkey123', 'appsecret123'
MY_TWITTER_CREDS = os.path.expanduser('my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("crypto sentiments", APP_KEY, APP_SECRET,
MY_TWITTER_CREDS)
oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)
auth = OAuth(
consumer_key=APP_KEY,
consumer_secret=APP_SECRET,
token=oauth_token,
token_secret=oauth_secret
)
twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com')
for msg in twitter_userstream.user():
print(msg)
if 'direct_message' in msg:
print (msg['direct_message']['text'])
My question: How can I modify this code so it displays the username of the sender? Like so: #Jack: Hey there!
Simple and dirty way (you could do something far nicer with the string formatting) would be something like
for msg in twitter_userstream.user():
print(msg)
if 'direct_message' in msg:
print ('#' + msg['direct_message']['screen_name'] + ': ' + msg['direct_message']['text'])
It is worth noting that Twitter's user streams will be going away in June, so you should look at the new Account Activity API instead. More details in this announcement.

Subscription with selector does not work from python - stomp.py

I have run into a problem where a Python subscriber using stomp (stomp.py) with a message selector does not receive the messages it should. Interestingly enough, it appears to me at least that the problem is somehow with the sending of the message and not the subscription.
I am using ActiveMQ.
Here's the subscriber code:
class Listener(object):
def __init__(self, count):
if count <= 0:
count = float('inf')
self.count = count
def on_error(self, headers, message):
print("=" * 72)
print('RECEIVED AN ERROR.')
print('Message headers:')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(headers)
print('Message body:')
print(message)
def on_message(self, headers, message):
print("=" * 72)
print('Message headers:')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(headers)
print('Message body:')
print(message)
def main():
global conn
args = parse_args()
conn = stomp.Connection([(args.host, args.port)])
conn.set_listener('Listener', Listener(args.count))
conn.start()
conn.connect(login=args.user, passcode=args.password)
if (args.selector):
conn.subscribe(
destination=args.destination,
id=1,
ack='auto',
headers={'selector': args.selector}
)
else:
conn.subscribe(
destination=args.destination,
id=1,
ack='auto'
)
Now I can run this subscriber with a selector such as "type = 'test'".
If I publish a message using Java JMS, the message is received just fine. However, if I publish the identical message from Python it is not.
Here's the relevant Python publishing code:
headers = {}
headers['type'] = 'test'
conn = stomp.Connection12([(args.host, args.port)], auto_content_length=False)
conn.start()
conn.connect(login=args.user, passcode=args.password)
conn.send(body=body, headers=headers, destination=args.destination)
conn.disconnect()
print 'Message sent.'
Some interesting notes from my testing and debugging:
Running the subscriber with a selector receives a matching message sent from Java JMS but not from Python.
Running the subscriber with no selector receives a message sent from Java and also a message sent from Python.
fairly old, but I was currently facing the same issue and so I would like to leave a possible solution here.
At first, according to the documentation, you can provide a field called selectorwith SQL like syntax and should be part of the headers. In your example:
headers = {}
headers['selector'] = "type='test'"
conn = stomp.Connection12([(args.host, args.port)], auto_content_length=False)
conn.start()
conn.connect(login=args.user, passcode=args.password)
conn.send(body=body, headers=headers, destination=args.destination)
conn.disconnect()
print 'Message sent.'
I was also facing the error, that I could not receive any message send from JMS, but after a lot of reading, I found here, that there is a field name JMSType. I changed the code to
headers['selector'] = "type='test' OR JMSType='test'"
With that JMSType in there everything works like expected. Hope that helps somebody

error message "(#12) fql is deprecated for versions v2.1 and higher"

I tried to fetching facebook messages using python script which is mentioned in the code below :
#!/usr/bin/python
import sys
from facepy import GraphAPI
from facepy import exceptions
#Acces token with expire time = 60days
LONG_LIVE_ACCESS_TOKEN = 'EAAZA7IlqBfvkBAKOjc7esSqY1VRJdsMkZC6QXM2mVlAwZAWjOiZA2ywalERBjLk4tzvZBu8JvoWvLRGcTtyZAGl482ueUI1o6MWjkK44y3TeoVKjYBayO5DSIP3Q1poVEa8hO8xZAXdScohEAgiFTtpvVQGk2nZB694ZD'
#Facebook app id and secret from http://developer.facebook.com/apps
APP_ID = '1824237337804537'
SECRET_KEY = 'ee788eb9bea6d36f5f40e52530248f55'
def user_id_to_username(userid):
""" Function to convert facebook USERID to username. """
if userid is not None:
userid = '/{0}'.format(userid)
try:
return graph.get(userid)['name']
except (exceptions.FacebookError, exceptions.OAuthError) as e:
print e.message
sys.exit(0)
def get_message_author(message_list):
return user_id_to_username(message_list['snippet_author'])
def get_message_author_id(message_list):
return message_list['snippet_author']
def get_message_body(message_list):
return message_list['snippet']
def get_recipients_list(message_list):
author = get_message_author_id(message_list)
temp = message_list['recipients']
temp.remove(author)
return ", ".join(map(user_id_to_username, temp))
def pretty_print(message_list):
for message in message_list:
print "from: ", get_message_author(message)
print "to: ", get_recipients_list(message)
print "Message: ", get_message_body(message)
print "-" * 140
graph = GraphAPI(LONG_LIVE_ACCESS_TOKEN)
#Output of the facebook query language(FQL)
#This FQL queries for message body, author, recipients for unread messages.
try:
json_output = graph.fql('SELECT snippet, snippet_author, recipients FROM thread WHERE folder_id = 0 and unread != 0 Limit 4')
except exceptions.OAuthError as e:
print e.message
sys.exit(0)
message_list = json_output['data']
if message_list:
pretty_print(message_list)
else:
print "No New Messages"
sys.exit(0)
on executing this script it shows the error message :
(#12) fql is deprecated for versions v2.1 and higher
FQL is deprecated and will be completely unsupported by Facebook by August 8, 2016. Facebook Query Language (FQL) Reference:
As of August 8, 2016, FQL will no longer be available and cannot be
queried. To migrate your app, use the API Upgrade Tool to see the
Graph API calls you can make instead.

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