我目前在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.
答案 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.
希望这会有所帮助,否则请提供有关问题和完整代码的更多信息。