-2

I'm coding this telegram bot for my clan. The bot should send a reply based on a few words in the text msg. Suppose I type a text in the group containing the words "Thalia" and "love" and I want the bot to respond. The following works.

elif "thalia" in text.lower():
    if "love" in text.lower():
        reply("I love u too babe <3." "\nBut I love my maker even more ;).")
    else:
        reply("Say my name!")

msg containing thalia and love

I coded it like this because when I use the "and" or "or" keywords the statement doesn't work and the bot goes crazy. In the above, if I code: elif "thalia" and "love"..... it doesn't work.

If there is another way to code this I would appreciate the tip!

Now I am trying the same technique on more words with "and" and "or" but it doesn't work. If I leave "and" and "or" out it works fine. But of course then I can't use the combinations of words I want with this particular response.

 elif "what" or "when" in text.lower():
    if "time" or "do" in text.lower():
        if "match" in text.lower():
            reply ("If you need assistence with matches, type or press /matches")

it triggered the command without the 3 words in one sentence

How can I rewrite this code in a more "professional" way and what do I need to change to get it to work? The bot responds only when the combination of the words are used like in the thalia love code. Instead of when "matches" is used.*

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
Kevin
  • 37
  • 10

1 Answers1

0

Python is much like natural language but the interpreter cannot fill in what human listeners can. 'a and b in c' must be written out as 'a in c and b in c'.

Before writing the if statements, you should lower case text once, not repeatedly. Then turn it into a set of words, after removing punctuation and symbols, to avoid repeated linear searches of the lower-cased string. Here is an incomplete example for ascii-only input.

d = str.maketrans('', '', '.,!')  # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())

Your 'matches' snippet can then be written as follows.

elif (("what" in text or "when" in text) and 
      ("time" in text or "do" in text) and
      "match" in text)
    reply ("If you need assistence with matches, type or press /matches")

You could also use regular expression matching to do the same thing, but logic statements like the above are probably easier to start with.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
  • Nice, this works even better I am grateful for ur help sir! I was wondering, how would the code change if i wanted to add "have" in the same line as "time" or "do". Cause im not sure u can use "or" for 3 things. This wouldn't work right?: `("time" in text or "do" in text or "have" in text ) `. So how would it work? – Kevin Mar 19 '16 at 15:52
  • `a or b or c` is fine. Easy to try: `>>> False or False or True` will echo `True`. – Terry Jan Reedy Mar 19 '16 at 20:25