Skip to content

Commit

Permalink
merge: http session PR (#246)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vyvy-vi authored Apr 4, 2021
2 parents be47b77 + 0c107d4 commit 60fa490
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 85 deletions.
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ verify_ssl = true
name = "pypi"

[packages]
"discord.py" = "1.6.0"
"discord.py" = "1.7.0"
motor = "==2.3.1"
wikipedia = "==1.4.0"
aiohttp = "==3.7.4"
Expand Down
8 changes: 4 additions & 4 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 10 additions & 13 deletions bot/cogs/comic.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from random import randint
from typing import Optional

import aiohttp

from discord import Embed
from discord.ext.commands import Context
from discord.ext import commands
Expand All @@ -21,17 +19,16 @@ async def xkcd(self, ctx: Context, arg: Optional[str] = 'random'):
base_url += f'{randint(1, 2390)}/'
elif arg != 'latest':
base_url += f'{arg}/'
async with aiohttp.ClientSession() as session:
url = base_url + 'info.0.json'
async with session.get(url) as json:
json = await json.json()
embed = Embed(title=json['title'],
url=base_url,
description=json['alt'],
color=COLOR.XKCD)
embed.set_image(url=json['img'])
txt = f"xkcd comic #{json['num']} | Requested by {ctx.author.name}"
embed.set_footer(text=txt)
url = base_url + 'info.0.json'
async with self.client.HTTP_SESSION.get(url) as json:
json = await json.json()
embed = Embed(title=json['title'],
url=base_url,
description=json['alt'],
color=COLOR.XKCD)
embed.set_image(url=json['img'])
txt = f"xkcd comic #{json['num']} | Requested by {ctx.author.name}"
embed.set_footer(text=txt)
await ctx.send(embed=embed)


Expand Down
68 changes: 11 additions & 57 deletions bot/cogs/meme.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,30 @@
from discord import Embed

from discord.ext import commands, tasks
from discord.ext import commands
from discord.ext.commands import Context

import aiohttp

from .utils.colo import COLOR

# Map of channel IDs to tasks.Loop automeme loops
automeme_loops = {}

class Meme(commands.Cog):
def __init__(self, client):
self.client = client

async def automeme_routine(ctx: Context):
'''sends a meme every 10 mins'''
async with aiohttp.ClientSession() as session:
url = "https://meme-api.herokuapp.com/gimme"
async with session.get(url) as response:
@commands.command(aliases=['meme'])
async def memes(self, ctx: Context, param: str = None):
sub = '/' if param is None else '/' + str(param)
url = "https://meme-api.herokuapp.com/gimme" + sub
async with self.client.HTTP_SESSION.get(url) as response:
response = await response.json()
embed = Embed(
title=response['title'],
url=response['postLink'],
color=COLOR.JOY)
embed.set_image(url=response['url'])
embed.set_footer(
text=f"r/{response['subreddit']} | Requested by {ctx.author.name}")
txt = f"r/{response['subreddit']} | Requested by {ctx.author.name}"
embed.set_footer(text=txt)
await ctx.send(embed=embed)


class Meme(commands.Cog):
def __init__(self, client):
self.client = client

@commands.command(aliases=['meme'])
async def memes(self, ctx: Context, param: str = None):
sub = '/' if param is None else '/' + str(param)
async with aiohttp.ClientSession() as session:
url = "https://meme-api.herokuapp.com/gimme" + sub
async with session.get(url) as response:
response = await response.json()
embed = Embed(
title=response['title'],
url=response['postLink'],
color=COLOR.JOY)
embed.set_image(url=response['url'])
txt = f"r/{response['subreddit']} | Requested by {ctx.author.name}"
embed.set_footer(text=txt)
await ctx.send(embed=embed)

@commands.command()
async def automeme(self, ctx: Context):
'''Triggers the automeme taskloop for the channel context'''
channel_id = ctx.channel.id
if channel_id in automeme_loops:
await ctx.send('Automeme already running here')
else:
# using decorator instead of tasks.Loop directly to preserve
# default arguments
loop = tasks.loop(seconds=600)(automeme_routine)
automeme_loops[channel_id] = loop
loop.start(ctx)

@commands.command()
async def automeme_cancel(self, ctx: Context):
'''Cancel the Automeme task in the current channel'''
channel_id = ctx.channel.id
if channel_id not in automeme_loops:
await ctx.send('Automeme not running here')
else:
automeme_loops[channel_id].cancel()
del automeme_loops[channel_id]
await ctx.send('Automeme canceled here')


def setup(client):
client.add_cog(Meme(client))
8 changes: 3 additions & 5 deletions bot/cogs/utilities.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import wikipedia
import aiohttp

from discord import Embed, Color
from discord.ext import commands
Expand Down Expand Up @@ -48,10 +47,9 @@ async def wiki(self, ctx: Context, *, args):
async def weather(self, ctx: Context, *, loc):
'''displays weather data'''
key = "353ddfe27aa4b3537c47c975c70b58d9" # dummy key(for now)
async with aiohttp.ClientSession() as session:
url = f"http://api.openweathermap.org/data/2.5/weather?appid={key}&q={loc}, verify= False"
async with session.get(url) as res:
q = await res.json()
url = f"http://api.openweathermap.org/data/2.5/weather?appid={key}&q={loc}, verify= False"
async with self.client.HTTP_SESSION.get(url) as res:
q = await res.json()

if q["cod"] not in [404, 401]:
embed = weather_embed(loc, q, ctx.message.author.name)
Expand Down
21 changes: 16 additions & 5 deletions bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# Standard modules
# TOKEN, MONGO URI are env-vars
from utils import get_environment_variable
from aiohttp import ClientSession
# intents (new discord feature to limit bots to certain bucket events)
intents = discord.Intents.default()

Expand All @@ -24,14 +25,22 @@
try:
client.MONGO = get_environment_variable("MONGO_CONNECTION_STRING")
client.TOKEN = get_environment_variable("DISCORD_BOT_TOKEN")
except Exception as e:
logger.error('Environment Variables Not Found...')
logger.error(e)
except ValueError as err:
logger.error(f'Environment Variables Not Found...\n{err}')
sys.exit()
# discord.py has an inbuilt help command, which doesn't look good''
client.remove_command('help')
# status-change-cycle(The bot changes presence after a few mins.)

_close = client.close


async def close():
logger.info('Logging out...')
await _close()
if client.HTTP_SESSION:
logger.info('Closing aiohttp.ClientSession')
await client.HTTP_SESSION.close()
client.close = close

d_logger = logging.getLogger('discord')
d_logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -83,12 +92,14 @@ async def on_ready():
That is, when the bot logs onto discord when the script is ran.
'''
change_status.start() # Triggers status change task
logger.info("|||||||||||||||")
logger.info("Bot has Successfully logged onto Discord...")
logger.info('Successfully logged in as {0.user}...'.format(client))
logger.info('Starting aiohttp.ClientSession')
client.HTTP_SESSION = ClientSession()
# client.user gives the bots discord username tag


# discord.py has an inbuilt help command, which doesn't look good''
@tasks.loop(seconds=600)
async def change_status():
'''
Expand Down

0 comments on commit 60fa490

Please sign in to comment.