Last active
June 21, 2020 17:54
-
-
Save Dan6erbond/1e19c924d8848d12f00cdf2f872f25b6 to your computer and use it in GitHub Desktop.
Discord bot layout to fetch new comments and post them to a desired location based on Banhammer.py's design and aPRAW.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from discord.ext import commands | |
import apraw | |
# instatiate a `Bot` instance | |
# this is using the Discord.py library | |
# source can be found here: https://github.com/Rapptz/discord.py | |
bot = commands.Bot(COMMAND_PREFIX, description=DESCRIPTION) | |
# instantiate a `Reddit` instance | |
# you can also supply a key to an entry within a praw.ini | |
# file, making your login compatible with praw as well | |
reddit = apraw.Reddit(client_id="CLIENT_ID", client_secret="CLIENT_SECRET", | |
password="PASSWORD", user_agent="USERAGENT", | |
username="USERNAME") | |
# functions to call when a new comment was made will be stored here | |
comment_functions = [] | |
# create a higher order function that adds the given function to the previous list | |
def comments(self, **kwargs): | |
# function that assigns the actual values | |
def assign(func): | |
# storing the function as a dictionary to keep track of `kwargs` | |
comment_functions.append({ | |
"func": func, | |
"kwargs": kwargs | |
}) | |
# return the original function as result | |
return func | |
return assign | |
# add this function to the list with the decorator | |
@comments | |
async def handle_comments(comment): | |
# send the received comment to a specified Discord channel | |
msg = await bot.get_channel(CHANNEL_ID).send(comment.body) | |
# this function will run in an endless loop, providing streams of comments | |
async def stream(): | |
# initialize the `Subreddit` object | |
subreddit = reddit.subreddit("aprawtest") | |
# iterate through comments on Reddit | |
# using aPRAW's stream method won't block as it uses `asyncio.sleep()` | |
async for comment in subreddit.comments.stream(): | |
# iterate through all stored comments | |
for func in comment_functions: | |
# call the desired function and feed it the comment | |
await func["func"](comment) | |
# add the stream function to the event loop | |
bot.loop.create_task(stream()) | |
# start running the bot | |
bot.run(TOKEN) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment