diff --git a/compute/xmpp_wikibot/README.md b/compute/xmpp_wikibot/README.md deleted file mode 100644 index e1dd45ecd56..00000000000 --- a/compute/xmpp_wikibot/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Wikibot example that can be run on Google Compute Engine - -[![Open in Cloud Shell][shell_img]][shell_link] - -[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png -[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=compute/xmpp_wikibot/README.md - -This sample shows how to use the [SleekXMPP](http://sleekxmpp.com/index.html) -client and [Flask](http://flask.pocoo.org/) to build a simple chatbot that can -be run on [Google Compute Engine](https://cloud.google.com/compute/). The -chatbot does two things: - -1. Sends messages to XMPP users via http get: - * The server is running on port 5000 - * if running on virtual machine use: - `http://:5000/send_message?recipient=&message=` - * If running locally use: - `http://localhost:5000/send_message?recipient=&message=` - -2. Responds to incoming messages with a Wikipedia page on the topic: - * Send a message with a topic (e.g., 'Hawaii') to the XMPP account the - server is using - * It should respond with a Wikipedia page (when one exists) - -## Setup - -Follow the instructions at the -[Compute Engine Quickstart Guide](https://cloud.google.com/compute/docs/quickstart-linux) -on how to create a project, create a virtual machine, and connect to your -instance via SSH. Once you have done this, you may jump to -[Installing files and dependencies](#installing-files-and-dependencies). - -You should also download the [Google Cloud SDK](https://cloud.google.com/sdk/). -It will allow you to access many of the features of Google Compute Engine via -your local machine. - -**IMPORTANT** You must enable tcp traffic on port 5000 to send messages to the -XMPP server. This can be done by running the following SDK commands: - - gcloud config set project - - gcloud compute firewall-rules create wikibot-server-rule --allow tcp:5000 --source-ranges=0.0.0.0/0 - -Or you can create a new firewall rule via the UI in the -[Networks](https://console.cloud.google.com/networking/networks/list) section of -the Google Cloud Console. - -### Installing files and dependencies - -First, install the `wikibot.py` and `requirements.txt` files onto your remote -instance. See the guide on -[Transferring Files](https://cloud.google.com/compute/docs/instances/transfer-files) -for more information on how to do this using the Mac file browser, `scp`, or -the Google Cloud SDK. - -Before running or deploying this application, you must install the dependencies -using [pip](http://pip.readthedocs.io/en/stable/): - - pip install -r requirements.txt - - -## Running the sample - -You'll need to have an XMPP account prior to actually running the sample. -If you do not have one, you can easily create an account at one of the many -XMPP servers such as [xmpp.jp](http://xmpp.jp). -Once you have an account, run the following command: - - python wikibot.py -j '' -p '' - -Where the username (e.g., 'bob@xmpp.jp') and password for the account that -you'd like to use for your chatbot are passed in as arguments. - -Enter control-C to stop the server - - -### Running on your local machine - -You may also run the sample locally by simply copying `wikibot.py` to a project -directory and installing all python dependencies there. diff --git a/compute/xmpp_wikibot/requirements-test.txt b/compute/xmpp_wikibot/requirements-test.txt deleted file mode 100644 index 95ea1e6a02b..00000000000 --- a/compute/xmpp_wikibot/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==6.2.4 diff --git a/compute/xmpp_wikibot/requirements.txt b/compute/xmpp_wikibot/requirements.txt deleted file mode 100644 index dfadd38f931..00000000000 --- a/compute/xmpp_wikibot/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -Flask==2.0.2 -requests==2.26.0 -sleekxmpp==1.3.3 -six==1.16.0 diff --git a/compute/xmpp_wikibot/wikibot.py b/compute/xmpp_wikibot/wikibot.py deleted file mode 100644 index a65c67c235c..00000000000 --- a/compute/xmpp_wikibot/wikibot.py +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wikibot server example using SleekXMPP client library""" - -import argparse -import getpass -import json -import re -import sys -import urllib - -from flask import Flask, request -import requests -from six.moves import html_parser -import sleekxmpp - -app = Flask(__name__) - - -@app.route('/send_message', methods=['GET']) -def send_message(): - recipient = request.args.get('recipient') - message = request.args.get('message') - - if chat_client and recipient and message: - chat_client.send_message(mto=recipient, mbody=message) - return 'message sent to {} with body: {}'.format(recipient, message) - else: - return 'message failed to send', 400 - - -class WikiBot(sleekxmpp.ClientXMPP): - """A simple SleekXMPP bot that will take messages, look up their content on - wikipedia and provide a link to the page if it exists. - """ - - def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) - - # 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) - - # The message event is triggered whenever a message - # stanza is received. Be aware that that includes - # MUC messages and error messages. - self.add_event_handler('message', self.message) - - # Register plugins. Note that while plugins may have - # interdependencies, the order you register them in doesn't matter. - self.register_plugin('xep_0030') # Service Discovery - self.register_plugin('xep_0004') # Data Forms - self.register_plugin('xep_0060') # PubSub - self.register_plugin('xep_0199') # XMPP Ping - - 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. - - Arguments: - event -- An empty dictionary. The session_start event does not - provide any additional data. - """ - self.send_presence() - self.get_roster() - - def message(self, msg): - """Process incoming message stanzas. - - Be aware that this also includes MUC messages and error messages. It is - usually a good idea to check the messages's type before processing or - sending replies. If the message is the appropriate type, then the bot - checks wikipedia to see if the message string exists as a page on the - site. If so, it sends this link back to the sender in the reply. - - Arguments: - msg -- The received message stanza. See the SleekXMPP documentation - for stanza objects and the Message stanza to see how it may be - used. - """ - if msg['type'] in ('chat', 'normal'): - msg_body = msg['body'] - encoded_body = urllib.quote_plus(msg_body) - response = requests.get( - 'https://en.wikipedia.org/w/api.php?' - 'action=query&list=search&format=json&srprop=snippet&' - 'srsearch={}'.format(encoded_body)) - doc = json.loads(response.content) - - results = doc.get('query', {}).get('search') - if not results: - msg.reply('I wasn\'t able to locate info on "{}" Sorry'.format( - msg_body)).send() - return - - snippet = results[0]['snippet'] - title = urllib.quote_plus(results[0]['title']) - - # Strip out html - snippet = html_parser.HTMLParser().unescape( - re.sub(r'<[^>]*>', '', snippet)) - msg.reply(u'{}...\n(http://en.wikipedia.org/w/?title={})'.format( - snippet, title)).send() - - -if __name__ == '__main__': - # Setup the command line arguments. - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - - # JID and password options. - parser.add_argument('-j', '--jid', help='JID to use', required=True) - parser.add_argument('-p', '--password', help='password to use') - - args = parser.parse_args() - - if args.password is None: - args.password = getpass.getpass('Password: ') - - xmpp = WikiBot(args.jid, args.password) - - chat_client = xmpp # set the global variable - - try: - # Connect to the XMPP server and start processing XMPP stanzas. - if not xmpp.connect(): - print('Unable to connect.') - sys.exit(1) - - xmpp.process(block=False) - - app.run(threaded=True, use_reloader=False, host='0.0.0.0', debug=False) - print('Done') - finally: - xmpp.disconnect()