你好,我一直在研究聊天机器人。一切正常。我设法通过应用镜头或类型来避免一些逻辑冲突。
但是,我认为如果我这样做会更容易:
for event in bot.listen.fucntion()
count = 0
greetings = [hi, hello]
id = event.user_id
if msg in greetings:
send_message(user_id, f'Hello User {user_id}. Type "search" to start searching, or type "count" to set number of profiles.'
elif msg == "count"
count = 1
elif count == 1:
try:
if int(msg) in range(1, 1001):
profile_count == int(msg) or 100
send_message(user_id, f'Profiles number is set to {msg}'
else:
send_message(user_id, 'Incorrect number. Please use numbers from 1 to 1000'
except:
continue
elif msg == "search"
try:
for user in get_users(conn, user_id=id)[:profile_count]
send_message(user_id, f'This is {user[0]}. They do {user[2]}.'
except:
send_message(user_id, 'An unexpected error occurred. Try later'
看起来不错,除了计数始终为 0。如果我删除
count = 0
,它会起作用,但是,如果用户不输入“计数”Python 错误name count is not defined
。有没有一种简单的方法可以强制覆盖计数,或者我应该对代码使用不同的结构?每当我尝试删除变量时,机器人都会陷入尝试循环并拒绝识别“搜索”消息。在我的实际机器人中,我还必须添加组、兴趣和一些可能包含整数的更多选项。也很想知道如何在任何消息上强制第一响应,而不是问候列表。
有趣的是,如果我在 bot 事件中的“for”循环中使用函数,它会获取 user_id 或 elif 变量中的其他设置(f.e. elif msg == 'groups' if len(int(msg)) == 9, group_id = = int(msg)), search_users(conn, group_id=None/group_id).