Python Discord bot,我希望用户输入两个名称并将其合并为一个并搜索JSON数据

mmvthczy  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(115)

{"draw ":0," recordsTotal ":1261," recordsFiltered ":1261," data ":[{" id":"1","ClassID":null,"Name":"Default Sword","Description":"Legends!","类型":“剑”、“元素”:"无","文件":" items/swords/GasparianBlade.swf ","链接":"GasparianBlade","Icon":【剑】、【装备】:“武器”、“等级”:" 1 "," DPS ":“25”,“范围”:“10”,“稀有度”:“3”,“数量”:"1","堆栈":" 1 ","成本":“0”,“硬币”:"0","Crystal":" 0 ","卖出":“1”、“市场”:“1”,“临时”:"0","升级":" 0","创始人":" 0"," VIP":" 0","人员":" 0"," EnhID":"% 1"," FactionID":null," ReqReputation":" 0"," ReqClassID":null," ReqClassPoints":" 0","请求任务":""," QuestStringIndex":"-1"," QuestStringValue":" 0","元":null,"颜色":" ffffff "},{" id":" 2"," ClassID":"% 1","名称":“流浪汉”、“简介”:“一个没有什么经验的流浪者,我们必须继续前进,学习更多关于冒险的知识!","类型":“类”、“元素”:"无","文件":" CyberPeasant.swf "," Link ":“网络农民”、“图标”:"cclass","设备":" ar "," Level ":"1","DPS":“25”,“范围”:“50”,“稀有度”:“3”,“数量”:" 1 ","堆栈":"1","成本":“0”,“硬币”:" 0 "," Crystal ":"0","卖出":“1”、“市场”:“1”,“临时”:" 0","升级":" 0","创始人":" 0"," VIP":" 0","人员":" 0"," EnhID":"% 1"," FactionID":null," ReqReputation":" 0"," ReqClassID":null," ReqClassPoints":" 0","请求任务":""," QuestStringIndex":"-1"," QuestStringValue":" 0"," Meta":null,"颜色":" ffffff "},{" id":" 3"," ClassID":null," Name":“炎魔之刃(测试版)”,“说明”:
这是我的数据,我创建了一个python discord bot,当用户输入Name:聋剑它输出的id:1但不一致的是它只接受第一个单词并输出未找到“Deafult”如何让python脚本取这两个“Deafult Sword”并搜索json数据并输出id:1

  1. @bot.command()
  2. async def item(ctx, item):
  3. data = "* data *"
  4. info_dict = json.loads(data)
  5. # Taking user input
  6. user_input_name = item
  7. # Find and print the ID if Name matches
  8. for entry in info_dict['data']:
  9. if entry.get("Name") == user_input_name:
  10. await ctx.send(f"Name : {item} - ID : {entry['id']}")
  11. break
  12. else:
  13. await ctx.send("ID not found. try writing full name."

字符串

clj7thdc

clj7thdc1#

引用official discord.py documentation
Discord bot命令将命令名称后的空格分隔的单词作为单独的参数。要使用一个中间有空格的单词,你应该这样引用它:/item "Default Sword" => Default Sword。作为一个警告,如果你省略了引号,你只会得到你在你的问题中描述的第一个词:/item Default Sword => Default
由于位置参数只是普通的Python参数,你可以有任意多个:

  1. @bot.command()
  2. async def test(ctx, arg1, arg2):
  3. await ctx.send(f'You passed {arg1} and {arg2}')

字符串
如果你想接受所有的参数(空格分隔的单词),你可以使用Python的*args功能,如下所示:

  1. @bot.command()
  2. async def item(ctx, *args):
  3. data = "* data *"
  4. info_dict = json.loads(data)
  5. # Merging the args into one string
  6. user_input_name = " ".join(args)
  7. # Find and print the ID if Name matches
  8. for entry in info_dict['data']:
  9. if entry.get("Name") == user_input_name:
  10. await ctx.send(f"Name : {item} - ID : {entry['id']}")
  11. break
  12. else:
  13. await ctx.send("ID not found. try writing full name.")


我希望这能解决你的问题。祝你今天愉快!

展开查看全部

相关问题