【问题标题】:How can I remove a character from message.content?如何从 message.content 中删除字符?
【发布时间】:2021-10-01 18:00:31
【问题描述】:

我目前正试图让我的机器人说出我所说的任何内容。因此,如果我的消息以“§”符号开头,机器人就会被激活。它应该删除我的消息,删除其中的“§”字符,然后在同一个聊天中发布不带该符号的消息。

我尝试了一些方法,包括减去符号或将其设为字符串,但没有任何效果。那么,我该怎么办?

@client.event
@commands.has_permissions(manage_messages = True)
async def on_message(message):
    if message.content.startswith('§'):
        channel1 = message.channel
        await message.delete()
        await channel1.send(f'{message.content}' - '§')

在这里,我收到一条错误消息:

await channel1.send(f'{message.content}' - '§')
TypeError: unsupported operand type(s) for -: 'str' and 'str'

我怎样才能使“§”符号从消息中删除?

【问题讨论】:

  • 只需使用对应的字符串切片从字符串中删除第一个字符 => message.content[1:]

标签: python discord discord.py chatbot


【解决方案1】:

用空字符串替换前缀

await channel1.send(f"{message.content.replace('§', '')}")

【讨论】:

  • 请注意,这将删除字符串中每个出现的字符,而不仅仅是第一个。
  • 在这种情况下,添加第三个参数,指定它将替换多少出现次数。
  • 好的,我该怎么做?你能给我举个例子吗?对不起,我对编码不是很了解。目前正在学习。
  • ... 或者直接删除第一个字符,因为它的存在已经用message.starstwith('§')=> await channel1.send(message.content[1:]) 进行了测试。 @Nhalrath 提出的替代方案是 await channel1.send(message.content.replace'('§', '', 1)。两者都将导致与您当前的代码示例相同的结果。
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 2018-09-08
  • 2014-04-12
  • 2017-01-27
  • 2021-10-26
相关资源
最近更新 更多