Enhance Python Knowledge Create a Python Quiz Telegram Bot:
Follow the Instructions from the Above Video then go for the Code Input:
import nest_asyncio
import asyncio
from telegram import Update,InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import Application,CommandHandler,CallbackQueryHandler
telegram_token=open('token.txt','r').read().strip()
nest_asyncio.apply()
questions =[{"question": "What is the output of: print('Hello, ' + 'World!')?",
"options": ["Hello, World!", "HelloWorld!", "Hello, + World!", "Error"],
"correct_option": 0},
{"question": "Which of the following can be used to iterate over a list in Python?",
"options": ["for", "while", "map", "All of the above"],
"correct_option": 3},
{"question": "What does the len() function do in Python?",
"options": ["Returns the number of elements in a list", "Returns the length of a string",
"Returns the number of key-value pairs in a dictionary", "All of the above"],
"correct_option": 3},
{"question": "Which of the following is not a keyword in Python?",
"options": ["class", "assert", "none", "pass"],
"correct_option": 2},
{"question": "How do you create a set in Python?",
"options": ["[]", "{}", "()", "set()"],
"correct_option": 2},
{"question": "What does NIFTY 50 represent?",
"options": ["Top 50 stocks in the BSE", "Top 50 stocks in the NSE", "Top 50 IT companies in India", "The 50 oldest companies in India"],
"correct_option": 1},
{"question": "What is the full form of IPO?",
"options": ["Initial Public Offering", "International Portfolio Offering", "Indian Public Organization", "Initial Purchase Offer"],
"correct_option": 0},
{"question": "Which regulatory body governs the securities market in India?",
"options": ["SEBI", "RBI", "IRDAI", "PFRDA"],
"correct_option": 0},
{"question": "Which of the following is a stock market index in India?",
"options": ["Dow Jones", "FTSE 100", "Sensex", "Nikkei 225"],
"correct_option": 2}
]
async def start(update:Update,context) -> None:
context.user_data['current_question']=0
context.user_data['correct_answers']=0
context.user_data['wrong_answers']=0
await ask_question(update,context)
async def ask_question(update:Update,context) -> None:
current_question_index=context.user_data['current_question']
question_data=questions[current_question_index]
keyboard=[
[InlineKeyboardButton(option,callback_data=str(index)) for index,option in enumerate(question_data['options']) ]]
reply_markup=InlineKeyboardMarkup(keyboard)
if update.message:
await update.message.reply_text(question_data['question'],reply_markup=reply_markup)
else:
query=update.callback_query
await query.edit_message_text(question_data['question'],reply_markup=reply_markup)
async def button(update:Update,context) -> None:
query=update.callback_query
current_question_index=context.user_data['current_question']
question_data=questions[current_question_index]
selected_option=int(query.data)
correct_option=question_data['correct_option']
if selected_option==correct_option:
context.user_data['correct_answers']+=1
await query.answer('Correct!')
else:
context.user_data['wrong_answers']+=1
await query.answer('Wrong!')
current_question_index += 1
if current_question_index < len(questions):
context.user_data['current_question']= current_question_index
await ask_question(update,context)
else:
correct= context.user_data['correct_answers']
wrong=context.user_data['wrong_answers']
await query.edit_message_text(f"Quiz Finished! Played Well: CA:{correct}, WA:{wrong}")
async def main():
application=Application.builder().token(telegram_token).build()
application.add_handler(CommandHandler('start',start))
application.add_handler(CallbackQueryHandler(button))
await application.run_polling()
if __name__=='__main__':
asyncio.run(main())
import nest_asyncio
import asyncio
from telegram import Update,InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import Application,CommandHandler,CallbackQueryHandler
telegram_token=open('token.txt','r').read().strip()
nest_asyncio.apply()
questions =[{"question": "What is the output of: print('Hello, ' + 'World!')?",
"options": ["Hello, World!", "HelloWorld!", "Hello, + World!", "Error"],
"correct_option": 0},
{"question": "Which of the following can be used to iterate over a list in Python?",
"options": ["for", "while", "map", "All of the above"],
"correct_option": 3},
{"question": "What does the len() function do in Python?",
"options": ["Returns the number of elements in a list", "Returns the length of a string",
"Returns the number of key-value pairs in a dictionary", "All of the above"],
"correct_option": 3},
{"question": "Which of the following is not a keyword in Python?",
"options": ["class", "assert", "none", "pass"],
"correct_option": 2},
{"question": "How do you create a set in Python?",
"options": ["[]", "{}", "()", "set()"],
"correct_option": 2},
{"question": "What does NIFTY 50 represent?",
"options": ["Top 50 stocks in the BSE", "Top 50 stocks in the NSE", "Top 50 IT companies in India", "The 50 oldest companies in India"],
"correct_option": 1},
{"question": "What is the full form of IPO?",
"options": ["Initial Public Offering", "International Portfolio Offering", "Indian Public Organization", "Initial Purchase Offer"],
"correct_option": 0},
{"question": "Which regulatory body governs the securities market in India?",
"options": ["SEBI", "RBI", "IRDAI", "PFRDA"],
"correct_option": 0},
{"question": "Which of the following is a stock market index in India?",
"options": ["Dow Jones", "FTSE 100", "Sensex", "Nikkei 225"],
"correct_option": 2}
]
async def start(update:Update,context) -> None:
context.user_data['current_question']=0
context.user_data['correct_answers']=0
context.user_data['wrong_answers']=0
await ask_question(update,context)
async def ask_question(update:Update,context) -> None:
current_question_index=context.user_data['current_question']
question_data=questions[current_question_index]
keyboard=[
[InlineKeyboardButton(option,callback_data=str(index)) for index,option in enumerate(question_data['options']) ]]
reply_markup=InlineKeyboardMarkup(keyboard)
if update.message:
await update.message.reply_text(question_data['question'],reply_markup=reply_markup)
else:
query=update.callback_query
await query.edit_message_text(question_data['question'],reply_markup=reply_markup)
async def button(update:Update,context) -> None:
query=update.callback_query
current_question_index=context.user_data['current_question']
question_data=questions[current_question_index]
selected_option=int(query.data)
correct_option=question_data['correct_option']
if selected_option==correct_option:
context.user_data['correct_answers']+=1
await query.answer('Correct!')
else:
context.user_data['wrong_answers']+=1
await query.answer('Wrong!')
current_question_index += 1
if current_question_index < len(questions):
context.user_data['current_question']= current_question_index
await ask_question(update,context)
else:
correct= context.user_data['correct_answers']
wrong=context.user_data['wrong_answers']
await query.edit_message_text(f"Quiz Finished! Played Well: CA:{correct}, WA:{wrong}")
async def main():
application=Application.builder().token(telegram_token).build()
application.add_handler(CommandHandler('start',start))
application.add_handler(CallbackQueryHandler(button))
await application.run_polling()
if __name__=='__main__':
asyncio.run(main())
How to Create a Telegram Bot in Python Updated 2024 Version:
Follow the Instructions from the Above Video then go for the Code Input:
import requests
token=open('token.txt','r').read().strip()
base_url=f'https://api.telegram.org/bot{token}'
chat_id=requests.get(f'{base_url}/getUpdates').json()['result'][0]['message']['chat']['id']
text='learning video visit youtube:https://youtube.com/profitadda/videos'
send_alert=requests.get(f'{base_url}/sendMessage?chat_id={chat_id}&text={text}').json()['result']['text']
print(send_alert)