[英]Problems with PyMongo: Checking a collection
我目前正在使用Python學習MongoDB,並且正在使用Discord機器人嘗試項目。 我想做一些事情,但我不知道該怎么做。
第一個問題如下:
@bot.command(pass_context=True)
async def test(ctx, arg:str=None):
db = client.db_test
collection = db["test"]
cursor = collection.find({"permission" : arg})
if perm is not None:
if perm == "x":
for y in cursor:
await bot.say(y)
機器人發送此消息:
{'_id': '<id>', 'name': '<name>', 'permission': 'x'}
但我希望它發送如下:
<name> has permission x
第二個問題如下:
我想檢查用戶是否具有權限“ x”並打印如下內容:
<name> has permission admin
我該如何解決並做到這一點?
在此細分中:
for y in cursor:
await bot.say(y)
y
實際上是Python dict
如打印時所見。 在這種情況下,您要做的就是從字典中獲取所需的值並自己創建字符串。
那將是(使用str的format()方法:
answer = "{} has permission {}".format(y["name"], y["permission"])
因此,您所需要做的就是返回它,而不是像tis一樣返回y:
for y in cursor:
answer = "{} has permission {}".format(y["name"], y["permission"])
await bot.say(answer)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.