我是Python的新手,需要一些帮助通过OAuth2验证Chatbot。我使用sleekxmpp
为python设置了Google Talk聊天机器人。它附带了一个名为“google”的内置插件,我不知道如何使用。
1)我在Googles Developer Console上设置了一个服务帐户,该帐户为我提供了一个JSON密钥,然后我通过oauth2client
请求了一个范围为GTalk的访问令牌。
def oAuthPing():
json_key = json.load(open(credentialsPath))
jid = json_key['client_email']
scope = ['https://www.googleapis.com/auth/googletalk']
accessToken = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
return accessToken, jid
2)发送聊天:
def sendPing(toPerson, toPersonMessage, accessToken, jid):
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
else:
raw_input = input
xmpp = SendMsgBot.SendMsgBot(jid, toPerson, unicode(toPersonMessage))
xmpp.credentials['access_token'] = accessToken
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0004') # date form
xmpp.register_plugin('google') # oAuth2
xmpp.register_plugin('xep_0199') # XMPP Ping
# Connect to the XMPP server and start processing XMPP stanzas.
if xmpp.connect(('talk.google.com', 5222)):
xmpp.process(block=True)
else:
print("Unable to connect to Google Talk")
3)SendMsgBot类:
class SendMsgBot(sleekxmpp.ClientXMPP):
"""
A basic SleekXMPP bot that will log in, send a message,
and then log out.
"""
def __init__(self, jid, recipient, message):
sleekxmpp.ClientXMPP.__init__(self, jid, 'ignore')
# The message we wish to send, and the JID that
# will receive it.
self.recipient = recipient
self.msg = message
# The session_start event will be triggered when
# the bot establishes its connection with the server
# and the XML streams are ready for use. We want to
# listen for this event so that we we can initialize
# our roster.
self.add_event_handler("session_start", self.start)
def start(self, event):
"""
Process the session_start event.
Typical actions for the session_start event are
requesting the roster and broadcasting an initial
presence stanza.
"""
self.send_presence()
self.get_roster()
self.send_message(mto=self.recipient,
mbody=self.msg,
mtype='chat')
# Using wait=True ensures that the send queue will be
# emptied before ending the session.
self.disconnect(wait=True)
非常感谢任何帮助。感谢。