Skip to main content

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:

  1. 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.

  2. Install the required Python libraries, including discord.py, praw (Python Reddit API Wrapper), and datetime.

  3. 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.

  4. Schedule the script to run once per day using a tool like cron or Task 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)
Note that you'll need to replace the placeholders with your own values for the bot token, Reddit API credentials, Discord server and channel IDs, and subreddit name. Additionally, you may want to modify the message formatting to fit your desired style.