【发布时间】:2020-08-21 05:27:09
【问题描述】:
我想在 python 上为我的 discord 机器人制作自定义前缀系统。我怎样才能做到?
【问题讨论】:
-
你知道如何判断一个字符串是否以另一个字符串开头吗?当您尝试自己解决问题时,您想到了什么?
标签: python discord discord.py
我想在 python 上为我的 discord 机器人制作自定义前缀系统。我怎样才能做到?
【问题讨论】:
标签: python discord discord.py
我假设您正在谈论让每个服务器都有一个自定义前缀。如果您使用的是异步分支,我建议您这样做。在与您的 .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
您可以在创建机器人实例时通过传递 command_prefix 参数来设置自定义前缀:
client = commands.Bot(command_prefix = "custom_prefix_here")
或者如果你使用的是重写版本:
client = discord.ext.commands.Bot(command_prefix = "custom_prefix_here");
【讨论】: