It looks like there are a few issues in your code that need to be addressed to make it work correctly. Additionally, I noticed that you included your bot token directly in your code. For security reasons, you should never share your bot token publicly. Please reset your bot token immediately through the Discord Developer Portal to ensure the security of your bot.
Now, let's fix your code. Here are the main issues we'll address:
-
Security Concern: Remove the bot token from the code and use an environment variable or a separate configuration file instead.
-
Outdated Roblox API Endpoints: The endpoints you're using to fetch game data are outdated or incorrect. We'll update them to use the current Roblox APIs.
-
Parsing HTML Content: Relying on HTML parsing with BeautifulSoup is not reliable due to frequent changes in the website structure. We'll use Roblox's official APIs to fetch game data instead.
-
Error Handling and Code Organization: We'll add proper error handling and clean up the code for better readability and maintainability.
Below is the corrected and updated code:
import discord
from discord.ext import commands
import re
import aiohttp
import asyncio
import platform
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 API"""
async with aiohttp.ClientSession() as session:
# Get place ID from URL
place_id_match = re.search(r'/games/(\d+)', game_url)
place_id = place_id_match.group(1) if place_id_match else None
if not place_id:
return None
# Get game details from the API
async with session.get(f'https://games.roblox.com/v1/games?placeIds={place_id}') as response:
if response.status == 200:
data = await response.json()
if 'data' in data and len(data['data']) > 0:
game_data = data['data'][0]
# Extract required information
game_link = game_url
players = str(game_data.get('playing', 0))
visits = game_data.get('visits', 0)
max_players = game_data.get('maxPlayers', 0)
universe_id = game_data.get('universeId', None)
# Get social links (e.g., Discord)
discord_link = None
if universe_id:
async with session.get(f'https://games.roblox.com/v1/games/{universe_id}/social-links/list') as social_response:
if social_response.status == 200:
social_data = await social_response.json()
for link in social_data.get('data', []):
if link.get('type') == 'Discord':
discord_link = link.get('url')
break
# Only return if visits are between 300k and 100M and has discord link
if discord_link and 300000 <= visits <= 100000000:
return {
"Game Link": game_link,
"Players": players,
"Max Players": str(max_players),
"Visits": str(visits),
"Discord Link": discord_link
}
return None
async def find_popular_games():
"""Find popular Roblox games with Discord servers"""
games = []
async with aiohttp.ClientSession() as session:
# Get popular games from the endpoint
async with session.get('https://games.roblox.com/v1/games/list?sortToken=863') as response:
if response.status == 200:
data = await response.json()
for game in data.get('Games', []):
game_id = game.get('PlaceId')
game_url = f"https://www.roblox.com/games/{game_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
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']}/{game['Max Players']}", 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()
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']}/{game_info['Max Players']}", 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 game doesn't meet 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']}/{game_info['Max Players']}", 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)
# Run the bot with your token
# Make sure to replace 'YOUR_BOT_TOKEN' with your actual bot token, but do not share it publicly!
client.run('YOUR_BOT_TOKEN')
Explanation of Changes:
-
Removed Direct Bot Token: The bot token has been replaced with 'YOUR_BOT_TOKEN'. Remember to keep your bot token secret and never share it publicly.
-
Updated scrape_game_info Function:
- Fetching Game Details via Roblox API: Instead of scraping the HTML content of the game page (which is unreliable), we're now using the Roblox API to fetch game details.
- Endpoints Used:
https://games.roblox.com/v1/games?placeIds={place_id}: Fetches game details using the place ID.
https://games.roblox.com/v1/games/{universe_id}/social-links/list: Fetches social links for the game, where we specifically look for a Discord link.
- Data Extraction: Extracted
players, visits, maxPlayers, and discord_link from the API responses.
- Criteria Check: The function only returns game information if the game has a Discord link and the number of visits is between 300,000 and 100,000,000.
-
Updated find_popular_games Function:
- Fetching Popular Games: Updated the endpoint to fetch popular games. The endpoint
https://games.roblox.com/v1/games/list?sortToken=863 is an example; you may need to adjust this based on the correct sort token or method to fetch popular games.
- Limitations: The function still attempts to limit the number of games fetched to prevent rate limiting.
-
Error Handling and Robustness:
- Checked for Non-existent Game IDs: Added checks to ensure that the place ID and universe ID are valid before making API calls.
- Response Status Checks: Added checks to ensure that API responses are successful before processing data.
- Updated Regex Patterns: Improved the regex patterns to correctly extract place IDs from URLs.
-
Removed Unnecessary Imports:
- Removed
BeautifulSoup and bs4 Imports: Since we're no longer parsing HTML content, these imports are no longer necessary.
-
Adjusted Embed Fields:
- Added Max Players: Displayed the maximum number of players in the game alongside the current number of players.
Important Security Reminder:
-
Reset Your Bot Token: Since your bot token was exposed, you should reset it immediately. To do this:
- Go to the Discord Developer Portal.
- Select your application.
- Navigate to the "Bot" tab.
- Click on "Regenerate" to get a new token.
-
Securely Store Your Bot Token:
-
Use environment variables or a configuration file (like .env) that is not tracked by version control (e.g., added to .gitignore if using Git).
-
Example using environment variables:
import os
token = os.getenv('DISCORD_TOKEN')
client.run(token)
Then, set the environment variable DISCORD_TOKEN on your system or hosting platform.
Additional Notes:
-
Discord Intents: Ensure that the message_content intent is enabled in your Discord bot settings on the Developer Portal, as well as in your code.
-
Handling API Changes: Roblox's APIs may change over time. If you encounter issues fetching data, check the latest API documentation or consider implementing error logging to track down problems.
-
Rate Limiting: Be cautious with the number of API requests you make in a short period. Hitting rate limits can cause your bot to malfunction or be temporarily banned from making requests.
-
Testing: Before deploying your bot, test it thoroughly in a private server to ensure all commands and features work as expected.
I hope this helps you get your bot up and running!