Added type hints and doc strings

This commit is contained in:
Gourav Kumar 2022-01-09 09:33:12 +05:30
parent 9040001b59
commit 95a7a45c04

View File

@ -35,20 +35,25 @@ def connect_db():
return pgcon return pgcon
def start(update, context): def start(
update: telegram.update.Update,
context: telegram.ext.callbackcontext.CallbackContext
) -> None:
""" Handles the start command to the bot. Responds with help content """
start_text = "Welcome to Random Word Bot. To fetch a word, just send /word" start_text = "Welcome to Random Word Bot. To fetch a word, just send /word"
context.bot.send_message(chat_id=update.effective_chat.id, text=start_text) context.bot.send_message(chat_id=update.effective_chat.id, text=start_text)
def slugify(message: str) -> str: def slugify(message: str) -> str:
""" This function adds relevant escape characters as per Telegram's markdown parsing rules """ """ Adds relevant escape characters as per Telegram's markdown parsing rules """
message = message.replace(".", "\\.").replace("*", "\\*").replace("(", "\\(").replace(")", "\\)").replace("-", "\\-") message = message.replace(".", "\\.").replace("*", "\\*").replace("(", "\\(").replace(")", "\\)").replace("-", "\\-")
return message return message
def scrape_def(word: str) -> dict: def scrape_def(word: str) -> dict:
""" This function scrapes the definition of a word from lexico.com""" """ Scrapes the definition and audio file link of a word from lexico.com"""
ox_url = f'https://www.lexico.com/definition/{word}?locale=en' ox_url = f'https://www.lexico.com/definition/{word}?locale=en'
def_page = requests.get(ox_url) def_page = requests.get(ox_url)
@ -57,9 +62,8 @@ def scrape_def(word: str) -> dict:
print(f'Word not found: {selected_word}') print(f'Word not found: {selected_word}')
return None return None
def_soup = BeautifulSoup(def_page.content, 'html.parser')
my_dict = {} my_dict = {}
def_soup = BeautifulSoup(def_page.content, 'html.parser')
word = def_soup.find_all("span", {"class": "hw"}) word = def_soup.find_all("span", {"class": "hw"})
my_dict['word'] = slugify(word[0].text.capitalize()) my_dict['word'] = slugify(word[0].text.capitalize())
@ -67,7 +71,6 @@ def scrape_def(word: str) -> dict:
my_dict['type'] = u'\u2022 ' + grammatical_type[0].text.capitalize() my_dict['type'] = u'\u2022 ' + grammatical_type[0].text.capitalize()
definition = def_soup.find_all("span", {"class": "ind"}) definition = def_soup.find_all("span", {"class": "ind"})
audio = def_soup.find_all("audio") audio = def_soup.find_all("audio")
my_dict['audio'] = audio[0]['src'].replace('https://lex-audio.useremarkable.com/mp3/', '') my_dict['audio'] = audio[0]['src'].replace('https://lex-audio.useremarkable.com/mp3/', '')
my_dict['definition'] = [] my_dict['definition'] = []
@ -77,7 +80,17 @@ def scrape_def(word: str) -> dict:
return my_dict return my_dict
def word_def(update, context): def word_def(
update: telegram.update.Update,
context: telegram.ext.callbackcontext.CallbackContext
) -> None:
""" Responds to the /word command on the bot
Fetches the definition from Lexico.com
Constructs the message and callback keyboard
Sends the message
"""
pgcon = connect_db() pgcon = connect_db()
if pgcon is None: if pgcon is None:
print("Db connection failed") print("Db connection failed")
@ -114,7 +127,9 @@ def word_def(update, context):
print(type(msg_response)) print(type(msg_response))
def get_synonyms(word): def get_synonyms(word: str) -> str:
""" Fetches the synonyms of a word from lexico.com"""
syn_url = 'https://www.lexico.com/synonyms/{}?locale=en' syn_url = 'https://www.lexico.com/synonyms/{}?locale=en'
response = requests.get(syn_url.format(word.lower())) response = requests.get(syn_url.format(word.lower()))
soup = BeautifulSoup(response.content, 'html.parser') soup = BeautifulSoup(response.content, 'html.parser')
@ -123,7 +138,11 @@ def get_synonyms(word):
return (''.join(synonym_list)) return (''.join(synonym_list))
def button(update, context): def button(
update: telegram.update.Update,
context: telegram.ext.callbackcontext.CallbackContext
) -> None:
""" Responds to callback buttons in the original message. """ Responds to callback buttons in the original message.
If the callback type is audio, then responds with already available audio URL If the callback type is audio, then responds with already available audio URL
@ -147,7 +166,9 @@ def button(update, context):
context.bot.send_message(update.effective_chat.id, text=synonyms, reply_to_message_id=query.message.message_id, parse_mode=ParseMode.MARKDOWN_V2) context.bot.send_message(update.effective_chat.id, text=synonyms, reply_to_message_id=query.message.message_id, parse_mode=ParseMode.MARKDOWN_V2)
def main(): def main() -> None:
""" Runs the bot and keeps it running """
wordbot_token = os.getenv('WORDBOT_TOKEN') wordbot_token = os.getenv('WORDBOT_TOKEN')
updater = Updater(token=wordbot_token, use_context=True) updater = Updater(token=wordbot_token, use_context=True)
dispatcher = updater.dispatcher dispatcher = updater.dispatcher