xmpppy and Facebook Chat Integration - python

I'm trying to create a very simple script that uses python's xmpppy to send a message over facebook chat.
import xmpp
FACEBOOK_ID = "username#chat.facebook.com"
PASS = "password"
SERVER = "chat.facebook.com"
jid=xmpp.protocol.JID(FACEBOOK_ID)
C=xmpp.Client(jid.getDomain(),debug=[])
if not C.connect((SERVER,5222)):
raise IOError('Can not connect to server.')
if not C.auth(jid.getNode(),PASS):
raise IOError('Can not auth with server.')
C.send(xmpp.protocol.Message("friend#chat.facebook.com","Hello world",))
This code works to send a message via gchat, however when I try with facebook I recieve this error:
An error occurred while looking up _xmpp-client._tcp.chat.facebook.com
When I remove #chat.facebook.com from the FACEBOOK_ID I get this instead:
File "gtalktest.py", line 11, in
if not C.connect((SERVER,5222)):
File "/home/john/xmpppy-0.3.1/xmpp/client.py", line 195, in connect
if not CommonClient.connect(self,server,proxy,secure,use_srv) or secureNone and not secure: return self.connected
File "/home/john/xmpppy-0.3.1/xmpp/client.py", line 179, in connect
if not self.Process(1): return
File "/home/john/xmpppy-0.3.1/xmpp/dispatcher.py", line 302, in dispatch
handler['func'](session,stanza)
File "/home/john/xmpppy-0.3.1/xmpp/dispatcher.py", line 214, in streamErrorHandler
raise exc((name,text))
xmpp.protocol.HostUnknown: (u'host-unknown', '')
I also notice any time I import xmpp I get the following two messages when running:
/home/john/xmpppy-0.3.1/xmpp/auth.py:24: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
import sha,base64,random,dispatcher
/home/john/xmpppy-0.3.1/xmpp/auth.py:26: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
I'm fairly new to solving these kinds of problems, and advise, or links to resources that could help me move forward in solve these issues would be greatly appreciated. Thanks for reading!

I also started the same project, and was trapped into same problem. I found the solution too. You have to write the UserName of facebook (Hence You must opt one Username) and that too in small Caps. This is the most important part. Most probably you too like me would not be writing it in small Caps.

import xmpp
FACEBOOK_ID = "username#chat.facebook.com"
PASS = "password"
SERVER = "chat.facebook.com"
jid=xmpp.protocol.JID(FACEBOOK_ID)
client=xmpp.Client(jid.getDomain(),debug=['always'])
if not client.connect((SERVER,5222)):
raise IOError('Can not connect to server.')
if not client.auth(jid.getNode(),PASS):
raise IOError('Can not auth with server.')
message = xmpp.protocol.Message(frm=client.Bind.bound[0], to="-<#_ID_OF_FRIEND>#chat.facebook.com", typ="chat", body="Hello world",)
client.SendAndWaitForResponse(message)
This worked for me. Anyway, if you want to know the server response to your query, use Client.SendAndWaitForResponse instead of Client.send ;)

Related

Authentication failed with Jenkins using python API

I am trying to create a job using the python api. I have created my own config, but the authentication fails. It produces an error message:
File "/usr/lib/python2.7/dist-packages/jenkins/__init__.py", line 415, in create_job
self.server + CREATE_JOB % locals(), config_xml, headers))
File "/usr/lib/python2.7/dist-packages/jenkins/__init__.py", line 236, in jenkins_open
'Possibly authentication failed [%s]' % (e.code)
jenkins.JenkinsException: Error in request.Possibly authentication failed [403]
The config file I have created was copied from another job config file as it was the easiest way to build it:
I am using the import jenkins module.
The server instance I create is using these credentials:
server = jenkins.Jenkins(jenkins_url, username = 'my_username', password = 'my_APITOKEN')
Any help will be greatly appreciated.
Error 403 is basically issued when the user is not allowed to access the resource. Are you able to access the resource manually using the same credentials? If there are some other admin credentials, then you can try using those.
Also, I am not sure but may be you can try running the python script with admin rights.
As far as I know for security reasons in Jenkins 2.x only admins are able to create jobs (to be specific - are able to send PUT requests). At least that's what I encountered using Jenkins Job Builder (also Python) and Jenkins 2.x.

