python - 如何从 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)
解决方案
你的问题不够清楚。我猜您正在尝试获取用户拥有的 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_id
discord 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)
推荐阅读
- nestjs - 如何在 NestJS 中拆除 MikroOrm
- azure - 能够对 API 管理服务的调用进行交互式登录吗?
- keras - 将 keras 图模型转换为 tf.js 时出错
- docker - 如何重置 couchbase docker 容器密码
- pandas - 带有值错误的熊猫数据框应用功能
- ruby - 在 Catalina 10.15.2 上安装 cocoapods 时出错
- python - 为时间序列预测预处理数据
- docker - 如何在 linux (Android) 中修改配置文件 (/proc/config.gz)?
- google-aiy - 如何使用 AIY Vision Bonnet 将相机旋转 90 度?
- unity3d - 有没有办法在 Unity 中修复这个错误?