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

时间:2020-08-21 18:47:15

标签: python discord.py

我已经构建了一个Discord机器人,该机器人可以连接到sqlite3数据库,并拥有Minecraft领域的特殊坐标。这是我在此问题中引用的代码:

HTML5

当我在discord中调用命令时,它可以正确地检索数据库中的数据,但是将其作为一个元组返回,就像这样:

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)

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

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

有人对如何执行此操作有任何想法吗?谢谢!

4 个答案:

答案 0 :(得分:0)

最短的方法

f_msg = '\n'.join(f"{k}: {v}" for k, v in coords)
await ctx.send(f_mesg)

删除await ctx.send(coords)并添加这两行。

如果您想将加粗,

f_msg = '\n'.join(f"**{k}:** {v}" for k, v in coords)

答案 1 :(得分:0)

(在这里,我将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

不相关:您还应该考虑使用嵌入来使邮件更漂亮。

答案 2 :(得分:0)

可能有一个函数,但是如果我遇到这个问题,我会这样做:

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

答案 3 :(得分:0)

您可以在此处使用字典。

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, 'D':4, 'E':5,........ }这是一本字典。

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

使用花括号即{ }

返回在Dictionary中的输出
相关问题