名称错误:名称“更新”未定义电报机器人

问题描述 投票:0回答:1

尝试在replit创建一个机器人;

用于管理采访,可以:

  1. 第一次启动时,为群组中所有成员创建一个字典,以防止更改用户名的用户作弊,将字段设置为以前的采访,默认值为 0。下次启动时,参考该字典来统计民意调查的回复。连接到谷歌表格

  2. 开始时,询问访谈创建者以下选项:

投票文本、投票时间限制、发送个人资料的时间限制、之前最少采访次数。

  1. 创建民意调查,根据输入提供民意调查的文本和时间限制,并使用以下选项: 是的,不是,导师民意调查检查。

  2. 时间限制后,从“是”的回答中,随机选择一个之前采访次数等于或小于所提供的输入的回答者,与已创建的字典进行比较。如果没有响应者匹配,则随机选择。

  3. 标记所选用户在时限内发送“个人资料简介”,将个人资料发送给民意调查创建者,并在发送文件后向机器人回复“是”,一旦回复“是”,则在该用户之前的采访中添加 1 .

  4. 如果所选用户未能回答“是”,请返回步骤 4。如果第二个所选用户也失败,请写入:所选受访者未发送个人资料,采访被取消。

`

import logging
import random

try:
    from telegram.ext import Update, Updater, CommandHandler, CallbackContext , PollHandler 
except ImportError:
    import os
    os.system("pip install python-telegram-bot --upgrade")

import gspread
from oauth2client.service_account import ServiceAccountCredentials


# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

# Load Google Sheets credentials
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("*************.json", scope)
client = gspread.authorize(creds)

# Open the Google Sheet by title
sheet_title = "*****"
sheet = client.open(sheet_title).sheet1

# Dictionary to store members and their previous interviews count
members_dict = {}

# Load data from Google Sheet into members_dict at the beginning of your script
def load_from_sheet():
    global members_dict
    members_dict = {}
    data = sheet.get_all_records()
    for row in data:
        user_id = row["User ID"]
        prev_interviews = row["Previous Interviews"]
        members_dict[user_id] = prev_interviews

# Function to update the Google Sheet with the members_dict

def update_sheet():
    # Get existing data from the sheet
    existing_data = sheet.get_all_records()

    # Update data in the existing_data list
    for user_id, prev_interviews in members_dict.items():
        # Check if the user_id is already in the sheet
        user_row = next((row for row in existing_data if row["User ID"] == user_id), None)

        if user_row:
            # Update the existing row
            user_row["Previous Interviews"] = prev_interviews
        else:
            # Add a new row
            existing_data.append({"User ID": user_id, "Previous Interviews": prev_interviews})

    # Clear existing data in the sheet
    sheet.clear()

    # Write header
    header = ["User ID", "Previous Interviews"]
    sheet.append_row(header)

    # Write modified data
    for row in existing_data:
        sheet.append_row([row["User ID"], row["Previous Interviews"]])

# Callback function for handling the /start command
def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text("Welcome to the interview bot! Please provide the following options:\n"
                              "/setoptions <poll_text> <poll_time_limit> <profile_time_limit> <min_previous_interviews>")

# Callback function for handling the /setoptions command
def set_options(update: Update, context: CallbackContext) -> None:
    args = context.args
    if len(args) != 4:
        update.message.reply_text("Usage: /setoptions <poll_text> <poll_time_limit> <profile_time_limit> <min_previous_interviews>")
        return

    poll_text, poll_time_limit, profile_time_limit, min_previous_interviews = args
    context.user_data['poll_text'] = poll_text
    context.user_data['poll_time_limit'] = int(poll_time_limit) * 60  # Convert minutes to seconds
    context.user_data['profile_time_limit'] = int(profile_time_limit) * 60  # Convert minutes to seconds
    context.user_data['min_previous_interviews'] = int(min_previous_interviews)

    update.message.reply_text("Options set successfully!")

# Callback function for handling the /interview command
def interview(update: Update, context: CallbackContext) -> None:
    if 'poll_text' not in context.user_data:
        update.message.reply_text("Please set options using /setoptions command first.")
        return

    # Create a poll
    poll_message = update.message.reply_poll(
        context.user_data['poll_text'],
        options=["Yes", "No", "Mentor Poll Check"],
        type=PollHandler.ANSWER_OPTIONS,
        is_anonymous=False,
        allows_multiple_answers=False,
        open_period=context.user_data['poll_time_limit']
    )

    # Get the poll ID
    poll_id = poll_message.poll.id

    # Set a timer to check the poll results
    context.job_queue.run_once(check_poll_results, context.user_data['poll_time_limit'], context=poll_id)

    # Display time limit
    update.message.reply_text(f"Poll created with time limit: {context.user_data['poll_time_limit'] / 60} minutes.")

# Callback function to check poll results
def check_poll_results(context: CallbackContext) -> None:
    poll_id = context.job.context
    poll_results = context.bot.stop_poll(chat_id=context.job.context, message_id=poll_id)

    # Process poll results
    process_poll_results(context.bot, context.user_data, poll_results)

# Function to process poll results
def process_poll_results(bot, user_data, poll_results):
    yes_responses = poll_results['options'][0]['voter_count']

    if yes_responses == 0:
        update.message.reply_text("No one responded 'Yes' to the poll. The interview is cancelled.")
        return

    # Filter members with previous interviews less than or equal to the specified limit
    eligible_members = [user_id for user_id, prev_interviews in members_dict.items() if prev_interviews <= user_data['min_previous_interviews']]

    if not eligible_members:
        selected_user_id = random.choice(list(members_dict.keys()))
    else:
        selected_user_id = random.choice(eligible_members)

    selected_user = bot.get_chat_member(chat_id=context.chat_data['chat_id'], user_id=selected_user_id).user

    # Notify the selected user to send a profile
    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.")

    # Set a timer to check if the user replies 'yes' in time
    context.job_queue.run_once(check_profile_submission, user_data['profile_time_limit'], context=(selected_user_id, user_data))

# Callback function to check profile submission
def check_profile_submission(context: CallbackContext) -> None:
    selected_user_id, user_data = context.job.context

    if members_dict[selected_user_id] == 0:
        # Notify the poll creator about the selected user's failure to reply 'yes'
        context.bot.send_message(context.chat_data['chat_id'], f"Selected user @{selected_user_id} did not reply 'yes'.")

        # Retry the process with another user
        process_poll_results(context.bot, user_data, context.chat_data)
    else:
        # Notify the poll creator about the successful profile submission
        context.bot.send_message(context.chat_data['chat_id'], f"Profile received from @{selected_user_id}.")
        # Increment the previous interviews count for the selected user
        members_dict[selected_user_id] += 1

    # Update Google Sheet
        update_sheet()

# Callback function for handling the /stop command
def stop(update: Update, context: CallbackContext) -> None:
    update.message.reply_text("Bot is stopping...")
    context.job_queue.stop()
    context.bot.stop()

# Main function to start the bot
def main() -> None:
    # Set your Telegram Bot Token
    updater = Updater("**********")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Register command handlers
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("setoptions", set_options))
    dp.add_handler(CommandHandler("interview", interview))
    dp.add_handler(CommandHandler("stop", stop))  # Added /stop command handler

    # Start the Bot
    updater.start_polling()

    # Run the bot until you send a signal to stop it
    updater.idle()

if __name__ == '__main__':
    main()

出现错误,

File "/home/runner/CalmHeartyObject/main.py", line 73, in <module> def start(Update: Update, context: CallbackContext) -> None: NameError: name 'Update' is not defined 

尝试更改导入语句,但无法理解错误..

python telegram-bot python-telegram-bot
1个回答
0
投票

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

更改此:

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

对此:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.