How to create a bot that publishes the daily top post of a subreddit to a Discord channel.
To create a bot that publishes the daily top post of a subreddit to a Discord channel, you can follow these general steps:
-
Create a new bot account on Discord by going to the Discord Developer Portal, creating a new application, adding a bot to the application, and then copying the bot's token.
-
Install the required Python libraries, including
discord.py
,praw
(Python Reddit API Wrapper), anddatetime
. -
Write a Python script that authenticates the bot using its token, connects to the appropriate Discord server and channel, and retrieves the daily top post of a subreddit using the
praw
library. -
Schedule the script to run once per day using a tool like
cron
orTask Scheduler
.
Here's an example script that retrieves the daily top post of the "AskReddit" subreddit and posts it to a Discord channel:
import discord
import praw
import datetime
# Discord bot token
TOKEN = "your-bot-token-here"
# Reddit API credentials
reddit = praw.Reddit(
client_id="your-client-id-here",
client_secret="your-client-secret-here",
user_agent="your-user-agent-here"
)
# Subreddit to retrieve top post from
SUBREDDIT = "AskReddit"
# Discord server and channel to post to
SERVER_ID = "your-server-id-here"
CHANNEL_ID = "your-channel-id-here"
# Get today's date in the format "MM/DD/YYYY"
today = datetime.datetime.now().strftime("%m/%d/%Y")
# Get the top post of the day from the subreddit
top_post = reddit.subreddit(SUBREDDIT).top(time_filter="day", limit=1).__next__()
# Build the message to post to Discord
message = f"**Top post on r/{SUBREDDIT} for {today}:**\n\n{top_post.title}\n\n{top_post.url}"
# Authenticate the Discord bot using its token
client = discord.Client()
@client.event
async def on_ready():
# Get the Discord server and channel to post to
server = client.get_guild(SERVER_ID)
channel = server.get_channel(CHANNEL_ID)
# Post the message to the Discord channel
await channel.send(message)
# Run the Discord bot
client.run(TOKEN)
No Comments