Skip to main content

How to create a bot that publishes the daily top post of a subreddit to a Discord channel (Docker).

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 Dockerfile in your project directory:

FROM python:3.9-slim-buster

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "bot.py" ]

This Dockerfile uses the official Python 3.9 image as a base, sets the working directory to /app, copies the requirements.txt file, installs the required packages, copies the rest of the files in the directory, and runs the bot.py script when the container starts.

 

  1. Create a docker-compose.yml file in your project directory:
version: '3'

services:
  bot:
    build: .
    environment:
      - DISCORD_TOKEN=<your-bot-token>
      - REDDIT_CLIENT_ID=<your-reddit-client-id>
      - REDDIT_CLIENT_SECRET=<your-reddit-client-secret>
      - REDDIT_USER_AGENT=<your-reddit-user-agent>
      - DISCORD_SERVER_ID=<your-discord-server-id>
      - DISCORD_CHANNEL_ID=<your-discord-channel-id>
      - SUBREDDIT=<your-subreddit-name>
    restart: always
This docker-compose.yml file defines a service named bot that builds the Docker image from the current directory, sets environment variables for the bot accounttoken, onReddit API credentials, Discord byserver goingand tochannel IDs, and subreddit name, and restarts the Discordcontainer Developerif Portal,it creatingcrashes or stops.
  1. Create a newrequirements.txt application,file addingin ayour botproject todirectory with the application,following and then copying the bot's token.

    contents:
discord.py
praw

InstallThis file specifies the required Python libraries,packages includingfor the bot to run.

 

  1. Modify your discord.bot.py, prawscript (Pythonto use environment variables for the bot token, Reddit API Wrapper), and datetime.

  2. Write a Python script that authenticates the bot using its token, connects to the appropriatecredentials, Discord server and channel,channel IDs, and retrieves the daily top post of a subreddit using the praw library.

  3. Schedule the script to run once per day using a toolname, like cron or Task Scheduler.

    this:

Here's an example script that retrieves the daily top post of the "AskReddit" subreddit and posts it to a Discord channel:

import os
import discord
import praw
import datetime

# Discord bot token
TOKEN = os.environ["your-bot-token-here"DISCORD_TOKEN"]

# Reddit API credentials
REDDIT_CLIENT_ID = os.environ["REDDIT_CLIENT_ID"]
REDDIT_CLIENT_SECRET = os.environ["REDDIT_CLIENT_SECRET"]
REDDIT_USER_AGENT = os.environ["REDDIT_USER_AGENT"]

reddit = praw.Reddit(
    client_id="your-client-id-here",REDDIT_CLIENT_ID,
    client_secret="your-client-secret-here",REDDIT_CLIENT_SECRET,
    user_agent="your-user-agent-here"REDDIT_USER_AGENT
)

# Subreddit to retrieve top post from
SUBREDDIT = os.environ["AskReddit"SUBREDDIT"]

# Discord server and channel to post to
SERVER_ID = int(os.environ["your-server-id-here"DISCORD_SERVER_ID"])
CHANNEL_ID = int(os.environ["your-channel-id-here"DISCORD_CHANNEL_ID"])

# 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
  1. Start the placeholdersDocker
  2. 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.