如何让我的Discord Bot向服务器发送更干净的消息

2024-05-07 17:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经构建了一个discord机器人,它连接到一个sqlite3数据库,并为Minecraft领域保存特殊坐标。以下是我在本期中引用的代码:

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='!')

connection = sqlite3.connect("mc_coords.db")

cursor = connection.cursor()

createTable = f"""CREATE TABLE IF NOT EXISTS
mcCoords(coord_id INTEGER PRIMARY KEY, coords TEXT, coord_name TEXT)"""

cursor.execute(createTable)

@bot.command(name='coords', help = 'Responds with a list of all of the coordinates added to the list')
async def coordinates(ctx):
    getCoords = f"""SELECT coord_name, coords FROM mcCoords"""
    with connection:
        cursor.execute(getCoords)
    coords = cursor.fetchall()
    if len(coords) < 1:
        await ctx.send("There are currently no coordinates in the list")
        return
    print(coords)
    await ctx.send(coords)

在discord中调用use命令时,它会正确检索数据库中的数据,但会将其作为元组返回,如下所示:

[('water monument', '1160 61 -1747'), ('test', '123 456 789')]

我希望上面的数据以更好的格式返回,如下所示:

water monument: 1160 51 -1747
test: 123 456 789

有人知道怎么做吗?谢谢


Tags: thenametoken数据库botcoordsconnectionsqlite3
3条回答

(在这里,我将coords指定为一个变量,只是为了模拟数据,在您的情况下,不使用该行。)

不发送返回的数据,而是重新格式化:

coords = [("a", "b"), ("c", "d"), ("e", "f")] #any number of tuples
string_to_send = "\n".join([f"{place}: {coord}" for place, coord in coords])
print(string_to_send)

这张照片是:

a: b
c: d
e: f

不相关:您也应该考虑使用嵌入来使消息更漂亮。

这可能有一个函数,但如果我面对这个问题,我会这样做:

for coord in coords:
    for i in range(0, coord.count("(")+1):
        coord = str(coord).replace("(", "").replace(")", "").replace(",", ":")
    print(coord)

你可以在这里使用字典

water monument: 1160 51 -1747
test: 123 456 789

上面的输出是在字典中使用的键值格式。 这里最好的部分是,只有元组可以用来构成字典,因为它们是不可变的

在你的例子中,我们得到了元组。因此,可以在此处返回字典而不是元组

例如:

import string 

string.ascii_lowercase

{item: ix for ix, item in enumerate(string.ascii_uppercase,1)}

这会将输出返回为:

{'A':1, “B”:2, "C":3,, "丁":四,, “E”:5,…}这是一本字典

这里,ix是我的枚举器是我的字母。我以item : ix的形式返回它,它是key : Value格式的

使用大括号返回字典中的输出,即{ }

相关问题 更多 >