I’m working on a discord.py bot and want to add a feature where I can make the bot leave servers remotely. Here’s what I’m trying to do:
I have a main control server where I run all my admin commands
When someone misuses my bot in another server, I want to kick the bot out from my control panel
The command should work like !exit ServerName and send a goodbye message before leaving
Is this functionality actually achievable? I’ve been searching but can’t find clear examples of how to target specific guilds from commands run in different servers.
Any code examples or guidance would be really helpful. Thanks!
Building on what’s been shared - both approaches work but error handling is crucial here. My bot crashed multiple times trying to leave servers where it lost permissions or the server went offline.
I combine both name and ID lookup with better exception handling:
@bot.command()
async def exit(ctx, *, identifier):
if ctx.guild.id != CONTROL_SERVER_ID:
return
target_guild = None
# Try ID first, then name
if identifier.isdigit():
target_guild = bot.get_guild(int(identifier))
else:
for guild in bot.guilds:
if guild.name.lower() == identifier.lower():
target_guild = guild
break
if not target_guild:
await ctx.send("Server not found")
return
try:
# Attempt goodbye message with timeout
default_channel = target_guild.system_channel or next((ch for ch in target_guild.text_channels if ch.permissions_for(target_guild.me).send_messages), None)
if default_channel:
await asyncio.wait_for(default_channel.send("Leaving server. Contact support if needed."), timeout=5.0)
await target_guild.leave()
await ctx.send(f"Successfully left {target_guild.name}")
except asyncio.TimeoutError:
await target_guild.leave()
await ctx.send(f"Left {target_guild.name} (couldn't send goodbye message)")
except Exception as e:
await ctx.send(f"Error leaving server: {str(e)}")
The timeout prevents hanging when Discord’s API is slow, which happens more than you’d expect.
Yeah, totally doable with discord.py. I built something similar for managing multiple community servers.
Just iterate through the bot’s guilds and match by name or ID:
@bot.command()
async def exit(ctx, *, server_name):
if ctx.guild.id != YOUR_CONTROL_SERVER_ID:
return
target_guild = None
for guild in bot.guilds:
if guild.name.lower() == server_name.lower():
target_guild = guild
break
if target_guild:
# Send goodbye message to their general channel
for channel in target_guild.text_channels:
if channel.permissions_for(target_guild.me).send_messages:
await channel.send("Bot leaving due to admin decision. Goodbye!")
break
await target_guild.leave()
await ctx.send(f"Successfully left {target_guild.name}")
else:
await ctx.send(f"Server '{server_name}' not found")
Trickiest part is finding the right channel for the goodbye message. I target the first channel where the bot can actually send messages.
Honestly though, cross-server automation gets messy fast when you scale up. I moved all my Discord bot management to Latenode because it handles webhook integrations and server monitoring way cleaner than coding everything from scratch.
With Latenode you can automate responses to server events and manage multiple bots without writing tons of custom code. Way less headache than maintaining all that logic yourself.
This definitely works - I’ve done something similar before. One thing the previous answer missed: be careful about server name matching since multiple servers can have identical names.
I’d use guild IDs instead of names for better reliability. Keep a database or config file that maps server names to their actual IDs. Here’s how I’d approach it:
@bot.command()
async def exit(ctx, server_id: int):
if ctx.author.id not in ADMIN_IDS:
return
guild = bot.get_guild(server_id)
if not guild:
await ctx.send("Guild not found or bot not in that server")
return
try:
# Find default channel or first available
channel = guild.system_channel or guild.text_channels[0]
await channel.send("This bot is being removed by administrator.")
except:
pass # If we can't send message, just leave silently
await guild.leave()
await ctx.send(f"Left {guild.name} ({guild.id})")
Make sure you have proper permission checks since this is a powerful command. You don’t want random users kicking your bot from servers.
Had the same setup running bots across gaming servers. Core functionality works fine, but you’ll want guild caching to avoid hammering the API when searching by name. I store guild data locally and refresh it periodically instead of hitting Discord’s API every time. Saves bandwidth and prevents those undocumented rate limits they don’t mention in their docs.
@bot.command()
async def exit(ctx, *, guild_identifier):
if ctx.guild.id != CONTROL_GUILD_ID:
return await ctx.send("Unauthorized server")
guild = None
if guild_identifier.isdigit():
guild = bot.get_guild(int(guild_identifier))
else:
guild = discord.utils.get(bot.guilds, name=guild_identifier)
if not guild:
return await ctx.send("Guild not found")
await ctx.send(f"Leaving {guild.name} ({guild.member_count} members)")
await guild.leave()
Watch out though - bot.get_guild() can return None even for valid IDs if the bot temporarily loses connection. Always have fallback logic for network hiccups. Learned this the hard way managing event bots that needed to stay up during peak hours.
Add a confirmation step before leaving servers. I accidentally left a server with thousands of members because of a typo - learned that lesson the hard way. Now I send an embed first with server details (member count, creation date, etc.) and wait for a confirmation reaction. Saves you from embarrassing screwups when you’re juggling multiple communities. Log which admin triggered the leave command and when. Discord’s audit logs only show your bot left, not what caused it. My own logs helped me spot patterns when certain servers kept having problems. Goodbye messages are nice but don’t count on them. Servers have weird permissions and bots can lose send access right before leaving. I’ve seen bots get stuck trying to send farewell messages in channels they suddenly can’t reach.
Everyone’s showing the basic discord.py approach, but you’ll hit massive maintenance issues with this setup.
Those code examples work for small scale stuff. Once you’re managing dozens of servers? Complete nightmare. You’ll spend more time fixing API timeouts, permission errors, and rate limits than actually using it.
I had a similar Python bot system. Worked great until it didn’t. Then I’m debugging at 2am because some edge case broke everything.
What fixed this for me was switching to Latenode. Instead of coding custom Discord API handlers, I built workflows that monitor server activity and automate bot decisions.
Latenode connects straight to Discord webhooks and triggers actions across multiple servers - no bot code needed. Handles rate limiting, error recovery, and logging automatically.
You can set triggers for server events like spam detection or rule violations that pull your bot before you need to step in.
Way more reliable than custom Python scripts, plus you get proper logging and monitoring.
Yeah, totally doable but be careful with rate limits if you’re handling multiple servers. Discord will throttle you hard if you spam their API. I throw in small delays between guild operations so I don’t hit the bucket limits and get temporarily banned from making requests.