如何让我的机器人收到消息的结尾并在其后面留言重复?这是我的代码:
elif message.content.startswith('/ban'):
bant = message.content.endswith('') and ('has been bant')
await client.send_message(message.channel, bant)
如果我说例如/ ban chiken
我想说:chiken一直不能
或者如果我说/禁止杰夫
我想说:杰夫一直不能
答案 0 :(得分:0)
message.content
是一个类似"/ban jeff"
我们可以使用str.split
在第一个空格
_, target = message.content.split(' ', 1)
target
将为"jeff"
对于较长的字符串/ban jeff andy
,我们只拆分一次,因此target
将为"jeff andy"
。
然后我们可以使用它来构建我们的响应
bant = '{} has been bant'.format(target)
答案 1 :(得分:0)
discord.Message.content
返回一个字符串,因此您需要进行简单的字符串操作。幸运的是,python是一种非常好的语言。
# There are various ways to address the issue.
# These are ranked from most recommended to least
# assuming content is: '/ban daisy boo foo'
arguments = message.content.lstrip('/ban')
# returns 'daisy boo foo'
arguments = message.content.split(' ', 1)
# returns 'daisy boo foo'
arguments = shlex.split(message.content)[1:]
# returns ['/ban', 'daisy', 'boo', 'foo']
# but we slice it to just ['daisy', 'boo', 'foo']
arguments = message.content[len('/ban'):]
# returns 'daisy boo foo'
如果你正在考虑使用这个if / elif内容以某种模式方法开始为你的机器人提供一个命令功能我不会推荐它,discord.py包含它自己的命令扩展来直接适应这些问题。< / p>
作为如何使用命令扩展来执行此操作的基本示例,这里有一些代码。
(假设discord.py rewrite 1.0.0a)
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='/')
@bot.command()
async def ban(ctx, user: discord.Member):
await user.ban()
@ban.error
async def ban_error(ctx, error):
await ctx.send(error)
bot.run('token')