ca_certs_locater/__init__.py import error

I was trying to get authentication of my api.However,it always show the following import errors:
public_key=raw.input ('...')
secret_key=raw.input ('...')
client = upwork.Client(public_key, secret_key)
It is supposed to appear a url, however it shows that
" File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/upwork/client.py", line 118, in __init__
ca_certs=ca_certs_locater.get(),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ca_certs_locater/__init__.py", line 36, in get
raise ImportError()"
I don't know what I should do about the ca_certs_locater
Before instantiating the upwork client, modify the module's LINUX_PATH constant.
import upwork
# Set the certificate path within the module
upwork.ca_certs_locater.LINUX_PATH = '/path/to/my/cert.crt'
...
client = upwork.Client(public_key, secret_key, **credentials)
...
I had this same problem. The solution is indeed as the comment suggests to do what Python - SSL Issue with Oauth2 says in combination with following the "SSL Certificate Note" on https://pypi.python.org/pypi/python-upwork. I did the following:
Read https://github.com/upwork/python-upwork/issues/9
Downloaded cacert.pem from Python - SSL Issue with Oauth2
Set the HTTPLIB_CA_CERTS_PATH environment variable to /path/to/cacert.pem
Then, the import error went away. My use case was the upwork API and yours may be different but the solution is the same either way.

Python suds "RuntimeError: maximum recursion depth exceeded while calling a Python object"

I'm trying to consume a SOAP web service using Python suds but I am getting the error "RuntimeError: maximum recursion depth exceeded while calling a Python object".
According to the trace, there is infinite recursion at "suds/binding/multiref.py", line 69.
The web service I'm trying to access is http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl.
The method I'm trying to access is loadPathwayForId.
Here's the part of my code that consumes the web service:
from suds.client import Client
client = Client('http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl')
pathway = client.service.loadPathwayForId(2470946)
I'm not sure what is responsible for the infinite recursion. I tried to look up this problem and there has been reports of issues with suds and infinite recursion, but the traces are different than mine (the recursive code is different), so I suspect my problem has other origins.
The full trace:
File "C:\Python27\lib\suds\bindings\multiref.py", line 69, in update
self.update(c)
File "C:\Python27\lib\suds\bindings\multiref.py", line 69, in update
self.update(c)
...
File "C:\Python27\lib\suds\bindings\multiref.py", line 69, in update
self.update(c)
File "C:\Python27\lib\suds\bindings\multiref.py", line 69, in update
self.update(c)
File "C:\Python27\lib\suds\bindings\multiref.py", line 67, in update
self.replace_references(node)
File "C:\Python27\lib\suds\bindings\multiref.py", line 80, in replace_references
href = node.getAttribute('href')
File "C:\Python27\lib\suds\sax\element.py", line 404, in getAttribute
prefix, name = splitPrefix(name)
File "C:\Python27\lib\suds\sax\__init__.py", line 49, in splitPrefix
if isinstance(name, basestring) \
RuntimeError: maximum recursion depth exceeded while calling a Python object
Thanks in advance for the help!
After more testing, it seems that (unfortunately) suds has trouble interpreting Java Collection objects serialized as XML. I ended up using SOAPpy instead to avoid this issue. If someone can suggest a fix, that would be awesome! I really like suds for its other merits over SOAPpy.
I tried lots of SUDS versions and forks, and finally got to find one that works with proxies, https and authenticated services, find it here:
https://github.com/unomena/suds
Also, here is example code showing simple usage:
from suds.client import Client
# SOAP WSDL url
url = 'https://example.com/ws/service?WSDL'
# SOAP service username and password for authentication, if needed
username = 'user_name'
password = 'pass_word'
# local intranet proxy definition to get to the internet, if needed
proxy = dict(http='http://username:password#localproxy:8080',
https='http://username:password#localproxy:8080')
# unauthenticaded, no-proxy
# client = Client(url)
# use a proxy to connect to the service
# client = Client(url, proxy=proxy)
# no proxy, authenticathed service
# client = Client(url, username=username, password=password)
# use a proxy to connect to an authenticated service
client = Client(url, proxy=proxy, username=username, password=password)
print client

