python Name错误:name 'update' is not defined

3b6akqbq  于 2024-01-05  发布在  Python
关注(0)|答案(2)|浏览(209)

试图在replit创建一个机器人;
管理面试,可以:
1.在第一次开始,创建一个字典中的所有成员在组中,以防止作弊的用户谁改变他们的用户名,设置一个字段为以前的采访与默认值0.在下一次开始,参考此字典来统计民意调查的React.连接到谷歌表
1.开始时,询问面试创建者以下选项:
投票文本,投票时限,发送个人资料的时限,最低以前的采访。
1.根据输入创建投票,提供投票的文本和时间限制,具有以下选项:是、否、导师投票检查。
1.在时间限制后,从“是”响应中,选择一个随机响应者,该响应者的先前访谈次数等于或小于所提供的输入,从已创建的字典中进行比较。如果没有响应者匹配,则随机选择。
1.标记选定的用户在发送配置文件的时间限制内发送“配置文件简报”,发送文件后,向投票创建者和回答是机器人,一旦回答是,该用户以前的采访加1。
1.如果所选用户未回复“是”,请返回步骤4。如果第二个所选用户也未回复,请填写:所选受访者未发送个人资料,面试取消。
`

  1. import logging
  2. import random
  3. try:
  4. from telegram.ext import Update, Updater, CommandHandler, CallbackContext , PollHandler
  5. except ImportError:
  6. import os
  7. os.system("pip install python-telegram-bot --upgrade")
  8. import gspread
  9. from oauth2client.service_account import ServiceAccountCredentials
  10. # Enable logging
  11. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  12. logger = logging.getLogger(__name__)
  13. # Load Google Sheets credentials
  14. scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
  15. creds = ServiceAccountCredentials.from_json_keyfile_name("*************.json", scope)
  16. client = gspread.authorize(creds)
  17. # Open the Google Sheet by title
  18. sheet_title = "*****"
  19. sheet = client.open(sheet_title).sheet1
  20. # Dictionary to store members and their previous interviews count
  21. members_dict = {}
  22. # Load data from Google Sheet into members_dict at the beginning of your script
  23. def load_from_sheet():
  24. global members_dict
  25. members_dict = {}
  26. data = sheet.get_all_records()
  27. for row in data:
  28. user_id = row["User ID"]
  29. prev_interviews = row["Previous Interviews"]
  30. members_dict[user_id] = prev_interviews
  31. # Function to update the Google Sheet with the members_dict
  32. def update_sheet():
  33. # Get existing data from the sheet
  34. existing_data = sheet.get_all_records()
  35. # Update data in the existing_data list
  36. for user_id, prev_interviews in members_dict.items():
  37. # Check if the user_id is already in the sheet
  38. user_row = next((row for row in existing_data if row["User ID"] == user_id), None)
  39. if user_row:
  40. # Update the existing row
  41. user_row["Previous Interviews"] = prev_interviews
  42. else:
  43. # Add a new row
  44. existing_data.append({"User ID": user_id, "Previous Interviews": prev_interviews})
  45. # Clear existing data in the sheet
  46. sheet.clear()
  47. # Write header
  48. header = ["User ID", "Previous Interviews"]
  49. sheet.append_row(header)
  50. # Write modified data
  51. for row in existing_data:
  52. sheet.append_row([row["User ID"], row["Previous Interviews"]])
  53. # Callback function for handling the /start command
  54. def start(update: Update, context: CallbackContext) -> None:
  55. update.message.reply_text("Welcome to the interview bot! Please provide the following options:\n"
  56. "/setoptions <poll_text> <poll_time_limit> <profile_time_limit> <min_previous_interviews>")
  57. # Callback function for handling the /setoptions command
  58. def set_options(update: Update, context: CallbackContext) -> None:
  59. args = context.args
  60. if len(args) != 4:
  61. update.message.reply_text("Usage: /setoptions <poll_text> <poll_time_limit> <profile_time_limit> <min_previous_interviews>")
  62. return
  63. poll_text, poll_time_limit, profile_time_limit, min_previous_interviews = args
  64. context.user_data['poll_text'] = poll_text
  65. context.user_data['poll_time_limit'] = int(poll_time_limit) * 60 # Convert minutes to seconds
  66. context.user_data['profile_time_limit'] = int(profile_time_limit) * 60 # Convert minutes to seconds
  67. context.user_data['min_previous_interviews'] = int(min_previous_interviews)
  68. update.message.reply_text("Options set successfully!")
  69. # Callback function for handling the /interview command
  70. def interview(update: Update, context: CallbackContext) -> None:
  71. if 'poll_text' not in context.user_data:
  72. update.message.reply_text("Please set options using /setoptions command first.")
  73. return
  74. # Create a poll
  75. poll_message = update.message.reply_poll(
  76. context.user_data['poll_text'],
  77. options=["Yes", "No", "Mentor Poll Check"],
  78. type=PollHandler.ANSWER_OPTIONS,
  79. is_anonymous=False,
  80. allows_multiple_answers=False,
  81. open_period=context.user_data['poll_time_limit']
  82. )
  83. # Get the poll ID
  84. poll_id = poll_message.poll.id
  85. # Set a timer to check the poll results
  86. context.job_queue.run_once(check_poll_results, context.user_data['poll_time_limit'], context=poll_id)
  87. # Display time limit
  88. update.message.reply_text(f"Poll created with time limit: {context.user_data['poll_time_limit'] / 60} minutes.")
  89. # Callback function to check poll results
  90. def check_poll_results(context: CallbackContext) -> None:
  91. poll_id = context.job.context
  92. poll_results = context.bot.stop_poll(chat_id=context.job.context, message_id=poll_id)
  93. # Process poll results
  94. process_poll_results(context.bot, context.user_data, poll_results)
  95. # Function to process poll results
  96. def process_poll_results(bot, user_data, poll_results):
  97. yes_responses = poll_results['options'][0]['voter_count']
  98. if yes_responses == 0:
  99. update.message.reply_text("No one responded 'Yes' to the poll. The interview is cancelled.")
  100. return
  101. # Filter members with previous interviews less than or equal to the specified limit
  102. eligible_members = [user_id for user_id, prev_interviews in members_dict.items() if prev_interviews <= user_data['min_previous_interviews']]
  103. if not eligible_members:
  104. selected_user_id = random.choice(list(members_dict.keys()))
  105. else:
  106. selected_user_id = random.choice(eligible_members)
  107. selected_user = bot.get_chat_member(chat_id=context.chat_data['chat_id'], user_id=selected_user_id).user
  108. # Notify the selected user to send a profile
  109. bot.send_message(selected_user_id, f"You've been selected for an interview! Please send your profile brief within {user_data['profile_time_limit'] / 60} minutes. Reply with 'yes' once done.")
  110. # Set a timer to check if the user replies 'yes' in time
  111. context.job_queue.run_once(check_profile_submission, user_data['profile_time_limit'], context=(selected_user_id, user_data))
  112. # Callback function to check profile submission
  113. def check_profile_submission(context: CallbackContext) -> None:
  114. selected_user_id, user_data = context.job.context
  115. if members_dict[selected_user_id] == 0:
  116. # Notify the poll creator about the selected user's failure to reply 'yes'
  117. context.bot.send_message(context.chat_data['chat_id'], f"Selected user @{selected_user_id} did not reply 'yes'.")
  118. # Retry the process with another user
  119. process_poll_results(context.bot, user_data, context.chat_data)
  120. else:
  121. # Notify the poll creator about the successful profile submission
  122. context.bot.send_message(context.chat_data['chat_id'], f"Profile received from @{selected_user_id}.")
  123. # Increment the previous interviews count for the selected user
  124. members_dict[selected_user_id] += 1
  125. # Update Google Sheet
  126. update_sheet()
  127. # Callback function for handling the /stop command
  128. def stop(update: Update, context: CallbackContext) -> None:
  129. update.message.reply_text("Bot is stopping...")
  130. context.job_queue.stop()
  131. context.bot.stop()
  132. # Main function to start the bot
  133. def main() -> None:
  134. # Set your Telegram Bot Token
  135. updater = Updater("**********")
  136. # Get the dispatcher to register handlers
  137. dp = updater.dispatcher
  138. # Register command handlers
  139. dp.add_handler(CommandHandler("start", start))
  140. dp.add_handler(CommandHandler("setoptions", set_options))
  141. dp.add_handler(CommandHandler("interview", interview))
  142. dp.add_handler(CommandHandler("stop", stop)) # Added /stop command handler
  143. # Start the Bot
  144. updater.start_polling()
  145. # Run the bot until you send a signal to stop it
  146. updater.idle()
  147. if __name__ == '__main__':
  148. main()

字符串
获取错误,
第一个月
//之前尝试更改导入语句时出现错误,但无法理解错误。

rjjhvcjd

rjjhvcjd1#

在start函数中有一个名为Update的参数,这与telegram.ext模块中的Update类冲突。
更改此:

  1. def start(Update: Update, context: CallbackContext) -> None:

字符串
对此:

  1. def start(update: Update, context: CallbackContext) -> None:


您需要更新函数定义中的参数名称以及函数中的任何引用。对于遇到类似问题的其他函数定义重复此操作。

yc0p9oo0

yc0p9oo02#

看看你的街区:

  1. try:
  2. from telegram.ext import Update, Updater, CommandHandler, CallbackContext , PollHandler
  3. except ImportError:
  4. import os
  5. os.system("pip install python-telegram-bot --upgrade")
  6. # Update and the others are not defined when this block gets executed

字符串
在ImportError的情况下,这些变量将不会被定义为Update, Updater, CommandHandler, CallbackContext , PollHandler
看起来这是发生了,一些ImportError发生了,但你没有充分处理它,留下变量未定义。
在我看来,你根本不应该尝试处理ImportError,因为你需要Updater类。否则,你可以按照Michael Butscher的评论,不计算类型提示。
此外,从脚本内部安装软件包是不好的做法。您可以在except块的末尾添加from telegram.ext import Update, Updater, CommandHandler, CallbackContext , PollHandler以尝试第二次导入。
TL;DR:提供一个带有适当软件包版本的需求文件,并假设所有内容都已提供,不要尝试动态安装。

相关问题