Creating core utils for boiler plate code

This commit is contained in:
Luke Robles 2018-02-04 22:14:11 +00:00
parent c80dea32ea
commit cfa3880a09
4 changed files with 22 additions and 10 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
.DS_Store
*.pyc

View File

@ -1,5 +1,6 @@
import requests
import core_utils
import get_from_reddit
def change_avatar():
@ -9,10 +10,8 @@ def change_avatar():
extension = image.split('.')[-1]
local_smug = "/tmp/smug.{}".format(extension)
# save an image locally
if extension.lower() in ['png', 'jpg']:
with open(local_smug, 'wb') as f:
f.write(requests.get(image).content)
return open(local_smug, 'rb').read()
# save an image locally
return open(core_utils.download_image(image, local_smug), 'rb').read()
else:
image = None

15
app/core_utils.py Normal file
View File

@ -0,0 +1,15 @@
import requests
def download_image(url, path=None):
request = requests.get(url)
suffix_list = ['jpeg', 'jpg', 'png', 'tif', 'svg',]
extension = request.headers['content-type'].split('/')[1]
if not path:
path = "/tmp/image.{}".format(extension)
if extension in suffix_list:
open(path, 'wb').write(requests.get(url).content)
return path
return 'Invalid image format'

View File

@ -9,6 +9,7 @@ import os
import requests
import avatar
import core_utils
import decide
import define_word
import discord
@ -132,10 +133,6 @@ async def on_message(message):
)
return
try:
# Download the emoji with requests
with open(emoji_staging, 'wb') as f:
f.write(requests.get(url).content)
# Attempt to upload the emoji
await client.send_message(
message.channel,
@ -143,7 +140,7 @@ async def on_message(message):
await client.create_custom_emoji(
server=message.server,
name=emoji_name,
image=open(emoji_staging, "rb").read()
image=open(core_utils.download_image(url, emoji_staging), "rb").read()
)
)
)