两次使用相同的命令但如果用户在列表中则得到不同的响应

Using the same command twice but getting a differrent response if the user is in the list

我目前正在 python 中为 twitch 创建一个机器人。 如果用户键入 !start 我想要输出 Tracking time,如果同一用户再次键入 start 我想要输出 Already tracking time。 我试过这个:

people = []
if "!start" in message:
    sendMessage(s, "Now recording your time in chat.")
    print(user.title() + " is now tracking time.")
    people.append(user)
    print(", ".join(people))

    if user in people and "start" in message:
        sendMessage(s, "Worked")

当我在聊天中输入“!start”时得到的当前输出是:Tracking time. ~换行~ Already tracking time.

您的问题是您在发送 "Now recording your time in chat" 之后直到案件结束才检查 user 是否已被跟踪。您需要更早地执行该检查。这些方面的内容可能对您有用:

people = []
if "!start" in message:
    if user in people:
        sendMessage(s, "Already tracking time")
    else:
        sendMessage(s, "Now recording your time in chat.")
        print(user.title() + " is now tracking time.")
        people.append(user)
        print(", ".join(people))

不久前在 Python 开发了机器人(编码实践不佳),我猜测这个 if 块是大型 handle_message 函数中的许多块之一。如果是这种情况,您很可能希望将 people = [] 移出该函数,这样它就不会在收到的每条消息上都重新初始化。


使用 sendMessage 的模拟实现来演示此解决方案:

def sendMessage(message):
    print('Bot responds: {}'.format(message))

people = []

def handle_message(user, message):
    print('{} says: {}'.format(user, message))
    if "!start" in message:
        if user in people:
            sendMessage("Already tracking time")
        else:
            sendMessage("Now recording your time in chat.")
            print(user.title() + " is now tracking time.")
            people.append(user)
            print(", ".join(people))

if __name__ == '__main__':
    for _ in range(2):
        handle_message("John", "!start")

输出

John says: !start
Bot responds: Now recording your time in chat.
John is now tracking time.
John
John says: !start
Bot responds: Already tracking time
#people = []
people = {}
if "!start" in message:
    sendMessage(s, "Now recording your time in chat.")
    print(user.title() + " is now tracking time.")
    people[user] = ['Already Tracking Time']
    print(", ".join(people))

    if user in people and "start" in message:
        sendMessage(people[user][0], "Worked") # In case you want to send a different message for different command then you just have to append to the user in this dictionary and reference the correct subscript in the list.

希望这对您有所帮助,否则请提供有关该问题的更多信息和完整代码。