Sure! Building a Discord bot in Python to scrape the list of posts from Histre's Hacker News AI tag and notify a Discord channel is a great project. Below is a step-by-step guide to achieve this, including the code you'll need.
Overview
Requirements:
- Scrape the list of posts from Histre's AI tag every 15 minutes.
- Check for new posts.
- Send a message to a specified Discord channel whenever a new post is found.
Tools and Libraries:
- Python 3.8+
- discord.py: Python library for Discord API.
- aiohttp: For making asynchronous HTTP requests.
- feedparser: To parse RSS feeds.
- asyncio: To handle asynchronous programming.
- JSON module: To store and retrieve data.
Step-by-Step Guide
1. Create a Discord Bot
First, you'll need to create a Discord bot and invite it to your server.
a. Create a New Discord Application
- Go to the Discord Developer Portal.
- Click on "New Application".
- Give your application a name and click "Create".
b. Add a Bot to Your Application
- In your application's page, navigate to the "Bot" tab.
- Click on "Add Bot".
- Confirm by clicking "Yes, do it!".
c. Get Your Bot's Token
- Under the "Bot" tab, you'll see a "Token" section.
- Click "Copy" to copy your bot's token. Keep this token secret! Never share it publicly or commit it to version control.
d. Invite Your Bot to Your Server
- Go to the "OAuth2" tab and then the "URL Generator" subtab.
- Under "Scopes", select "bot".
- Under "Bot Permissions", select the permissions your bot needs (usually "Send Messages").
- Copy the generated URL and open it in your browser.
- Select the server you want to add the bot to and authorize it.
2. Set Up Your Python Environment
Ensure you have Python 3.8 or higher installed.
a. Install Required Libraries
Open your terminal and run:
pip install discord.py==1.7.3 aiohttp feedparser
Note: discord.py version 1.7.3 is the last stable release supporting bots. The library is transitioning to a new namespace. For async functionality, ensure you're using this version.
3. Coding the Bot
Create a new Python script, e.g., discord_bot.py.
a. Import Necessary Modules
import discord
from discord.ext import commands, tasks
import aiohttp
import feedparser
import asyncio
import json
b. Set Up the Bot
# Replace with your bot's token
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
# Replace with your target Discord channel ID
CHANNEL_ID = YOUR_CHANNEL_ID_HERE # e.g., 123456789012345678
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
Note: To get your channel ID:
- Enable Developer Mode in Discord (User Settings > Advanced > Developer Mode).
- Right-click on the channel you want the bot to post in and select "Copy ID".
c. Manage Sent Posts
We'll keep track of posts we've already sent to avoid duplicates.
sent_posts = set()
def load_sent_posts():
global sent_posts
try:
with open('sent_posts.json', 'r') as f:
sent_posts = set(json.load(f))
except FileNotFoundError:
sent_posts = set()
def save_sent_posts():
with open('sent_posts.json', 'w') as f:
json.dump(list(sent_posts), f)
d. Fetch and Parse the RSS Feed
We'll use aiohttp to fetch the RSS feed and feedparser to parse it.
async def fetch_feed(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.read()
return content
e. Check for New Posts Task
@tasks.loop(minutes=15)
async def check_new_posts():
feed_url = 'https://histre.com/rss/hn/?tags=%2Bai'
try:
feed_content = await fetch_feed(feed_url)
f = feedparser.parse(feed_content)
except Exception as e:
print(f"Error fetching or parsing feed: {e}")
return
new_entries = []
for entry in f.entries:
post_id = entry.link # Using the link as a unique identifier
if post_id not in sent_posts:
new_entries.append(entry)
sent_posts.add(post_id)
# Save the sent posts
save_sent_posts()
# Send messages for new entries
if new_entries:
channel = bot.get_channel(CHANNEL_ID)
if channel is None:
print(f"Channel with ID {CHANNEL_ID} not found.")
return
for entry in new_entries:
title = entry.title
link = entry.link
message = f"**New Post:** {title}\n<{link}>"
try:
await channel.send(message)
except Exception as e:
print(f"Error sending message: {e}")
f. Start the Bot and the Background Task
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
load_sent_posts()
check_new_posts.start()
bot.run(BOT_TOKEN)
4. Complete Code
Putting it all together:
import discord
from discord.ext import commands, tasks
import aiohttp
import feedparser
import asyncio
import json
# Replace with your bot's token
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
# Replace with your target Discord channel ID
CHANNEL_ID = YOUR_CHANNEL_ID_HERE # e.g., 123456789012345678
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
sent_posts = set()
def load_sent_posts():
global sent_posts
try:
with open('sent_posts.json', 'r') as f:
sent_posts = set(json.load(f))
except FileNotFoundError:
sent_posts = set()
def save_sent_posts():
with open('sent_posts.json', 'w') as f:
json.dump(list(sent_posts), f)
async def fetch_feed(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.read()
return content
@tasks.loop(minutes=15)
async def check_new_posts():
feed_url = 'https://histre.com/rss/hn/?tags=%2Bai'
try:
feed_content = await fetch_feed(feed_url)
f = feedparser.parse(feed_content)
except Exception as e:
print(f"Error fetching or parsing feed: {e}")
return
new_entries = []
for entry in f.entries:
post_id = entry.link # Using the link as a unique identifier
if post_id not in sent_posts:
new_entries.append(entry)
sent_posts.add(post_id)
# Save the sent posts
save_sent_posts()
# Send messages for new entries
if new_entries:
channel = bot.get_channel(CHANNEL_ID)
if channel is None:
print(f"Channel with ID {CHANNEL_ID} not found.")
return
for entry in new_entries:
title = entry.title
link = entry.link
message = f"**New Post:** {title}\n<{link}>"
try:
await channel.send(message)
except Exception as e:
print(f"Error sending message: {e}")
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
load_sent_posts()
check_new_posts.start()
bot.run(BOT_TOKEN)
5. Run the Bot
Ensure that your BOT_TOKEN and CHANNEL_ID are correctly set.
Run your bot script:
python discord_bot.py
Additional Notes
- Keeping Track of Posts: The bot uses a JSON file (
sent_posts.json) to keep track of which posts have been sent to prevent duplicates, even if the bot restarts.
- Error Handling: The code includes basic error handling for network requests and message sending. You can expand this to handle specific exceptions as needed.
- Bot Permissions: Ensure that the bot has permission to send messages in the target channel.
- Rate Limits: Sending messages every 15 minutes is within Discord's rate limits. However, always be cautious and handle
discord.errors.HTTPException if you plan to send many messages in a short period.
- Asynchronous Programming: Since
discord.py uses asynchronous programming, we use asyncio, aiohttp, and async/await syntax to ensure smooth operation without blocking the event loop.
Testing and Debugging
To ensure your bot works correctly:
- Check the Console: Monitor your terminal for any error messages or print statements.
- Verify Channel Access: Make sure the
CHANNEL_ID is correct and that the bot is present in that channel.
- Test Message Sending: You can add a test command to your bot to verify it can send messages.
@bot.command()
async def test(ctx):
await ctx.send("Bot is working!")
Deploying the Bot
If you want your bot to run continuously, consider deploying it on a cloud server or service such as:
- Heroku
- AWS (EC2, Lightsail)
- DigitalOcean
- Google Cloud Platform
- Dedicated hosting services for Discord bots
Ensure you handle the storage of sent_posts.json properly, and consider using a database for persistence if deploying on a cloud platform.
Conclusion
You've now set up a Discord bot that fetches the latest AI-tagged posts from Histre's Hacker News feed and notifies a Discord channel every 15 minutes. This bot can be expanded and customized further based on your needs. Happy coding!