如何在discord上结束消息并让我的机器人重复它?

时间:2018-01-20 21:40:27

标签: python discord

如何让我的机器人收到消息的结尾并在其后面留言重复?这是我的代码:

elif message.content.startswith('/ban'):
        bant = message.content.endswith('') and ('has been bant')
        await client.send_message(message.channel, bant)

如果我说例如/ ban chiken

我想说:chiken一直不能

或者如果我说/禁止杰夫

我想说:杰夫一直不能

2 个答案:

答案 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')