How to develop a Discord bot that interacts with MySQL based on user commands

I’m looking to create a Discord bot that can respond to private messages and query a MySQL database. The functionality I want includes:

When a user sends a command in a direct message (for example, !check myPassword), the bot should:

  1. Verify if the user’s Discord name is present in my MySQL database.
  2. If they are in the database, send the user information from relevant columns.
  3. If not found, provide an error message instead.

I’m uncertain about how to establish a connection between the bot and MySQL or how to execute a query using the Discord username. Any tips on this process would be greatly appreciated.

u should check out discord.py and mysql-connector-python for db connection. first, set your bot token. then, use @bot.event for on_message to handle DMs. when a user sends the command, parse it, run your query, and be careful with inputs to avoid SQL injections!

I’ve built something similar and hit a few gotchas. The mysql-connector approach works well, but set up connection pooling so multiple users don’t overwhelm your database. Store Discord user IDs instead of usernames - usernames change but IDs don’t. Use parameterized queries like cursor.execute("SELECT * FROM users WHERE discord_id = %s", (user.id,)) to prevent injection attacks. Database connection timeouts caught me off guard, so add reconnection logic or use SQLAlchemy for better connection management.

Discord permissions will bite you - learned this the hard way. Your bot needs read message history and send DMs permissions, or users won’t get any responses even when your database works fine. Add rate limiting to your commands too, or spam queries will hammer your MySQL server. Always wrap database operations in try-catch blocks because network issues between the bot and database are inevitable. Oh, and use a separate test database - you don’t want to break production data while debugging.