Certainly! I'll help you modify your code to use Roblox's public APIs instead of the ROBLOSECURITY_COOKIE, which requires authentication and poses security risks if exposed. However, please note that monitoring a user's real-time game presence without authentication is limited due to Roblox API restrictions. We can still create a bot that checks when a user comes online and notifies the Discord channel without requiring authentication.
Here's how you can adjust your code:
-
Remove the dependency on ro_py and any code that requires authentication.
-
Update the fetch_username function to use Roblox's public Users API.
-
Modify the monitoring functionality to check when a user comes online instead of joining a specific game.
Below is the modified code:
import discord
from discord.ext import commands, tasks
from discord import app_commands
import asyncio
import json
from pathlib import Path
import aiohttp # For making HTTP requests
# ============================
# Configuration - Fill in Your Details Below
# ============================
TOKEN = "YOUR_DISCORD_BOT_TOKEN" # Replace with your bot's token as a string
NOTIFICATION_CHANNEL_ID = 123456789012345678 # Replace with your Discord channel ID as an integer
CHECK_INTERVAL = 15 # Adjust as needed (minimum is around 15 seconds due to rate limits)
# ============================
# End of Configuration
# ============================
# Data persistence
BASE_DIR = Path(__file__).parent
DATA_FILE = BASE_DIR / 'monitoring.json'
if DATA_FILE.exists():
with open(DATA_FILE, 'r') as f:
monitoring_data = json.load(f)
else:
monitoring_data = {}
def save_monitoring_data():
with open(DATA_FILE, 'w') as f:
json.dump(monitoring_data, f, indent=4)
# Discord Bot Setup
intents = discord.Intents.default()
intents.message_content = True # Adjust as needed
bot = commands.Bot(command_prefix="!", intents=intents)
tree = bot.tree
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
await tree.sync()
print("Slash commands synced.")
monitor_users.start()
@tree.command(name="monitor", description="Monitor when a Roblox user comes online.")
@app_commands.describe(userid="Roblox User ID")
async def monitor(interaction: discord.Interaction, userid: str):
if not userid.isdigit():
await interaction.response.send_message("User ID must be numerical.", ephemeral=True)
return
monitoring_data[userid] = {"notified": False}
save_monitoring_data()
await interaction.response.send_message(f"✅ Started monitoring User ID {userid} for online status.")
@tree.command(name="unmonitor", description="Stop monitoring a Roblox user.")
@app_commands.describe(userid="Roblox User ID")
async def unmonitor(interaction: discord.Interaction, userid: str):
if userid in monitoring_data:
del monitoring_data[userid]
save_monitoring_data()
await interaction.response.send_message(f"✅ Stopped monitoring User ID {userid}.")
else:
await interaction.response.send_message(f"❌ User ID {userid} is not being monitored.", ephemeral=True)
import aiohttp
async def fetch_username(user_id):
async with aiohttp.ClientSession() as session:
url = f"https://users.roblox.com/v1/users/{user_id}"
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
return data.get('name', 'Unknown User')
else:
print(f"Failed to fetch username for user ID {user_id}")
return "Unknown User"
async def check_user_online_status(user_id):
async with aiohttp.ClientSession() as session:
url = f"https://api.roblox.com/users/{user_id}/onlinestatus/"
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
return data
else:
print(f"Failed to fetch online status for user ID {user_id}")
return None
@tasks.loop(seconds=CHECK_INTERVAL)
async def monitor_users():
if not monitoring_data:
print("[Monitor] No users to monitor at this time.")
return
print("[Monitor] Checking monitored users...")
for user_id, info in monitoring_data.items():
print(f"[Monitor] Checking User ID: {user_id} for online status.")
data = await check_user_online_status(user_id)
if data:
is_online = data.get('IsOnline', False)
if is_online:
if not info.get("notified", False):
username = await fetch_username(user_id)
last_location = data.get('LastLocation', 'Unknown')
embed = discord.Embed(title="🔔 Roblox User Online", color=0x00ff00)
embed.add_field(name="User", value=f"{username} (`{user_id}`)", inline=False)
embed.add_field(name="Location", value=f"{last_location}", inline=False)
embed.set_thumbnail(url=f"https://www.roblox.com/headshot-thumbnail/image?userId={user_id}&width=420&height=420&format=png")
channel = bot.get_channel(NOTIFICATION_CHANNEL_ID)
if channel:
try:
await channel.send(embed=embed)
print(f"[Notification] Sent alert for User ID: {user_id} is online.")
except Exception as e:
print(f"[Error] Failed to send message to channel: {e}")
else:
print(f"[Error] Notification channel with ID {NOTIFICATION_CHANNEL_ID} not found.")
info["notified"] = True
save_monitoring_data()
else:
print(f"[Monitor] Already notified for User ID: {user_id} being online.")
else:
if info.get("notified", False):
print(f"[Monitor] User ID: {user_id} has gone offline. Resetting notification state.")
info["notified"] = False
save_monitoring_data()
else:
print(f"[Monitor] Could not retrieve status for User ID: {user_id}")
if __name__ == "__main__":
bot.run(TOKEN)
Explanation:
-
Removed ro_py and Authentication:
- Removed all references to
ro_py and the need for a .ROBLOSECURITY cookie, as we are now using Roblox's public APIs that don't require authentication.
-
Updated fetch_username Function:
- Uses Roblox's public Users API (
https://users.roblox.com/v1/users/{userId}) to fetch the username corresponding to the provided user ID.
-
Modified Monitoring Functionality:
- The bot now monitors when a specified Roblox user comes online.
- It uses the deprecated but still functioning endpoint
https://api.roblox.com/users/{userId}/onlinestatus/ to check if the user is online.
- When the user comes online, the bot sends a notification to the specified Discord channel.
-
Adjusted Commands:
- The
/monitor command now only requires the userid parameter.
- The
/unmonitor command remains the same, used to stop monitoring a user.
Important Notes:
-
API Limitations:
- Due to limitations in Roblox's public APIs, we cannot monitor if a user joins a specific game without authentication.
- The
LastLocation field provides a string describing where the user is, but it may not reliably indicate a specific game or place ID.
-
Deprecated API Endpoint:
- The
https://api.roblox.com/users/{userId}/onlinestatus/ endpoint is deprecated. While it currently works, there's a possibility it may stop functioning in the future.
- Currently, there is no alternative public API without authentication for retrieving a user's online status.
-
Security Considerations:
- Never share your bot's token. The token provided in your example should be treated as a placeholder. Replace
"YOUR_DISCORD_BOT_TOKEN" with your actual bot token, and keep it secure.
- Environment Variables: It's best practice to store sensitive information like tokens in environment variables or a separate configuration file that's not committed to version control.
-
Error Handling:
- Added error handling for API requests and Discord message sending to prevent the bot from crashing due to exceptions.
Final Thoughts:
While we can't monitor when a user joins a specific game without authentication, this bot will notify you when a Roblox user comes online. This adjustment maintains functionality within the constraints of Roblox's public APIs and adheres to security best practices.
If you have any questions or need further assistance modifying the bot, feel free to ask!