#!/usr/bin/env python3 # The MIT License (MIT) # Copyright (c) 2020 Dineshkarthik Raveendran # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE # OR OTHER DEALINGS IN THE SOFTWARE. """Random Wikipedia article Telegram bot.""" from telebot import TeleBot, types import requests bot = TeleBot("") def get_article(): resp = requests.get("https://en.wikipedia.org/wiki/Special:Random") article_name = resp.url.split("/")[-1] url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{article_name}" return requests.get(url).json() @bot.message_handler(commands=["random"]) def send_random_article(message): """/random.""" article = get_article() msg_content = "{0} \n{2}".format( article["title"], article.get("thumbnail", {}).get("source", ""), article["extract"], ) markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, row_width=1) markup.add("Read-Wiki", "Skip") msg = bot.send_message( message.chat.id, msg_content, reply_markup=markup, parse_mode="html", ) bot.register_next_step_handler(msg, send_article_url, article["content_urls"]) def send_article_url(message, article_urls): if message.text == "Read-Wiki": bot.send_message(message.chat.id, article_urls["desktop"]["page"]) @bot.message_handler(commands=["start", "help"]) def send_instructions(message): """/start, /help""" msg_content = ( "*Available commands:*\n\n" "/random - get summary of random Wikipedia article" ) bot.send_message( message.chat.id, msg_content, parse_mode="markdown", ) bot.polling(none_stop=True)