Discord bot is sending multiple messages

时间:2019-04-23 15:11:07

标签: python youtube-api youtube-data-api discord.py discord.py-rewrite

When I run the code and some event occures bot is sending message from third elif statement all the time. This message should be the link to a youtube video 'cause i made a function that reads the message that has been sent by someone, search videos and return video link

I moved code that searches the video to a function getVid(), I moved it to another file called search.py, I tried getting the video link in many other ways but nothing helped

This is main.py snippet that causes the problem (containing discord bot):

@client.event
async def on_message(message):
    id = client.get_guild(###)

    if message.content == "!hello":
        await message.channel.send("hi")
    elif message.content == "!members":
        await message.channel.send(f"""All members: {id.member_count}""")
    elif message.content != "!hello" or "!members":
        res = search.getVid(message.content)
        await message.channel.send(res)

And here youtube api connection search.py:

def getVid(txt):
    req = youtube.search().list(q=txt, part="snippet", type="video", maxResults=3)
    res = req.execute()
    count = 0
    links = []
    for item in res['items']:
        links.append(item['id']['videoId'])
        count = count+1
        if count==3:
            break
    print(links)
    vid = links[0]
    print(links[0])
    link = f"http://youtube.com/watch?v={vid}"
    return link

I know this looks disguisting but I really tried everything to get this working.

Third elif statement runs every time even when there should be only one statement executed but when I delete this function everything is working correctly. I hope i wrote this clearly enough, thanks for any help

1 个答案:

答案 0 :(得分:0)

The line

elif message.content != "!hello" or "!members":

is checking that either message.content != "!hello", or the value "!members" is truthy. So it's always going to return true. You'll want to do this instead:

elif message.content != "!hello" or message.content != "!members":

or even:

message.content not in ["!hello", "!members"]