首页 > 解决方案 > 为什么 isalpha() 不能清理用户输入?

问题描述

我在这里遇到的问题是该isalpha()功能没有做它应该做的事情,用户能够发送包含非字母字符的消息。我不确定为什么会发生这种情况。在假设我的代码中存在逻辑错误之前,我假设这是某种托管问题(看起来不是),但从逻辑上讲,这对我来说可能是错误的?我还假设它与函数不是异步的有关,我不知道我可能正在使用那个。

import discord
from discord.ext import commands
import re


class Shiritori(commands.Cog):
    """ Start a new word from the last letter of the one before. """

    def __init__(self, client):
        self.client = client
        self.repeats = re.compile(r'(.)\1{2,}')  # Matches spam like 'eeeeeee'
        self.shiritori_channel = 578788555120312330  # Official

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if message.channel.id == self.shiritori_channel:
                previous_message = (await message.channel.history(limit=2).flatten())[1].content

                repeats_mo = self.repeats.search(message.content)
                if not repeats_mo and message.content.isalpha():
                    if previous_message[-1].lower() != message.content[0].lower():
                        await message.author.send(
                            f'Your message must start with the last letter of the latest message!')
                        await message.delete()
                else:
                    await message.author.send("You can't do that here!")
                    await message.delete()
        except discord.Forbidden:
            await message.delete()

标签: python-3.xdiscord.py

解决方案


我猜您期望任何非 ascii 英文字符都不是 alpha。

根据文档

str.isalpha() 如果字符串中的所有字符都是字母并且至少有一个字符,则返回 True,否则返回 False。字母字符是在Unicode 字符数据库中定义为“字母”的字符,即一般类别属性为“Lm”、“Lt”、“Lu”、“Ll”或“Lo”之一的字符。请注意,这与 Unicode 标准中定义的“字母”属性不同。

所以例如à(french a) orлюбовь也被考虑alpha

'à'.isalpha()
True
'любовь'.isalpha()
True

如果你想要英文字母,请使用isascii()

'à'.isascii()
False

推荐阅读