【问题标题】:How to make discord.py custom prefixes system?如何制作 discord.py 自定义前缀系统?
【发布时间】:2020-08-21 05:27:09
【问题描述】:

我想在 python 上为我的 discord 机器人制作自定义前缀系统。我怎样才能做到?

【问题讨论】:

  • 你知道如何判断一个字符串是否以另一个字符串开头吗?当您尝试自己解决问题时,您想到了什么?

标签: python discord discord.py


【解决方案1】:

我假设您正在谈论让每个服务器都有一个自定义前缀。如果您使用的是异步分支,我建议您这样做。在与您的 .py 文件相同的目录中创建一个名为 prefixes.txt 的文件。之后,只需使用这段代码,剩下的就交给它了:

import discord

bot = discord.Client()

def get_prefix(guild_id):
    file = open('prefixes.txt') 
    for line in file.readlines():
        line = line.split(',')
        if(line[0] == str(guild_id)):
            return line[1]
    return '!'

@bot.event
async def on_message(message):
    prefix = get_prefix(message.guild.id)
    command = message.content.split(' ')[0].replace(prefix, '')
    if(message.content.startswith(prefix)):
        if(command == 'some_command_name'):
            #do stuff

        if(command == 'prefix'):
            file = open('prefixes.txt')
            newfile = ''
            for line in file.readlines():
                lineSplit = line.split(',')
                if(lineSplit[0] == str(message.guild.id)):
                    newfile += str(message.guild.id) + ',' + message.content.split(' ')[1]
                else:
                    newfile += line
            file = open('prefixes.txt', 'w')
            file.write(newfile)
            await message.channel.send('The prefix for this server is now `' + message.content.split(' ')[1] + '`')
                    

bot.run('token')

【讨论】:

  • 我试过这段代码,但我得到一个错误:Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\Максим\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event await coro(*args, **kwargs) File "5.py", line 29, in on_message await message.channel.send('The prefix for this server is now `' + message.content.split(' ')[1] + '`') IndexError: list index out of range
  • @IAMLegen 你确定在输入命令后加上前缀吗?
  • 我收到了前缀已更改的确认消息,但实际上并没有更改。当我在更改后转到我的 prefixes.txt 时,我的编辑器提供重新加载以显示新文件。当我重新加载时,它仍然是一个空白文件。所以它看起来像是在文件中写入,但实际上并没有写入任何内容
  • @IAMLegend hmm 那么可能是编辑器的问题。你用什么编辑器?
【解决方案2】:

您可以在创建机器人实例时通过传递 command_prefix 参数来设置自定义前缀:

client = commands.Bot(command_prefix = "custom_prefix_here")

或者如果你使用的是重写版本:

client = discord.ext.commands.Bot(command_prefix = "custom_prefix_here");

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 2021-04-04
    • 2021-11-01
    • 2020-12-31
    • 2021-03-30
    • 2020-05-20
    • 2021-07-19
    • 2020-11-25
    相关资源
    最近更新 更多