首页 > 解决方案 > 如何从 MySQL 数据库中插入和获取数据并将其发送到 Discord

问题描述

我是初学者,我想用 python 编写一个 Discord 机器人。我已连接到我的数据库并从数据库中获取数据,但我不知道如何将数据发送到不和谐服务器通道。

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='xp')
cur = conn.cursor()
cur.execute("SELECT dis_id FROM users ")

for row in cur:
    xp = row
    print(xp)

if message.content.startswith('+xp'):
    mbed = discord.Embed(
       title=" Bot Information ",
       description = str(xp),
       colour=(discord.Colour.green())
    )
    channel = client.get_channel(828248385369669642)
    await channel.send(embed=mbed)
    

标签: pythonmysqldiscorddiscord.py

解决方案


你的问题不够清楚。我猜您正在尝试获取用户拥有的 XP 数量。如果我错了,请纠正我,我会更新答案。

我假设您的表格有一列 fordis_id和一列 for xp。如果是这样,这里是如何根据用户 ID 获取 XP。

首先,如果您打算制作命令,则需要指定命令前缀。在您定义客户的地方执行此操作。

client = commands.Bot(command_prefix='+') #"+" is the command prefix. Every message starting with "+" will be a command.

现在让我们编写xp命令,这样当有人+xp输入聊天时,命令就会被执行。

@client.command() #All commands start with this line called a decorator.
async def xp(ctx, user_id : int): # The command takes in a "context" argument and a "user_id" argument.
    cur.execute(f"SELECT * FROM users WHERE dis_id = {user_id}") # Select all the items for the specified "user_id"

    for row in cur: 
        xp = int(row[0]) # Get the amount of xp the user has
        print(xp)

    mbed = discord.Embed( # Define the embed
       title=" Bot Information ",
       description = str(xp),
       colour=(discord.Colour.green())
    )
    channel = client.get_channel(828248385369669642)
    await channel.send(embed=mbed) #Send the embed to the channel

所以现在当你想运行这个命令时,你需要输入+xp user_iddiscord chat。该机器人将发送一个嵌入的用户拥有的 XP 数量。

这是完整的代码

import discord
from discord.ext import commands
import mysql.connector

client = commands.Bot(command_prefix='+')

conn = mysql.connector.connect(host='localhost', port=3306, user='root', passwd='', database='xp')
cur = conn.cursor()

@client.command()
async def xp(ctx, user_id : int):
    cur.execute(f"SELECT * FROM users WHERE dis_id = {user_id}") 

    for row in cur:
        xp = int(row[0])
        print(xp)

    mbed = discord.Embed(
       title=" Bot Information ",
       description = str(xp),
       colour=(discord.Colour.green())
    )
    channel = client.get_channel(828248385369669642)
    await channel.send(embed=mbed)

推荐阅读