skip to Main 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?

4

Answers


  1. >>> 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")
    
    Login or Signup to reply.
  2. You must check single words for existence in world_list

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

    returns True or False
    so use it like this

    ...    
    if any([word in world_list for word in message.split(' ')]):
            await message.channel.send("i'm coming home")
    
    Login or Signup to reply.
  3. you are currently checking whether the whole message content is on the list. But you are trying to achieve another thing checking whether any of the list items is in the message content.
    try doing it like this,

    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")
    
    Login or Signup to reply.
  4. Just loop through the list;

    world_list = ['home', 'house', 'maison']
    
    for word in world_list:
        if word in message.content:
            await message.channel.send("i'm coming home")
            break
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search