Skip to content

Commit

Permalink
Add OAuth to reddit api
Browse files Browse the repository at this point in the history
  • Loading branch information
joinemm committed Dec 13, 2023
1 parent 55e4eec commit 2f53aa8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
28 changes: 25 additions & 3 deletions modules/media_embedders.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import discord
import regex
import yarl
from aiohttp import ClientConnectorError
from aiohttp import BasicAuth, ClientConnectorError
from attr import dataclass
from discord.ext import commands
from discord.ui import View
Expand Down Expand Up @@ -235,8 +235,30 @@ async def create_message(
reddit_post_id: str,
options: Options | None = None,
):
api_url = f"https://api.reddit.com/api/info/?id=t3_{reddit_post_id}"
async with self.bot.session.get(api_url) as response:
user_agent = "Miso Bot (by Joinemm)"
token = self.bot.reddit_access_token
now = arrow.utcnow().timestamp()
if token["expiry"] < now:
async with self.bot.session.post(
"https://www.reddit.com/api/v1/access_token",
headers={"User-Agent": user_agent},
data={"grant_type": "client_credentials"},
auth=BasicAuth(
self.bot.keychain.REDDIT_CLIENT_ID,
self.bot.keychain.REDDIT_CLIENT_SECRET,
),
) as response:
data = await response.json()
self.bot.reddit_access_token = {
"expiry": now + data["expires_in"],
"token": data["access_token"],
}
api_url = f"https://oauth.reddit.com/api/info/?id=t3_{reddit_post_id}"
headers = {
"User-Agent": user_agent,
"Authorization": f"Bearer {self.bot.reddit_access_token['token']}",
}
async with self.bot.session.get(api_url, headers=headers) as response:
data = await response.json()
post = data["data"]["children"][0]["data"]

Expand Down
1 change: 1 addition & 0 deletions modules/misobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def __init__(
self.datalama = Datalama(self)
self.boot_up_time: float | None = None
self.session: aiohttp.ClientSession
self.reddit_access_token = {"expiry": 0, "token": None}
self.register_hooks()

async def get_context(self, message: discord.Message):
Expand Down

0 comments on commit 2f53aa8

Please sign in to comment.