Skip to content

Instantly share code, notes, and snippets.

@redthista
Forked from danwalkeruk/reddit-feed.py
Last active January 13, 2023 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redthista/c1a78ff0942c7cfc669c8e8c9ae952e2 to your computer and use it in GitHub Desktop.
Save redthista/c1a78ff0942c7cfc669c8e8c9ae952e2 to your computer and use it in GitHub Desktop.
Script to post new subreddit posts to a Discord channel via webhook
# Loops through a 2d array like: (1. Subredit name 2. Discord webhook link 3. Type: Hot | New | Top | Rising) and performs the actions to post the posts to the webhooked discord server. also changed the 1second wait to 2 seconds as i was still seeing the web request error.
import requests
import json
import time
from discord_webhook import DiscordWebhook, DiscordEmbed
i = 0
def right(value, count):
# To get right part of string, use negative first index in slice.
return value[-count:]
#array columns 1. Subredit name 2. Discord webhook link 3. Type: Hot | New | Top | Rising
myarray = [
["discordapp","<discord webhook link here>","hot"]
]
#posts new posts for each subreddit to discord
for item in range(0,len(myarray)):
#set up variables
webhook_url = str(myarray[i][1])
subreddit = str(myarray[i][0]) # can be chained with + (example: python+webdev)
rtype = str(myarray[i][2])
dbname = str(subreddit + right(webhook_url,4) + ".json")
# open the cache, or start from a blank list
try:
with open(dbname) as json_file:
db = json.load(json_file)
except FileNotFoundError:
db = []
req = requests.get(f'https://www.reddit.com/r/{subreddit}/{rtype}/.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"https://www.reddit.com{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_image(url=post['data']['thumbnail'])
embed.set_footer(text=f"Video posted by {post['data']['author']}")
else: # image post
embed = DiscordEmbed(title=post['data']['title'], url=permalink)
embed.set_image(url=post['data']['url'])
embed.set_footer(text=f"Image posted by {post['data']['author']}")
# attach the embed to the webhook request and go!
webhook.add_embed(embed)
webhook.execute()
time.sleep(2) # to prevent Discord webhook rate limiting
# add post name to DB so we don't display it again
db.append(post['data']['name'])
# save the cache of (at least) the last 50 posts seen
with open(dbname, 'w') as outfile:
json.dump(db[-50:], outfile)
i= i + 1
@gregs484
Copy link

can you please tell me how i can implement this? which needs to be added in this code? no i need to create a cache file/ folder?

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