changed file to cog
changed print statements to logger
This commit is contained in:
parent
43b1dc5ae7
commit
d395d8cd3a
1 changed files with 93 additions and 95 deletions
|
|
@ -3,110 +3,108 @@ import os
|
||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
|
|
||||||
async def answer_question(topic, model="gpt-3.5-turbo"):
|
class Meme(commands.Cog):
|
||||||
headers = {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': f'Bearer {os.getenv("openai.api_key")}',
|
|
||||||
}
|
|
||||||
|
|
||||||
data = {
|
def __init__(self, bot):
|
||||||
"model": model,
|
self.bot = bot
|
||||||
"messages": [{"role": "user", "content": topic}]
|
|
||||||
}
|
|
||||||
|
|
||||||
url = "https://api.openai.com/v1/chat/completions"
|
async def answer_question(self, topic, model="gpt-3.5-turbo"):
|
||||||
|
headers = {
|
||||||
try:
|
'Content-Type': 'application/json',
|
||||||
http_session = aiohttp.ClientSession()
|
'Authorization': f'Bearer {os.getenv("openai.api_key")}',
|
||||||
async with http_session.post(url, headers=headers, json=data) as resp:
|
|
||||||
response_data = await resp.json()
|
|
||||||
response = response_data['choices'][0]['message']['content']
|
|
||||||
await http_session.close()
|
|
||||||
return response
|
|
||||||
except Exception as error:
|
|
||||||
return "error occurred in meme"
|
|
||||||
|
|
||||||
@commands.command(
|
|
||||||
description="Meme",
|
|
||||||
help="Generates a meme based on input. Usage: !meme (topic)",
|
|
||||||
brief="Generate a meme"
|
|
||||||
)
|
|
||||||
async def meme(ctx):
|
|
||||||
async def generate_random_meme(topic):
|
|
||||||
http_session = aiohttp.ClientSession()
|
|
||||||
async with http_session.get('https://api.imgflip.com/get_memes') as resp:
|
|
||||||
response_data = await resp.json()
|
|
||||||
response = response_data['data']['memes']
|
|
||||||
memepics = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in response]
|
|
||||||
|
|
||||||
#Pick a meme format
|
|
||||||
memenumber = random.randint(1,99)
|
|
||||||
meme_name = response[memenumber-1]['name']
|
|
||||||
panel_count = response[memenumber-1]['box_count']
|
|
||||||
print("panel_count ",panel_count)
|
|
||||||
panel_text = await answer_question("Create text for a meme. The meme is " + meme_name + ". It has " + str(panel_count) + " panels. Only create one meme. Do not use emojis or hashtags! Use the topic: " + topic + ". Use the output format (DO NOT USE EXTRA NEWLINES AND DO NOT DESCRIBE THE PICTURE IN YOUR OUTPUT): \n1: [panel 1 text]\n2: [panel 2 text]")
|
|
||||||
|
|
||||||
id = memenumber
|
|
||||||
imgflip_username = os.getenv('imgflip_username')
|
|
||||||
imgflip_password = os.getenv('imgflip_password')
|
|
||||||
params = {
|
|
||||||
'username':imgflip_username,
|
|
||||||
'password':imgflip_password,
|
|
||||||
'template_id':memepics[id-1]['id']
|
|
||||||
}
|
}
|
||||||
boxes = []
|
|
||||||
text = panel_text.split('\n')
|
|
||||||
for x in range(len(text)):
|
|
||||||
if text[x].strip() != "":
|
|
||||||
item = text[x][3:]
|
|
||||||
if len(params)-3 < panel_count:
|
|
||||||
dictionary = {"text":item, "color": "#ffffff", "outline_color": "#000000"}
|
|
||||||
boxes.append(dictionary)
|
|
||||||
|
|
||||||
for i, box in enumerate(boxes):
|
data = {
|
||||||
params[f"boxes[{i}][text]"] = box["text"]
|
"model": model,
|
||||||
params[f"boxes[{i}][color]"] = box["color"]
|
"messages": [{"role": "user", "content": topic}]
|
||||||
params[f"boxes[{i}][outline_color]"] = box["outline_color"]
|
}
|
||||||
|
|
||||||
URL = 'https://api.imgflip.com/caption_image'
|
url = "https://api.openai.com/v1/chat/completions"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
#http_session = aiohttp.ClientSession()
|
async with self.bot.http_session.post(url, headers=headers, json=data) as resp:
|
||||||
async with http_session.post(URL, params=params) as resp:
|
response_data = await resp.json()
|
||||||
response = await resp.json()
|
response = response_data['choices'][0]['message']['content']
|
||||||
print(f"Generated Meme = {response['success']}\nImage Link = {response['data']['url']}\nPage Link = {response['data']['page_url']}")
|
return response
|
||||||
image_link = response['data']['url']
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
print("Error occurred in meme")
|
return "error occurred in meme"
|
||||||
|
|
||||||
|
@commands.command(
|
||||||
|
description="Meme",
|
||||||
|
help="Generates a meme based on input. Usage: !meme (topic)",
|
||||||
|
brief="Generate a meme"
|
||||||
|
)
|
||||||
|
async def meme(self, ctx):
|
||||||
|
async def generate_random_meme(topic):
|
||||||
|
async with self.bot.http_session.get('https://api.imgflip.com/get_memes') as resp:
|
||||||
|
response_data = await resp.json()
|
||||||
|
response = response_data['data']['memes']
|
||||||
|
memepics = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in response]
|
||||||
|
|
||||||
|
#Pick a meme format
|
||||||
|
memenumber = random.randint(1,99)
|
||||||
|
meme_name = response[memenumber-1]['name']
|
||||||
|
panel_count = response[memenumber-1]['box_count']
|
||||||
|
panel_text = await answer_question("Create text for a meme. The meme is " + meme_name + ". It has " + str(panel_count) + " panels. Only create one meme. Do not use emojis or hashtags! Use the topic: " + topic + ". Use the output format (DO NOT USE EXTRA NEWLINES AND DO NOT DESCRIBE THE PICTURE IN YOUR OUTPUT): \n1: [panel 1 text]\n2: [panel 2 text]")
|
||||||
|
|
||||||
|
id = memenumber
|
||||||
|
imgflip_username = os.getenv('imgflip_username')
|
||||||
|
imgflip_password = os.getenv('imgflip_password')
|
||||||
|
params = {
|
||||||
|
'username':imgflip_username,
|
||||||
|
'password':imgflip_password,
|
||||||
|
'template_id':memepics[id-1]['id']
|
||||||
|
}
|
||||||
|
boxes = []
|
||||||
|
text = panel_text.split('\n')
|
||||||
|
for x in range(len(text)):
|
||||||
|
if text[x].strip() != "":
|
||||||
|
item = text[x][3:]
|
||||||
|
if len(params)-3 < panel_count:
|
||||||
|
dictionary = {"text":item, "color": "#ffffff", "outline_color": "#000000"}
|
||||||
|
boxes.append(dictionary)
|
||||||
|
|
||||||
|
for i, box in enumerate(boxes):
|
||||||
|
params[f"boxes[{i}][text]"] = box["text"]
|
||||||
|
params[f"boxes[{i}][color]"] = box["color"]
|
||||||
|
params[f"boxes[{i}][outline_color]"] = box["outline_color"]
|
||||||
|
|
||||||
|
URL = 'https://api.imgflip.com/caption_image'
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with self.bot.http_session.post(URL, params=params) as resp:
|
||||||
|
response = await resp.json()
|
||||||
|
image_link = response['data']['url']
|
||||||
|
except Exception as error:
|
||||||
|
self.bot.logger.exception("Error occurred in meme")
|
||||||
|
try:
|
||||||
|
#------------------------------------Saving Image Using Aiohttp---------------------------------#
|
||||||
|
filename = memepics[id-1]['name']
|
||||||
|
async with self.bot.http_session.get(image_link) as response:
|
||||||
|
folder = "tmp/meme/"
|
||||||
|
filename = folder + topic + str(len(os.listdir(folder))) + ".jpg"
|
||||||
|
|
||||||
|
with open(filename, "wb") as file:
|
||||||
|
while True:
|
||||||
|
chunk = await response.content.read(1024) # Read the response in chunks
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
file.write(chunk)
|
||||||
|
except:
|
||||||
|
self.bot.logger.exception("Something's Wrong with the aiohttp in meme So try again")
|
||||||
|
return image_link, filename
|
||||||
|
|
||||||
try:
|
try:
|
||||||
#------------------------------------Saving Image Using Aiohttp---------------------------------#
|
topic = ctx.message.content.split(" ", maxsplit=1)[1]
|
||||||
filename = memepics[id-1]['name']
|
await ctx.send(f'Generating {topic} meme')
|
||||||
async with http_session.get(image_link) as response:
|
link, filepath = await generate_random_meme(topic)
|
||||||
folder = "tmp/meme/"
|
await ctx.send(link)
|
||||||
filename = folder + topic + str(len(os.listdir(folder))) + ".jpg"
|
|
||||||
|
|
||||||
with open(filename, "wb") as file:
|
|
||||||
while True:
|
|
||||||
chunk = await response.content.read(1024) # Read the response in chunks
|
|
||||||
if not chunk:
|
|
||||||
break
|
|
||||||
file.write(chunk)
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
print("Something's Wrong with the aiohttp in meme So try again")
|
self.bot.logger.exception("Error occurred in meme")
|
||||||
await http_session.close()
|
await ctx.send('Something went wrong try again. Usage: !meme (topic)')
|
||||||
return image_link, filename
|
|
||||||
|
|
||||||
try:
|
|
||||||
topic = ctx.message.content.split(" ", maxsplit=1)[1]
|
|
||||||
await ctx.send(f'Generating {topic} meme')
|
|
||||||
link, filepath = await generate_random_meme(topic)
|
|
||||||
await ctx.send(link)
|
|
||||||
except Exception as error:
|
|
||||||
print("Error occurred in meme")
|
|
||||||
await ctx.send('Something went wrong try again. Usage: !meme (topic)')
|
|
||||||
|
|
||||||
async def setup(bot):
|
async def setup(bot):
|
||||||
bot.add_command(meme)
|
await bot.add_cog(Meme(bot))
|
||||||
Loading…
Add table
Add a link
Reference in a new issue