我是一个初学者,我想用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)
你的问题不够清楚。我猜你正在尝试获得一个用户拥有的XP数量。如果我错了,纠正我,我会更新答案。
我假设您的表中有一列dis_id
和一列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_id
。机器人将发送一个包含用户拥有的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)