如何在我的 callbackQuery 函数中使用 `link` 变量?

How can I use the `link` variable in my callbackQuery function?

我想为每种格式生成按钮,然后下载所选格式的视频...

我该怎么做?

步数:

1 - 请求 link

2- 获取 link 并显示所有可用的流(为它们制作按钮)

3-下载指定分辨率的视频(这里需要一个回调查询处理器)

步骤 1

def ask_for_link(update,context):
    bot.send_message(chat_id=update.effective_chat.id ,text="Please Paste the video link here ... ")
    return STREAMS

步骤 2

def streams (update , context) :
    try:
        link=str(update.message.text)

        Video_Url = YouTube(link)
        Video= Video_Url.streams
        chooseRes = []
        for i in Video :
            chooseRes.append([str(i).split()[2][str(i).split()[2].index("=")+2:len(str(i).split()[2])-1] , str(i).split()[3][str(i).split()[3].index("=")+2:len(str(i).split()[3])-1]])
        print(chooseRes)

        # list of resolution menu's buttons
        res_menu_buttons_list = []

         # a loop which create a button for each of resolutions
        for each in chooseRes:
            res_menu_buttons_list.append(InlineKeyboardButton(f"{each[0]}  ❤️  {each[1]}", callback_data = each[1] ))
       # print(res_menu_buttons_list)

        #it'll show the buttons on the screen 
        replyMarkup=InlineKeyboardMarkup(build_res_menu(res_menu_buttons_list, n_cols=2 )) 
        #button's explanaions 
        update.message.reply_text("Choose an Option from the menu below ... ",reply_markup=replyMarkup)
        return CLICK_FORMAT

    except Exception as e:
        print(e)
        bot.send_message(chat_id=update.effective_chat.id , text = "Oooops !!! Something Went Wrong ... \n\n ( Make sure that you wrote the link correctly )")
        quit(update,context)


# make columns based on how we declared 
def build_res_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
    res_menu_buttons = [buttons[i:i + n_cols] for i in range(0 , len(buttons), n_cols)]
    if header_buttons:
        res_menu_buttons.insert(0, header_buttons)
    if footer_buttons:
        res_menu_buttons.append(footer_buttons)
    return res_menu_buttons

到目前为止一切顺利...Bot 请求 link,获取 link,并为每种格式生成一个按钮 ...

现在我们需要一个 CallBackQueryHandler 来下载所选格式的视频...

我这样做了,但它不能正常工作...我需要在我的函数中使用 link 变量,但我不知道如何...我尝试 return 它来自 streams 函数,但我不能因为我也需要 return 我使用的函数 (ConverstationHandler)

总之,这是我到现在为止的东西...

步骤 3

def click_format(update,context):
    query = update.callback_query
    """
       My problem is exactly HERE 
       as You see I tried to Use Downloader. link but it doesn't work ... 
       I receive this error : AttributeError: 'function' object has no attribute 'link'

    """
    Video = YouTube(Downloader.link).streams.filter(res=query.data).first().download()

        
    format_vid=re.sub(Video.mime_type[:Video.mime_type.index("/")+1],"",Video.mime_type)  
    bot.send_message(chat_id=update.effective_chat.id , text = f"{Video.title} has Downloaded successfully ... ")
    bot.send_video(chat_id=update.effective_chat.id ,video=open(f"{Video.title}.{format_vid}" , 'rb'), supports_streaming=True)
      
    try:
        os.remove(f"{Video.title}.{format_vid}")
        print("removed")
    except:
        print("Can't remove")
        quit(update,context)

这是我的 ConverstationHandler :

DOWNLOADER , CLICK_FORMAT = 0 ,1

YouTube_Downloader_converstation_handler=ConversationHandler(
    entry_points=[CommandHandler("YouTubeDownloader", ask_for_link)] , 
    states={
        STREAMS :[MessageHandler(Filters.text , callback=streams )],
        CLICK_FORMAT : [CallbackQueryHandler(click_format)]
          
        },
    fallbacks=[CommandHandler("quit" , quit)]) 

dispatcher.add_handler(YouTube_Downloader_converstation_handler)

谁能帮我完成第三步?我想以所选格式下载视频....如何在我的 click_format 函数中使用 link 变量????

IISC 你的问题是你想在回调 click_format.[=25 的对话状态 CLICK_FORMAT/ 中访问定义在 streams 中的变量 link =]

由于 click_format 中的 update 变量包含有关按钮点击的信息,而不是有关先前发送的消息的信息,因此您必须将 link 存储在一个变量中click_format可以访问。您可以天真地为此使用全局变量,但这有很多缺点。最值得注意的是,当多个用户尝试同时使用您的机器人时,这将无法正常工作。

但是,PTB 专门为此配备了一个内置机制:context.user_data 是一个字典,您可以在其中存储与该用户相关的信息。因此,您可以将 link 存储为例如context.user_data['link'] = link 并在 click_format 中作为 link = context.user_data['link'].

访问它

请参阅 wiki page for an explanation of user_data with example and also see conversationbot.py 示例,其中此功能与 ConversationHandler 结合使用。