Home > Software design >  discord bot is replying to every message that contains a word from a phrase in a list
discord bot is replying to every message that contains a word from a phrase in a list

Time:11-19

@client.event
async def on_message(message):
if message.author == client.user:
    return

List = open("D:/code/code/DIscord bot/myFile.txt").readlines()
List = str(List).replace("\\n", " ")
if message.content in List:
    msg = 'REAL!'
    await message.reply(msg)

im trying to get the bot to read all the sentences in a .txt file (one sentence per row) and then when that phrase is said in discord, itll respond with "REAL!" this all works but it seems to also respond to every message sent.

CodePudding user response:

You're asking this in the context of the discord API, but it could easily be reduced to a simple str unit test.

You're checking whether message.content in List. An equivalent check, which would yield greater diagnostic value, is

    if List.find(message.content) > -1:

Why? Because upon unwanted match, you could log the numeric .find() result and examine the portion of List which matched. This includes examining the match length -- sometimes we see the empty string or another very short match which appears in the larger haystack.

Log both strings, understand where the match is, and revise your logic. Do this within a discord handler, or more conveniently within a TestCase.


Pep-8 asks that the identifier be spelled lst.


Using the same identifier to denote first a vector and then a string is not improving the readability of the code. The Hare and the Hatter ask that we say what we mean, and mean what we say. The name was accurate upon initial assignment, but less so when re-assigned.

CodePudding user response:

You assign List to be a string, not an array. What you likely want is this:

List = open("D:/code/code/DIscord bot/myFile.txt").readlines()
List = str(List).split("\\n")

This allows your in statement to check for entire sentences instead of individual words. Note, you may want to convert all the text to lowercase or do something of that sort.

CodePudding user response:

Change this line into

List = str(List).replace("\\n", " ")

This

List = list(map(lambda item: item.strip(), List))

This will remove \n from all the strings in the collection, and maintain the list datatype

  • Related