Skip to content

Instantly share code, notes, and snippets.

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment