简体   繁体   English

有没有办法在 python 中将字符串定义为 function

[英]Is there a way to define a string as a function in python

This is my on message and I want a way to do this without getting the command not found error while still using the same prefix like it were a command.这是我的消息,我想要一种方法来做到这一点,而不会出现未找到命令错误,同时仍然使用与命令相同的前缀。 the only issue is I want the command.jail to add jail role and.human to add human role while having them be server specific.唯一的问题是我希望 command.jail 添加监狱角色和.human 添加人员角色,同时让它们特定于服务器。 the only way I could make this work is on message beause I cant find a way to define something you read from a file.我可以完成这项工作的唯一方法是在消息上,因为我找不到一种方法来定义您从文件中读取的内容。 anybody got tips有人得到提示

@bot.event
async def on_message(message):
    msg1 = message.content.lower().split()
    crcfile = "crcstorage/" + str(message.guild.id) + "crcdict.json"
    
    if os.path.exists(crcfile):
        with open(crcfile) as json_file:
            crcdict = json.load(json_file)
        
        for word in msg1:
            if word in crcdict:
                user = message.mentions[0]
                crcname = crcdict[word]
                role = discord.utils.get(message.guild.roles, name=crcname)
                if role in user.roles:
                    await user.remove_roles(role)
                else:
                    await user.add_roles(role)
    else:
        print("no file making new one")
        with open("crcstorage/" + 'crcdefault.json') as f:
            data = json.load(f)
        with open(crcfile, 'w') as f:
            json.dump(data, f, indent=2)
            print("New json file is created from crcdefault.json file")
    await bot.process_commands(message)

There's a bunch of work you need to do before actually running the command:在实际运行命令之前,您需要做很多工作:

  1. Filter out the bot messages过滤掉机器人消息
  2. Name your command (for instance, $run )命名您的命令(例如, $run
  3. Filter out messages without that prefix过滤掉没有该前缀的消息
  4. Finally, run the code that you already wrote.最后,运行您已经编写的代码。

So, consider moving your code to a separate function (ie run() , and do some filterings in the on_message() .因此,考虑将您的代码移动到单独的 function (即run() ,并在on_message()中进行一些过滤。

COMMAND_PREFIX = "$run"

async def run_command(message):
    
    msg1 = message.content.lower().split()
    
    # skip COMMAND_PREFIX
    msg1 = msg1[1:]
    
    crcfile = "crcstorage/" + str(message.guild.id) + "crcdict.json"
    
    if os.path.exists(crcfile):
        with open(crcfile) as json_file:
            crcdict = json.load(json_file)
        
        for word in msg1:
            if word in crcdict:
                user = message.mentions[0]
                crcname = crcdict[word]
                role = discord.utils.get(message.guild.roles, name=crcname)
                if role in user.roles:
                    await user.remove_roles(role)
                else:
                    await user.add_roles(role)
    else:
        print("no file making new one")
        with open("crcstorage/" + 'crcdefault.json') as f:
            data = json.load(f)
        with open(crcfile, 'w') as f:
            json.dump(data, f, indent=2)
            print("New json file is created from crcdefault.json file")

    # I'm not sure if you actually need the line below
    # await bot.process_commands(message)


@bot.event
async def on_message(message):
    # filter out bot's own messages
    if message.author == client.user:
        return

    # leave only messages that are prefixed with "$run"
    if not message.content.startswith(COMMAND_PREFIX):
        return

    # and finally process remaining messages as a commands
    await run_command(message)

From what I understood, if the user does: {prefix}{role_name} , the bot gives the rolename to the message.author and if there's a mention after that, it gives the role to that user.据我了解,如果用户这样做: {prefix}{role_name} ,机器人将角色名称提供给message.author ,如果之后有提及,它将角色提供给该用户。

First off, add the necessary filters like checking if the command is from a bot or user.首先,添加必要的过滤器,例如检查命令是来自机器人还是用户。 Also ensure that this message is used in a server and not DMs.还要确保此消息用于服务器而不是 DM。 Then, filter out if the message.startswith(prefix) and then apply the below code.然后,如果message.startswith(prefix)过滤掉,然后应用下面的代码。

try:
  user=message.mentions[0]
except IndexError:
  user=message.author

# Add any other necessary checks

role_name = message.content[len(prefix)].split()[0]

role = discord.utils.get(message.guild.roles, name=role_name)
if role: # Role found, else role=None
  # check to add/remove role from the user.
else:
  await bot.process_commands(message)

You won't face command not found error here because you're not trying to process the command unless it doesn't find a role with the command's name to add.您不会在此处遇到command not found错误,因为您不会尝试处理该命令,除非它找不到具有要添加的命令名称的角色。

The logic is simple, if there's a role with that name, then it's not the command and there's no need to process it, else you do need to process the command.逻辑很简单,如果有这个名字的角色,那么它不是命令,不需要处理它,否则你需要处理命令。

Edit: I would encourage you to use an async function to apply the above logic in on_message as it would look much cleaner.编辑:我鼓励您使用异步 function 在on_message中应用上述逻辑,因为它看起来更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法通过字符串定义PYthon函数参数列表? - Is there a way to define a PYthon function parameter list by a string? 有没有一种方法可以定义一个变量,该变量是Python函数内部的一个参数? - Is there a way to define a variable that is a parameter inside a function in Python? 有没有办法定义比较 function 到 Python 中的 issubset - Is there a way to define a compare function to issubset in Python Python定义和调用字符串表示的函数 - Python define and call function represented by string 如何使用python从字符串定义函数 - how to define a function from a string using python 在python模块中定义一个函数,使函数名等于一个字符串变量 - Define a function in a python module so that the function name equals to a string variable 有没有一种方法可以像python一样在android / java中定义函数字典? - Is there a way to define function-dictionaries in android/Java like in python? 有什么方法可以定义带有前导可选参数的 Python 函数吗? - Is there any way to define a Python function with leading optional arguments? Python:使用2元组列表定义函数的最快方法 - Python: fastest way to define a function using a list of 2-tuples 有没有一种方法可以将完整的代码块定义为变量,以代替 python 上的 goto function? - Is there a way to define a full block of code as a variable as a stand in for a goto function on python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM