如何在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 ... nn ( 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函数返回它,但我无法返回,因为我也需要返回函数。我使用(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)

这是我的对话手柄:

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/的回调click_format中访问streams中定义的变量link

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

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

有关user_data的示例说明,请参阅wiki页面,也可参阅conversationbot.py示例,其中此功能与ConversationHandler一起使用。

最新更新