@client.event
async def on_ready():
print(f'Bot logged in as {client.user}')
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Failed to sync commands: {e}")
async def scrape_game_info(game_url):
"""Scrape game information from Roblox page"""
async with aiohttp.ClientSession() as session:
async with session.get(game_url) as response:
if response.status == 200:
soup = BeautifulSoup(await response.text(), 'html.parser')
code
# Get game ID from URL
game_id = re.search(r'/games/(\d+)/', game_url)
game_id = game_id.group(1) if game_id else None
# Get player count using Roblox API
players = "0"
if game_id:
async with session.get(f'https://games.roblox.com/v1/games/{game_id}/playing') as player_response:
if player_response.status == 200:
player_data = await player_response.json()
players = str(player_data.get('data', [0])[0])
# Get visit count from metadata
visits = 0
visit_meta = soup.find('meta', {'name': 'visit-count'})
if visit_meta:
visits = int(visit_meta.get('content', '0'))
# Get discord link if present
discord_link = None
discord_links = re.findall(r'https?://(?:www\.)?discord\.gg/[^\s]+', str(soup))
if discord_links:
discord_link = discord_links[0]
# Only return if visits are between 300k and 100M and has discord link
if discord_link and 300000 <= visits <= 100000000:
return {
"Game Link": game_url,
"Players": players,
"Visits": str(visits),
"Discord Link": discord_link
}
return None
async with aiohttp.ClientSession() as session:
for start in range(0, 1000, 100): # Check first 1000 games
async with session.get(base_url + str(start)) as response:
if response.status == 200:
data = await response.json()
for game in data.get('Collection', []):
game_url = f"https://www.roblox.com/games/{game.get('PlaceID', '')}/"
game_info = await scrape_game_info(game_url)
if game_info:
games.append(game_info)
if len(games) >= 5: # Limit to 5 games to avoid rate limiting
return games
return games
@client.tree.command(name="findgames", description="Find popular Roblox games with Discord servers")
async def findgames(interaction: discord.Interaction):
await interaction.response.defer()
code
games = await find_popular_games()
if games:
for game in games:
embed = discord.Embed(title="Game Information", color=0x00ff00)
embed.add_field(name="Game Link", value=game["Game Link"], inline=False)
embed.add_field(name="Players", value=f"{game['Players']}/40", inline=True)
embed.add_field(name="Visits", value=game["Visits"], inline=True)
embed.add_field(name="Discord Link", value=game["Discord Link"], inline=False)
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("No games found matching the criteria.")
Ensure you delete or remove the code snippet containing your token from any public platforms (e.g., GitHub, forums).
Why This Is Critical:
Your bot token is essentially the password to your Discord bot. If someone else has access to it, they can control your bot, potentially leading to misuse, spam, or other malicious activities under your bot's identity.
Fixing the Code
Assuming you've regenerated your token, here's the revised code with additional improvements and ensuring best practices:
Use Environment Variables for the Token:
Never hardcode your token in the script. Instead, use environment variables or a separate configuration file that's excluded from version control.
Enhanced Error Handling:
Improved error messages and handling for better debugging.
Optimizations and Best Practices:
Minor code improvements for efficiency and readability.
Revised Code:
python
import discord
from discord.ext import commands
import re
import aiohttp
from bs4 import BeautifulSoup
import asyncio
import platform
import os
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Set up intents
intents = discord.Intents.default()
intents.message_content = True
# Create bot instance with slash commands
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print(f'Bot logged in as {client.user}')
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Failed to sync commands: {e}")
async def scrape_game_info(game_url):
"""Scrape game information from Roblox page"""
async with aiohttp.ClientSession() as session:
try:
async with session.get(game_url) as response:
if response.status != 200:
print(f"Failed to fetch {game_url}: Status {response.status}")
return None
soup = BeautifulSoup(await response.text(), 'html.parser')
# Get game ID from URL
game_id_match = re.search(r'/games/(\d+)/', game_url)
game_id = game_id_match.group(1) if game_id_match else None
# Get player count using Roblox API
players = "0"
if game_id:
api_url = f'https://games.roblox.com/v1/games/{game_id}/playing'
async with session.get(api_url) as player_response:
if player_response.status == 200:
player_data = await player_response.json()
players = str(player_data.get('data', [0])[0])
else:
print(f"Failed to fetch player count: Status {player_response.status}")
# Get visit count from metadata
visits = 0
visit_meta = soup.find('meta', {'name': 'visit-count'})
if visit_meta:
try:
visits = int(visit_meta.get('content', '0'))
except ValueError:
print(f"Invalid visit count format: {visit_meta.get('content', '0')}")
# Get Discord link if present
discord_link = None
discord_links = re.findall(r'https?://(?:www\.)?discord\.gg/[^\s]+', str(soup))
if discord_links:
discord_link = discord_links[0]
# Only return if visits are between 300k and 100M and has Discord link
if discord_link and 300000 <= visits <= 100000000:
return {
"Game Link": game_url,
"Players": players,
"Visits": str(visits),
"Discord Link": discord_link
}
except Exception as e:
print(f"Error scraping {game_url}: {e}")
return None
async def find_popular_games():
"""Find popular Roblox games with Discord servers"""
base_url = "https://www.roblox.com/games/list-json?sortFilter=3&limit=100&startRows=" # Popular sorting
games = []
async with aiohttp.ClientSession() as session:
for start in range(0, 1000, 100): # Check first 1000 games
try:
url = base_url + str(start)
async with session.get(url) as response:
if response.status != 200:
print(f"Failed to fetch games list at startRows={start}: Status {response.status}")
continue
data = await response.json()
for game in data.get('Collection', []):
place_id = game.get('PlaceID')
if not place_id:
continue
game_url = f"https://www.roblox.com/games/{place_id}/"
game_info = await scrape_game_info(game_url)
if game_info:
games.append(game_info)
if len(games) >= 5: # Limit to 5 games to avoid rate limiting
return games
except Exception as e:
print(f"Error fetching games at startRows={start}: {e}")
return games
@client.tree.command(name="findgames", description="Find popular Roblox games with Discord servers")
async def findgames(interaction: discord.Interaction):
await interaction.response.defer()
games = await find_popular_games()
if games:
for game in games:
embed = discord.Embed(title="Game Information", color=0x00ff00)
embed.add_field(name="Game Link", value=game["Game Link"], inline=False)
embed.add_field(name="Players", value=f"{game['Players']}/40", inline=True)
embed.add_field(name="Visits", value=game["Visits"], inline=True)
embed.add_field(name="Discord Link", value=game["Discord Link"], inline=False)
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("No games found matching the criteria.")
@client.tree.command(name="roblox", description="Share Roblox game info")
async def roblox_slash(interaction: discord.Interaction, game_link: str):
await interaction.response.defer()
# Validate the game link
if not re.match(r'^https?://(www\.)?roblox\.com/games/\d+/', game_link):
await interaction.followup.send("Please provide a valid Roblox game link.")
return
game_info = await scrape_game_info(game_link)
if game_info:
embed = discord.Embed(title="Game Information", color=0x00ff00)
embed.add_field(name="Game Link", value=game_info["Game Link"], inline=False)
embed.add_field(name="Players", value=f"{game_info['Players']}/40", inline=True)
embed.add_field(name="Visits", value=game_info["Visits"], inline=True)
embed.add_field(name="Discord Link", value=game_info["Discord Link"], inline=False)
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("No game information found or the game doesn't meet the criteria.")
@client.event
async def on_message(message):
if message.author == client.user:
return
if "roblox.com/games/" in message.content:
match = re.search(r'https?://(?:www\.)?roblox\.com/games/\d+/', message.content)
if match:
game_link = match.group(0)
game_info = await scrape_game_info(game_link)
if game_info:
embed = discord.Embed(title="Game Information", color=0x00ff00)
embed.add_field(name="Game Link", value=game_info["Game Link"], inline=False)
embed.add_field(name="Players", value=f"{game_info['Players']}/40", inline=True)
embed.add_field(name="Visits", value=game_info["Visits"], inline=True)
embed.add_field(name="Discord Link", value=game_info["Discord Link"], inline=False)
await message.channel.send(embed=embed)
await client.process_commands(message)
# It's recommended to load the token from an environment variable for security
# Example: export DISCORD_BOT_TOKEN='your-token-here'
TOKEN = os.getenv('DISCORD_BOT_TOKEN')
if not TOKEN:
print("Error: DISCORD_BOT_TOKEN environment variable not set.")
exit(1)
client.run(TOKEN)
Changes and Improvements:
Token Handling:
Removed the hardcoded token.
Implemented loading the token from an environment variable (DISCORD_BOT_TOKEN). This is a more secure practice.
Error Handling:
Added try-except blocks around network requests to handle potential exceptions gracefully.
Added print statements for debugging failed requests or unexpected data formats.
Input Validation:
In the /roblox command, added validation to ensure the provided game link matches the expected format.
Code Readability:
Improved variable naming for clarity (e.g., game_id_match instead of just game_id to indicate it's a regex match object).
Added comments and docstrings for better understanding.
Security and Rate Limiting:
Limited the number of games fetched to 5 in the find_popular_games function to prevent potential rate limiting issues.
Setting Up Environment Variables:
To set the DISCORD_BOT_TOKEN environment variable:
On Windows:
Open Command Prompt.
Run:
cmd
set DISCORD_BOT_TOKEN=your-new-token-here
Run your Python script in the same Command Prompt session.
On macOS/Linux:
Open Terminal.
Run:
bash
export DISCORD_BOT_TOKEN=your-new-token-here
Run your Python script in the same Terminal session.
Alternatively, you can create a .env file and use the python-dotenv package to load environment variables. Ensure the .env file is added to .gitignore if using version control.
Additional Recommendations
Use discord.Bot for Slash Commands:
If your bot primarily uses slash commands, consider using discord.Bot instead of commands.Bot. It provides better integration for interactions.
Asynchronous Efficiency:
Consider implementing asynchronous concurrency (e.g., asyncio.gather) when scraping multiple game URLs to improve performance.
Logging:
Instead of using print statements, utilize Python's logging module for more flexible and configurable logging.
Rate Limiting and API Respect:
Ensure your scraping respects Roblox's robots.txt and consider implementing rate limiting to avoid overwhelming their servers.
Exception Notifications:
Implement mechanisms to notify you (e.g., via logs or Discord messages) when critical errors occur.
Dependencies Management:
Use a requirements.txt file to manage dependencies, ensuring easy setup and maintenance.
Example requirements.txt:
code
discord.py==2.0.0
aiohttp
beautifulsoup4
Install dependencies using:
bash
pip install -r requirements.txt
By following these steps, you'll enhance the security, reliability, and maintainability of your Discord bot. Always prioritize keeping sensitive information like tokens secure and adhere to best coding practices to ensure smooth operation.