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

时间:2017-01-22 19:56:46

标签: python bots twitch

我目前在python中创建了一个抽搐机器人。 如果用户输入!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.

2 个答案:

答案 0 :(得分:0)

您的问题是,在您已经发送"现在在聊天记录您的时间后,您不会检查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

答案 1 :(得分:0)

#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.

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