DNS query using Google App Engine socket

I'm trying to use the new socket support for Google App Engine in order to perform some DNS queries. I'm using dnspython to perform the query, and the code works fine outside GAE.
The code is the following:
class DnsQuery(webapp2.RequestHandler):
def get(self):
domain = self.request.get('domain')
logging.info("Test Query for "+domain)
answers = dns.resolver.query(domain, 'TXT', tcp=True)
logging.info("DNS OK")
for rdata in answers:
rc = str(rdata.exchange).lower()
logging.info("Record "+rc)
When I run in GAE I get the following error:
File "/base/data/home/apps/s~/one.366576281491296772/main.py", line 37, in post
return self.get()
File "/base/data/home/apps/s~/one.366576281491296772/main.py", line 41, in get
answers = dns.resolver.query(domain, 'TXT', tcp=True)
File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 976, in query
raise_on_no_answer, source_port)
File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 821, in query
timeout = self._compute_timeout(start)
File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 735, in _compute_timeout
raise Timeout
Which is raised by dnspython when no answer is returned within the time limit. I've raised the timelimit to 60 seconds, and DnsQuery is a task, but still getting the same error.
Is there any limitation in Google App Engine socket implementation, which prevents the execution of DNS requests ?
This is a bug and will be fixed ASAP.
As a workaround, pass in the source='' argument to dns.resolver.query.
tcp=True is not necessary.
No. There is no limit on UDP ports. (only smtp ports on TCP).
It is possible there is an issue with the socket service routing. Please file an issue with the app engine issue tracker. https://code.google.com/p/googleappengine/issues/list
dnspython is using socket. However, socket is only available in paid apps.1

Python login to email server authentication error

I am on a Linux machine. My company has an email exchange server which is already configured. I am using a Python script to try to login to the email server so that I can send an email programmatically. Here is what I have so far -
server = smtplib.SMTP('email-0.abc.com', 25)
server.set_debuglevel(1)
server.ehlo_or_helo_if_needed()
server.login('abc/johndoe', 'pwd')
However, at the server.login command, I get an error as
raise SMTPException("No suitable authentication method found.")
SMTPException: No suitable authentication method found.
Anyone know what the problem is please?
Thanks
You might need to switch to STARTTLS authentication. Here's an example that helped me.
How To Send Email In Python Via SMTPLIB
It seems that your Mail Server is rejecting the plain Authentication method.
What server do you use?
If MS Exchange please see this article: http://www.exchangeinbox.com/article.aspx?i=93
I was getting the same error. My case could be the different from yours but error is same as you mentioned.
In my scenario, I don't have to pass the username and password for authentication as server IP was added in white-list of SMTP mail server. And I was passing username and password for authentication which was giving me the error stating "No suitable authentication method found."
This may not be the case with you but I just thought to share the my experience for the same kind of error so that anyone coming to this thread can benefit from it.
Thanks.
The Exchange server I was connecting to, required NTLM authentication, which is not supported by smtplib out of the box.
As of this writing (January 2022) and according to my modest research, the most maintained Python library that solves this problem, is pyspnego. The following snippet was provided by the library author and worked for me without any modifications:
import base64
import spnego
from smtplib import SMTPException, SMTPAuthenticationError
def ntlm_authenticate(smtp, username, password):
auth = spnego.client(username, password, service="SMTP", protocol="ntlm")
ntlm_negotiate = auth.step()
code, response = smtp.docmd("AUTH", "NTLM " + base64.b64encode(ntlm_negotiate).decode())
if code != 334:
raise SMTPException("Server did not respond as expected to NTLM negotiate message")
ntlm_challenge = base64.b64decode(response)
ntlm_auth = auth.step(ntlm_challenge)
code, response = smtp.docmd("", base64.b64encode(ntlm_auth).decode())
if code != 235:
raise SMTPAuthenticationError(code, response)

Categories