message.content中的世界列表

2024-10-01 17:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在尝试用Python为电报制作一个自定义机器人。 我期待着使用一个世界名单与信息内容相结合

world_list = ['home', 'house', 'maison']

@client.listen('on_message')
async def on_message(message):
     if message.content in world_list:
        await message.channel.send("i'm coming home")

如果使用此代码编写

i would like to go home

bot保持沉默,只有当消息是列表中的一个世界时,它才能工作,我如何修复它


Tags: clientmessagehomeworldasyncon世界机器人
3条回答

您当前正在检查整个邮件内容是否在列表中。但是,您正在尝试实现另一件事,即检查消息内容中是否有任何列表项 试着这样做

world_list = ['home', 'house', 'maison']

@client.listen('on_message')
async def on_message(message):
    for word in world_list:
        if word in message.content:
            await message.channel.send("i'm coming home")
>>> message = "I would like to go home"
>>> words = ["home", ...]
>>> message in words
False

您正在将整个消息内容与列表进行比较,如果列表是这样的["I would like to go home", ...],则结果将是True,但事实并非如此,因为您可以使用any函数

>>> message = "I would like to go home"
>>> words = ["home", ...]
>>> any(word in message for word in words)
True
>>> message = "Something else"
>>> any(word in message for word in words)
False

这和

>>> def words_in_message(content: str, words: list[str]) -> bool:
...     for word in words:
...         if word in content:
...             return True
...     return False
>>> 
>>> message = "I would like to go home"
>>> words = ["home", ...]
>>> words_in_message(message, words)
True
>>> message = "Something else"
>>> words_in_message(message, words)
False

您的代码应该如下所示

world_list = ['home', 'house', 'maison']

@client.listen('on_message')
async def on_message(message):
     if any(word in message.content for word in words):
        await message.channel.send("i'm coming home")

必须检查world_list中是否存在单个单词

any([word in world_list for word in message.split(' ')])

返回TrueFalse 所以像这样使用它

...    
if any([word in world_list for word in message.split(' ')]):
        await message.channel.send("i'm coming home")

相关问题 更多 >

    热门问题