each cog now handles its own http session

This commit is contained in:
phixxy 2024-02-13 01:54:36 -08:00
parent 10ac529323
commit 5331a5e2e7
7 changed files with 42 additions and 33 deletions

View file

@ -1,4 +1,5 @@
import random import random
import aiohttp
from discord.ext import commands from discord.ext import commands
import discord import discord
@ -7,13 +8,17 @@ class Anime(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.url = "https://api.waifu.im/search" self.url = "https://api.waifu.im/search"
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
async def get_waifu(self, tags): async def get_waifu(self, tags):
params = { params = {
'included_tags': tags, 'included_tags': tags,
'height': '>=1000' 'height': '>=1000'
} }
async with self.bot.http_session.get(self.url, params=params) as resp: async with self.http_session.get(self.url, params=params) as resp:
resp_data = await resp.json() resp_data = await resp.json()
try: try:
image = random.choice(resp_data['images']) image = random.choice(resp_data['images'])
@ -27,7 +32,7 @@ class Anime(commands.Cog):
return "Something went wrong" return "Something went wrong"
async def get_anime_from_img(self, img_url): async def get_anime_from_img(self, img_url):
async with self.bot.http_session.get(f"https://api.trace.moe/search?anilistInfo&url={img_url}") as resp: async with self.http_session.get(f"https://api.trace.moe/search?anilistInfo&url={img_url}") as resp:
resp_data = await resp.json() resp_data = await resp.json()
title = resp_data["result"][0]["anilist"]["title"] title = resp_data["result"][0]["anilist"]["title"]
video = resp_data["result"][0]["video"] video = resp_data["result"][0]["video"]

View file

@ -9,6 +9,10 @@ class Meme(commands.Cog):
self.bot = bot self.bot = bot
self.working_dir = "tmp/meme/" self.working_dir = "tmp/meme/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
def folder_setup(self): def folder_setup(self):
try: try:
@ -31,7 +35,7 @@ class Meme(commands.Cog):
url = "https://api.openai.com/v1/chat/completions" url = "https://api.openai.com/v1/chat/completions"
try: try:
async with self.bot.http_session.post(url, headers=headers, json=data) as resp: async with self.http_session.post(url, headers=headers, json=data) as resp:
response_data = await resp.json() response_data = await resp.json()
response = response_data['choices'][0]['message']['content'] response = response_data['choices'][0]['message']['content']
return response return response
@ -45,7 +49,7 @@ class Meme(commands.Cog):
) )
async def meme(self, ctx): async def meme(self, ctx):
async def generate_random_meme(topic): async def generate_random_meme(topic):
async with self.bot.http_session.get('https://api.imgflip.com/get_memes') as resp: async with self.http_session.get('https://api.imgflip.com/get_memes') as resp:
response_data = await resp.json() response_data = await resp.json()
response = response_data['data']['memes'] response = response_data['data']['memes']
memepics = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in response] memepics = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in response]
@ -81,7 +85,7 @@ class Meme(commands.Cog):
URL = 'https://api.imgflip.com/caption_image' URL = 'https://api.imgflip.com/caption_image'
try: try:
async with self.bot.http_session.post(URL, params=params) as resp: async with self.http_session.post(URL, params=params) as resp:
response = await resp.json() response = await resp.json()
image_link = response['data']['url'] image_link = response['data']['url']
except Exception as error: except Exception as error:
@ -89,7 +93,7 @@ class Meme(commands.Cog):
try: try:
#------------------------------------Saving Image Using Aiohttp---------------------------------# #------------------------------------Saving Image Using Aiohttp---------------------------------#
filename = memepics[id-1]['name'] filename = memepics[id-1]['name']
async with self.bot.http_session.get(image_link) as response: async with self.http_session.get(image_link) as response:
folder = "tmp/meme/" folder = "tmp/meme/"
filename = folder + topic + str(len(os.listdir(folder))) + ".jpg" filename = folder + topic + str(len(os.listdir(folder))) + ".jpg"

View file

@ -3,6 +3,7 @@ import io
import base64 import base64
import time import time
import html import html
import aiohttp
import asyncssh import asyncssh
from PIL import Image, PngImagePlugin from PIL import Image, PngImagePlugin
from discord.ext import commands, tasks from discord.ext import commands, tasks
@ -20,6 +21,10 @@ class PhixxyCom(commands.Cog):
self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log" self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log"
self.phixxy_loop.start() self.phixxy_loop.start()
self.blog_loop.start() self.blog_loop.start()
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
def folder_setup(self): def folder_setup(self):
try: try:
@ -94,7 +99,7 @@ class PhixxyCom(commands.Cog):
for image in image_list: for image in image_list:
filename = image.replace(" ", "").lower() + ".png" filename = image.replace(" ", "").lower() + ".png"
payload = {"prompt": image, "steps": 25} payload = {"prompt": image, "steps": 25}
response = await self.bot.http_session.post(url=f'{url}/sdapi/v1/txt2img', json=payload) response = await self.http_session.post(url=f'{url}/sdapi/v1/txt2img', json=payload)
r = await response.json() r = await response.json()
for i in r['images']: for i in r['images']:
image = Image.open(io.BytesIO(base64.b64decode(i.split(",", 1)[0]))) image = Image.open(io.BytesIO(base64.b64decode(i.split(",", 1)[0])))

