Python 将输入解析为命令、参数和这些参数的值的好方法是什么?
我正在尝试使用Python中的Discord.py模块创建一个Discord机器人,该模块能够解析出命令。我遇到的问题是,我希望每个命令都有参数,用a-表示。 例如,如果有人发送sm!poll-m='Test'-s bot应该返回{user}asked:Test。如果有人发短信!poll-m='Test-2'机器人应该回复@everyone{user}提问:Test-2 这就是问题所在。我使用-来表示一个参数,但我也希望能够在bot发送的轮询中使用它。以下是我目前掌握的代码:Python 将输入解析为命令、参数和这些参数的值的好方法是什么?,python,parsing,discord.py,Python,Parsing,Discord.py,我正在尝试使用Python中的Discord.py模块创建一个Discord机器人,该模块能够解析出命令。我遇到的问题是,我希望每个命令都有参数,用a-表示。 例如,如果有人发送sm!poll-m='Test'-s bot应该返回{user}asked:Test。如果有人发短信!poll-m='Test-2'机器人应该回复@everyone{user}提问:Test-2 这就是问题所在。我使用-来表示一个参数,但我也希望能够在bot发送的轮询中使用它。以下是我目前掌握的代码: async def
async def on_message(message):
if message.content.startswith('sm!'):
cmd=(message.content+'! ').split('!')[1]#finds everything after sm!
param=(cmd+"- ").split('-')[1:]# separates out all of the parameters
paramDict={}# makes a dictionary to hold the parameters
for i in param:
temp=i.split('=')# tries to split each parameter into a parameter and a value
try:
temp[1]
except IndexError:# if there is no value, sets the value to true
temp.append(True)
paramDict[temp[0]]=temp[1]
最终目标是有一个名为cmd的变量,我可以使用startswith on,还有一个包含消息中所有参数的字典
基本上,如果-在引号之间,则忽略它,但如果它在引号之外,则将其视为参数
谢谢你的帮助 谢谢你的帮助@KarlKnechtel 我使用shlex.split以空格分隔消息,保留引号内的任何内容
import shlex
async def on_message(message):
if message.content.startswith('sm!'):
cmd=message.content.split('!',1)[1]
sep=shlex.split(cmd)
params={}
params['cmd']=sep[0]
for i in sep[1:]:
try:
params[i.split('=',1)[0]]=i.split('=',1)[1]
except IndexError:
params[i.split('=',1)[0]]=True
使用on_message函数管理命令不是正确的方法
我建议你使用分机
这是导入它的方式:
从discord.ext导入命令
主菜单中的命令__
如果您希望命令位于_主文件中,请按照以下方式创建命令:
在主管道中
@机器人命令
异步定义hellocontext,我的参数:
wait context.sendfHello{my_arg}
用法:
.hello world
输出:
Hello world
从__main发出的命令__
或者,如果希望将命令存储在外部文件中并将其作为对象进行管理,则可以使用discord.py扩展系统。
您的命令将写入名为Cog的对象中
这就是你如何做到的:
# Inside my_cog.py
from discord.ext import commands
class MyCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def my_command(self, context):
"""
DO SOMETHING
"""
# OUT OF THE CLASS
def setup(bot):
bot.add_cog(MyCommand(bot))
现在,您必须告诉您的机器人在哪里可以找到您刚才编写的命令:
# In __main__.py
import discord
import asyncio
import os
from discord.ext import commands
class Main:
def __init__(self):
# Private
self.__TOKEN = os.environ["YOUR_TOKEN"] # Safety first, use os.environ !
self.__prefix = ['.'] # You can store multiple prefixes
self.__extensions = ["extensions.my_command"] # Path to my_command.py file
def run(self):
bot = commands.Bot(command_prefix=self.__prefix)
"""
YOUR STUFF
"""
# Load your extensions
for extension in self.__extensions
await asyncio.sleep(0)
bot.load_extension(extension)
client.run(self.__TOKEN)
if __name__ == "__main__":
Main().run()
这就是使用discord.py管理命令的方式
我强烈建议你阅读《医生》
希望有帮助!享受与discord.py合作的乐趣 基本上,如果-在引号之间,则忽略它,但如果它在引号之外,则将其视为参数。尝试SHILC.SPLION第一SLEX在标准库中,看看它是否足够适合您的目的。“KalnKunChelt将在您使用SLeX拆分命令之后,您可能需要考虑使用AgPARSE来处理选项。请注意,argparse不限于解析sys.argv。您可以将要解析的列表作为参数提供给parse_args;仅当未提供参数时才使用sys.argv。