Discord.py Bot: Reacting To Server Kicks & Exits

by Lucas 49 views
Iklan Headers

Hey everyone! So, you're diving into the awesome world of Discord.py, and you're wondering how to make your bot react when it gets the boot (kicked) or when it peace-out (leaves) a server, right? No problem! This guide will walk you through the steps, making sure your bot knows what's up when it's no longer welcome. We'll cover the basics, so whether you're a coding newbie or a seasoned Python pro, you'll be able to understand and adapt the code to fit your needs. Let's get started, shall we?

Understanding the on_guild_remove Event in Discord.py

First things first, let's talk about the main event we'll be using: on_guild_remove. This is the magic trigger that fires whenever your bot is removed from a server. It could be because the bot was kicked, banned, or the server owner simply decided to remove it. The key here is that on_guild_remove handles all of these scenarios.

from discord.ext import commands

bot = commands.Bot(command_prefix="!")  # Or whatever prefix you like

@bot.event
async def on_guild_remove(guild):
    print(f"I have been removed from {guild.name} (ID: {guild.id})")
    # Add your code here to handle the removal

In this basic example, the bot will print a message to your console every time it's removed from a server. The guild parameter gives you information about the server, like its name and ID. Pretty simple, right? Now, let's dive into how to use this event to do some cool stuff.

Customizing Your Bot's Response

Now, let's get to the fun part: deciding what your bot should do when it's removed. This is where you can add your custom logic. Here are some ideas:

  • Logging: Log the event to a file or a database. This is super helpful for tracking bot usage and identifying potentially problematic servers.
  • Database Updates: If your bot uses a database (like SQLite, PostgreSQL, etc.), you can remove the server's data from the database. This keeps your database clean.
  • Notifications: Send a notification to your bot's owner or a specific channel, letting them know the bot has been removed from a server. This helps you stay informed.
  • Cleanup: Perform any necessary cleanup tasks, such as closing connections or releasing resources.

Let's look at a more practical example that involves database interactions. We'll use SQLite for simplicity. Make sure you have the sqlite3 module installed (it's usually included with Python).

import sqlite3
from discord.ext import commands

bot = commands.Bot(command_prefix="!")

# Database setup (outside the event for efficiency)
conn = sqlite3.connect('bot_data.db') # Replace with your database file
cursor = conn.cursor()

# Create a table if it doesn't exist (e.g., for server settings)
cursor.execute("""
CREATE TABLE IF NOT EXISTS servers (
    guild_id INTEGER PRIMARY KEY,
    setting_1 TEXT,
    setting_2 INTEGER
)
""")
conn.commit()

@bot.event
async def on_guild_remove(guild):
    print(f"Removing data for {guild.name} (ID: {guild.id}) from the database.")
    try:
        # Delete server data from your database
        cursor.execute("DELETE FROM servers WHERE guild_id = ?", (guild.id,))
        conn.commit()
        print(f"Successfully removed data for {guild.name}.")
    except Exception as e:
        print(f"Error removing data: {e}")

# Close the connection when the bot stops (optional but recommended)
@bot.event
async def on_disconnect():
    conn.close()

In this example, the bot tries to delete the server's data from a servers table in your SQLite database. The database setup is done outside the event, which is more efficient. The code includes error handling (try...except) to catch any issues. This way, your bot won't crash if there's a problem.

Additional Considerations

Here are some extra things to keep in mind when working with on_guild_remove:

  • Error Handling: Always include error handling in your event handlers. This helps prevent unexpected crashes and makes debugging easier. Use try...except blocks to catch potential exceptions.
  • Database Connections: If you're using a database, make sure you properly manage the connections. Open the connection when your bot starts and close it when it stops (or when the on_disconnect event fires).
  • Asynchronous Operations: Remember that Discord.py is asynchronous. Use async and await when performing operations that take time, such as database queries or network requests.
  • Permissions: Your bot needs the appropriate permissions to perform certain actions (e.g., sending messages to a channel). Ensure your bot has the necessary permissions in the Discord server settings.
  • Rate Limits: Be mindful of Discord's rate limits. Avoid sending too many requests in a short period. Use asyncio.sleep() to add delays if needed.

Detecting Kicks vs. Other Removals

While on_guild_remove covers all removal scenarios, there isn't a direct way to tell why the bot was removed (kick, ban, or owner removal) using just the on_guild_remove event itself. However, you can implement workarounds, but they might not be 100% accurate:

  1. Audit Log (Requires Permissions): If your bot has permission to view the server's audit log, you could try to check the audit log for 'bot kicked' events. This is the most reliable method, but it requires your bot to have the view audit log permission. You'll need to fetch the audit log entries for the server shortly before the on_guild_remove event fires. This approach involves fetching the audit log using guild.audit_logs(). The reason attribute of the audit log entry can provide valuable insight (e.g.,