View file

@ -1,3 +1,4 @@
import aiohttp
from discord.ext import commands from discord.ext import commands
import discord import discord
@ -5,9 +6,13 @@ class Pokedex(commands.Cog):
def __init__(self, bot) -> None: def __init__(self, bot) -> None:
self.bot = bot self.bot = bot
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
async def get_json(self, url): async def get_json(self, url):
async with self.bot.http_session.get(url) as resp: async with self.http_session.get(url) as resp:
json_data = await resp.json() json_data = await resp.json()
return json_data return json_data

View file

@ -1,11 +1,11 @@
#plugin file for sparkytron 3000
from discord.ext import commands
import discord
import random import random
import os import os
import json import json
import math import math
import time import time
import aiohttp
from discord.ext import commands
import discord
class PokemonGame(commands.Cog): class PokemonGame(commands.Cog):
@ -15,9 +15,13 @@ class PokemonGame(commands.Cog):
self.working_dir = "tmp/pokemon/" self.working_dir = "tmp/pokemon/"
self.data_dir = "data/pokemon/" self.data_dir = "data/pokemon/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
async def get_json(self, url): async def get_json(self, url):
async with self.bot.http_session.get(url) as resp: async with self.http_session.get(url) as resp:
json_data = await resp.json() json_data = await resp.json()
return json_data return json_data

View file

@ -1,5 +1,6 @@
import time import time
import os import os
import aiohttp
import discord import discord
from discord.ext import commands from discord.ext import commands
@ -10,6 +11,10 @@ class TextToSpeech(commands.Cog):
self.working_dir = "tmp/tts/" self.working_dir = "tmp/tts/"
self.data_dir = "data/tts/" self.data_dir = "data/tts/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session()
def create_aiohttp_session(self):
return aiohttp.ClientSession()
def folder_setup(self): def folder_setup(self):
try: try:
@ -40,7 +45,7 @@ class TextToSpeech(commands.Cog):
} }
filename = f"{time.time_ns()}.mp3" filename = f"{time.time_ns()}.mp3"
filepath = f"{self.data_dir}{filename}" filepath = f"{self.data_dir}{filename}"
response = await self.bot.http_session.post(url, json=data, headers=headers) response = await self.http_session.post(url, json=data, headers=headers)
with open(filepath, 'wb') as f: with open(filepath, 'wb') as f:
async for chunk in response.content.iter_chunked(CHUNK_SIZE): async for chunk in response.content.iter_chunked(CHUNK_SIZE):
if chunk: if chunk:
@ -63,7 +68,7 @@ class TextToSpeech(commands.Cog):
} }
filename = f"{time.time_ns()}.mp3" filename = f"{time.time_ns()}.mp3"
filepath = f"{self.data_dir}{filename}" filepath = f"{self.data_dir}{filename}"
response = await self.bot.http_session.post(url, json=data, headers=headers) response = await self.http_session.post(url, json=data, headers=headers)
with open(filepath, 'wb') as f: with open(filepath, 'wb') as f:
async for chunk in response.content.iter_chunked(CHUNK_SIZE): async for chunk in response.content.iter_chunked(CHUNK_SIZE):
if chunk: if chunk:

View file

@ -1,7 +1,6 @@
import os import os
import discord import discord
from discord.ext import commands from discord.ext import commands
import aiohttp
from dotenv import load_dotenv from dotenv import load_dotenv
import src.logger as logger import src.logger as logger
import src.utils as utils import src.utils as utils
@ -11,12 +10,6 @@ intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents) bot = commands.Bot(command_prefix='!', intents=intents)
bot.logger = logger.logger_setup() bot.logger = logger.logger_setup()
async def create_session():
return aiohttp.ClientSession()
async def close_session(http_session):
await http_session.close()
async def load_cogs(bot: commands.Bot, cog_path: str) -> None: async def load_cogs(bot: commands.Bot, cog_path: str) -> None:
for plugin_file in os.listdir(cog_path): for plugin_file in os.listdir(cog_path):
if plugin_file[-3:] == '.py': if plugin_file[-3:] == '.py':
@ -26,18 +19,6 @@ async def load_cogs(bot: commands.Bot, cog_path: str) -> None:
except: except:
bot.logger.exception(f"Failed to load plugin {plugin_file}") bot.logger.exception(f"Failed to load plugin {plugin_file}")
@bot.event
async def on_connect():
bot.http_session = await create_session()
@bot.event
async def on_resumed():
bot.http_session = await create_session()
@bot.event
async def on_disconnect():
await close_session(bot.http_session)
@bot.event @bot.event
async def on_ready(): async def on_ready():
try: try: