Python3 和 MariaDB 使用 Discord Py
Python3 and MariaDB using Discord Py
我编写了一个机器人,可以根据用户输入将内容插入数据库,而且效果很好。然而,有时数据库 returns 多个相同的字符串,而机器人只使用第一个。解决此问题的最佳方法是什么,以便用户可以选择正确的选项,而不是仅使用第一个选项的机器人。
编辑以进一步说明:
cursor.execute("SELECT name FROM forts WHERE name LIKE '" + str(arg) + "%';")
gym_title = str(cursor.fetchall())
有时会出现多个相同的地方,例如星巴克。我没有更改它们,而是想知道是否可以让 discord 机器人回复每一个,并且用户可以选择正确的选项。
这实际上比听起来更棘手,因为 discord.py
的事件驱动模型。我们的命令将接受我们查询的一些参数,并 return 向用户提供他们选择的逐项列表。我们将该用户和该列表存储在字典中。然后,在我们的 on_message
事件中,我们将根据我们关心的作者的字典检查每条消息,并尝试将他们的消息解释为列表中的选项,直到他们做出有效选择。
waiting_for = {}
@bot.command(pass_context=True)
async def fort(ctx, arg):
# database setup stuff
names = cursor.execute("SELECT name FROM forts WHERE name LIKE '" + str(arg) + "%';")
if not names:
await bot.say("That fort does not exist")
elif len(names) == 1:
await process_fort(name)
else:
choices = "\n".join("{}. {}".format(i, x) for i, x in enumerate(names, start=1))
await bot.say("Your choices are")
await bot.say(choices)
waiting_for[ctx.message.author.id] = names
@bot.event
async def on_message(message):
id = message.author.id
if id in waiting_for:
if message.content.isdigit():
names = waiting_for[id]
selection = int(message.content)
if 0 < selection < len(names):
del waiting_for[id]
await process_fort(name)
return
await bot.process_commands(message)
# Whatever you want to do with the name once you have it
async def process_fort(name):
...
如果这看起来很复杂,您也可以向用户回显所有可能性,直到输入一个只有 return 一个结果的查询。
我编写了一个机器人,可以根据用户输入将内容插入数据库,而且效果很好。然而,有时数据库 returns 多个相同的字符串,而机器人只使用第一个。解决此问题的最佳方法是什么,以便用户可以选择正确的选项,而不是仅使用第一个选项的机器人。
编辑以进一步说明:
cursor.execute("SELECT name FROM forts WHERE name LIKE '" + str(arg) + "%';")
gym_title = str(cursor.fetchall())
有时会出现多个相同的地方,例如星巴克。我没有更改它们,而是想知道是否可以让 discord 机器人回复每一个,并且用户可以选择正确的选项。
这实际上比听起来更棘手,因为 discord.py
的事件驱动模型。我们的命令将接受我们查询的一些参数,并 return 向用户提供他们选择的逐项列表。我们将该用户和该列表存储在字典中。然后,在我们的 on_message
事件中,我们将根据我们关心的作者的字典检查每条消息,并尝试将他们的消息解释为列表中的选项,直到他们做出有效选择。
waiting_for = {}
@bot.command(pass_context=True)
async def fort(ctx, arg):
# database setup stuff
names = cursor.execute("SELECT name FROM forts WHERE name LIKE '" + str(arg) + "%';")
if not names:
await bot.say("That fort does not exist")
elif len(names) == 1:
await process_fort(name)
else:
choices = "\n".join("{}. {}".format(i, x) for i, x in enumerate(names, start=1))
await bot.say("Your choices are")
await bot.say(choices)
waiting_for[ctx.message.author.id] = names
@bot.event
async def on_message(message):
id = message.author.id
if id in waiting_for:
if message.content.isdigit():
names = waiting_for[id]
selection = int(message.content)
if 0 < selection < len(names):
del waiting_for[id]
await process_fort(name)
return
await bot.process_commands(message)
# Whatever you want to do with the name once you have it
async def process_fort(name):
...
如果这看起来很复杂,您也可以向用户回显所有可能性,直到输入一个只有 return 一个结果的查询。