Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quote import temp #114

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions byugui/inspire_quote_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import traceback
import json
import random
import requests
from requests.api import get
try:
from PySide import QtGui as QtWidgets
from PySide import QtGui as QtGui
Expand All @@ -25,6 +27,7 @@ def __init__(self, parent):
quotes_path = os.path.join(os.environ['BYU_TOOLS_DIR'], 'byugui', 'assets', 'inspire-quotes.json')
quote_json = file(quotes_path)
self.quoteData = json.loads(quote_json.read())['quotes']
self.addQuotesFromSlack()
self.initUI()

def initUI(self):
Expand Down Expand Up @@ -60,21 +63,68 @@ def getQuote(self):
index = random.randrange(0,len(self.quoteData))
return self.quoteData[index]

def populateQuote(self):
quoteInfo = self.getQuote()

self.quote.setText(quoteInfo["quote"] + "\n\t-" + quoteInfo["author"])# + "\n\n\n Submitted by: " + quoteInfo["contributor"])
image_path = os.path.join(os.environ['BYU_TOOLS_DIR'], 'byugui', 'assets', 'images', quoteInfo['image'])
pixmap = QtGui.QPixmap(image_path)
# Scales image to proper size. Minimizes code duplication.
def scaleImage(self, pixmap):
scaled = pixmap.scaledToWidth(self.size().width()/2)
print scaled
print "\n" + str(self.size()) + " " + str(self.size().width())
self.img.setPixmap(scaled)

def populateQuote(self):
quoteInfo = self.getQuote()
self.quote.setText(quoteInfo["quote"] + "\n\t-" + quoteInfo["author"])# + "\n\n\n Submitted by: " + quoteInfo["contributor"])
# If we obtained the quote from Slack, this grabs the avatar of the user who posted the quote.
if "slack" in quoteInfo['image']:
path = quoteInfo['image']
res = get(path)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(res.content)
self.scaleImage(pixmap)
else:
image_path = os.path.join(os.environ['BYU_TOOLS_DIR'], 'byugui', 'assets', 'images', quoteInfo['image'])
pixmap = QtGui.QPixmap(image_path)
self.scaleImage(pixmap)

def closeEvent(self, event):
self.finished.emit()
event.accept()

# Gets image to use for each Slack quote.
def getImageForSlackQuote(self, userID):
# We will send another GET request to the slack API.
URL = "https://slack.com/api/users.profile.get?token=xoxp-262198519712-364750013863-363181322081-b04dd4517e6975431c598decc65c85fd&user=" + userID
result = get(URL)
jsonData = result.json()
imageID = jsonData['profile']['image_1024']
return imageID

# Pulls quotes from the all_the_quotes Slack channel.
def addQuotesFromSlack(self):
# Authentication via Dandbot's user account. Dandbot isn't actually a bot, but rather a user registered to the Slack workspace.
URL = "https://slack.com/api/channels.history?token=xoxp-262198519712-364750013863-363181322081-b04dd4517e6975431c598decc65c85fd&channel=C98MS1YH1"
# Send a GET request to the Slack service, and convert it into a JSON object.
result = get(URL)
myJson = result.json()
# Iterate through all the received messages from Slack.
for message in myJson['messages']:
# Ensures that we only pull quotes from the chat, while omitting "user_x joined #all_the_quotes" messages.
if "-" in message['text']:
userID = message['user']
print "userID: ", userID
img = self.getImageForSlackQuote(userID)
# rsplit accounts for quotes that might have hyphens in them, such as "flaming hell-octo-copter".
data = message['text'].rsplit("-", 1)
author = data[1]
quote = data[0]
# Format JSON object for appending to the JSON array.
toAppendToJson = ("{\"author\": \"" + author + "\","
+ "\"quote\": " + quote + ","
+ "\"image\": \"" + img + "\","
+ "\"contributor\": \"Alex Neville and Dandbot\"}")
# Appends data to the JSON object at runtime, so we don't have to create a database of already uploaded quotes.
jsonDict = json.loads(toAppendToJson)
self.quoteData.append(jsonDict)

if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = QuoteWindow(app)
Expand Down
77 changes: 77 additions & 0 deletions byugui/requests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-

# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /

"""
requests HTTP library
~~~~~~~~~~~~~~~~~~~~~

Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:

>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True

... or POST:

>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}

The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>.

:copyright: (c) 2014 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.

"""

__title__ = 'requests'
__version__ = '2.4.3'
__build__ = 0x020403
__author__ = 'Kenneth Reitz'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2014 Kenneth Reitz'

# Attempt to enable urllib3's SNI support, if possible
try:
from .packages.urllib3.contrib import pyopenssl
pyopenssl.inject_into_urllib3()
except ImportError:
pass

from . import utils
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
RequestException, Timeout, URLRequired,
TooManyRedirects, HTTPError, ConnectionError
)

# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass

logging.getLogger(__name__).addHandler(NullHandler())
Loading