首页 > 解决方案 > 如何在我的 callbackQuery 函数中使用 `link` 变量?

问题描述

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

我该怎么做?

脚步:

1 - 请求链接

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

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 请求链接,获取链接,并为每种格式生成一个按钮...

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

我这样做了,但它不能正常工作......我需要link在我的函数中使用该变量,但我不知道如何......我试图从streams函数中返回它,但我无法导致我需要返回我也使用函数(ConvertationHandler)

无论如何,这是我到现在为止的东西......

第 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)

这是我的转换处理程序:

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)

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

标签: pythonpython-3.xtelegram-botpython-telegram-botpytube

解决方案


IISC 你的问题是你想访问在对话状态/回调中link定义的变量。streamsCLICK_FORMATclick_format

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

但是,PTB 附带了一个内置机制:context.user_data它是一个字典,您可以在其中存储与该用户相关的信息。因此,您可以将链接存储为 egcontext.user_data['link'] = link并将其访问click_formatlink = context.user_data['link'].

请参阅wiki 页面以获取有关示例的说明,user_data另请参阅conversationbot.py示例,其中此功能与ConversationHandler.


推荐阅读