Skip to content

Instantly share code, notes, and snippets.

Last active March 23, 2023 18:22
What would you like to do?
Script to post new subreddit posts to a Discord channel via webhook
# - posts new subreddit posts to a Discord channel via webhook
# author: Dan Walker
# email:
# url:
# created: 2020-08-13
import requests
import json
import time
from discord_webhook import DiscordWebhook, DiscordEmbed
# open the cache, or start from a blank list
with open('db.json') as json_file:
db = json.load(json_file)
except FileNotFoundError:
db = []
webhook_url = ""
subreddit = 'discordapp' # can be chained with + (example: python+webdev)
req = requests.get(f'{subreddit}/new/.json', headers={
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"User-Agent": "discord-feed-bot"})
posts = req.json()['data']['children']
# for each new post found in this request
for post in posts:
if post['data']['name'] not in db:
webhook = DiscordWebhook(url=webhook_url)
permalink = f"{post['data']['permalink']}"
# create an appropriate embed object
if post['data']['thumbnail'] == 'self': # text post
embed = DiscordEmbed(title=post['data']['title'], url=permalink, description=post['data']['selftext'])
embed.set_footer(text=f"Posted by {post['data']['author']}")
elif post['data']['is_video']: # video post
embed = DiscordEmbed(title=post['data']['title'], url=permalink)
embed.set_footer(text=f"Video posted by {post['data']['author']}")
else: # image post
embed = DiscordEmbed(title=post['data']['title'], url=permalink)
embed.set_footer(text=f"Image posted by {post['data']['author']}")
# attach the embed to the webhook request and go!
time.sleep(1) # to prevent Discord webhook rate limiting
# add post name to DB so we don't display it again
# save the cache of (at least) the last 50 posts seen
with open('db.json', 'w') as outfile:
json.dump(db[-50:], outfile)
Copy link

Great script, I have forked and added a loop so you can specify in an array: 1. Subredit name 2. Discord webhook link 3. Type: Hot | New | Top | Rising. making it a little more modular and easier to add to.

Copy link

also changed to 2 second wait time as I was still getting issues.

Copy link

Will this automatically post new content or will i need to code a task?

Copy link

Will this automatically post new content or will i need to code a task?

Hi @killaxia, I'm not entirely sure what you mean? You will need to run the script on a regular interval, each time it runs it checks for new posts and if there are any, it submits them to your Discord. Ideally you'd run this as a cronjob.

Copy link

killaxia commented Oct 27, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment