discord.js中如何检测消息作者ID是否在MySQL数据库并实现新增?
Got it, let's break this down step by step—since you already have MySQL basics down, we'll focus on tying that into your Discord bot with discord.js. The core goal is: when a user sends a message, verify if their ID exists in your database; if not, add them with default level/XP values.
1. First: Set Up Your MySQL Table
Let's start with the right table structure. Create a table (we'll call it member_levels) to store each user's Discord ID, level, and XP. Run this SQL in your MySQL client:
CREATE TABLE IF NOT EXISTS member_levels ( user_id VARCHAR(255) NOT NULL PRIMARY KEY, level INT DEFAULT 1, xp INT DEFAULT 0 );
- We use
VARCHARforuser_idbecause Discord IDs are large numeric strings—storing them as numbers can cause overflow issues in some cases. DEFAULT 1andDEFAULT 0ensure new users start at level 1 with 0 XP automatically, so you don't have to specify those values every time you add someone.
2. Connect MySQL to Your Discord.js Bot
We'll use the mysql2 library (it supports promises, which makes async code way cleaner). First install it:
npm install mysql2
Then set up a connection pool in your bot code (connection pools are better than single connections for bots—they reuse connections efficiently instead of creating/destroying them every time):
const mysql = require('mysql2/promise'); // Create a connection pool with your MySQL credentials const pool = mysql.createPool({ host: 'your-host', // usually 'localhost' if running locally user: 'your-mysql-username', password: 'your-mysql-password', database: 'your-database-name', waitForConnections: true, connectionLimit: 10, queueLimit: 0 });
Replace the placeholder values with your actual MySQL login details.
3. Core Function: Check User Existence & Create if Missing
Now let's write an async function that takes a user ID, checks if they're in the database, and adds them if they aren't. We'll use async/await to handle the asynchronous database calls smoothly.
async function checkOrCreateMember(userId) { try { // First, check if the user already exists const [rows] = await pool.execute('SELECT * FROM member_levels WHERE user_id = ?', [userId]); if (rows.length === 0) { // User doesn't exist—insert them with default level/XP await pool.execute('INSERT INTO member_levels (user_id) VALUES (?)', [userId]); console.log(`Added new user to database: ${userId}`); } else { console.log(`User ${userId} is already in the database`); } } catch (error) { console.error('Error checking/creating member:', error); } }
- The
?in the SQL queries are placeholders—this prevents SQL injection, which is critical for security (never concatenate user input directly into SQL strings!). - We wrap everything in a
try/catchto handle any database errors (like connection drops or invalid queries) gracefully.
4. Hook the Function into Your Message Event
Finally, connect this function to your bot's messageCreate event so it runs every time a user sends a message:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent // Required to read message content ] }); client.on('messageCreate', async (message) => { // Ignore bot messages to avoid cluttering the database if (message.author.bot) return; // Check if the user exists, create them if not await checkOrCreateMember(message.author.id); // From here, you can add XP/level update logic, e.g.: // await pool.execute('UPDATE member_levels SET xp = xp + 10 WHERE user_id = ?', [message.author.id]); }); client.login('your-bot-token');
- Don't forget to enable the required intents in your Discord Developer Portal (Guilds, GuildMessages, MessageContent)—without these, your bot won't receive message events.
- Ignoring bot messages prevents unnecessary database calls from other bots interacting with your server.
Quick Pro Tips
- If you need to fetch the user's level/XP after checking, modify the function to return
rows[0]if the user exists, or the newly inserted data. - For high-traffic servers, consider adding a small cooldown to XP updates so users can't spam messages to farm XP.
- Always test your database queries separately first to make sure they work before tying them into your bot.
内容的提问来源于stack exchange,提问作者DR_BOMBAY




