如果用户在lis中,则使用同一命令两次,但得到不同的响应

2024-03-29 11:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python为twitch创建一个bot。 如果一个用户键入!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")

当我输入“!开始“在聊天是:Tracking time.~新行Already tracking time.


Tags: 用户inmessage键入iftimepeoplestart
2条回答
#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.

希望这有帮助,否则请提供一些关于问题和完整代码的更多信息。你知道吗

您的问题是,在发送了“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开发了bot(代码实践很差),我猜这个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

相关问题 更多 >