Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

python - World list in message.content

Hello i'm trying to make a custom bot for telegram in Python. i'm looking to use a world list combined with in message content.

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")

with this code if a use write

i would like to go home

bot remain silent, it work only if the message is a single world of the list, how i can fix it?

question from:https://stackoverflow.com/questions/65902684/world-list-in-message-content

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> message = "I would like to go home"
>>> words = ["home", ...]
>>> message in words
False

You're comparing the WHOLE message content to the list, if the list was something like this ["I would like to go home", ...] the result would be True, but it's not, for that you can use the any function

>>> 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

It's the same as

>>> 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

Your code should look like this

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...