Skip to content

Commit

Permalink
remove proxy, cleanup, use shortcuts, more
Browse files Browse the repository at this point in the history
- now send feedback directly to bot dev
- updated vaccine info
- other slight changes/bug fixes
  • Loading branch information
harshil21 committed Jun 14, 2021
1 parent 3e919b0 commit 9464247
Show file tree
Hide file tree
Showing 17 changed files with 97 additions and 181 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
files/token.txt
files/feedback.txt
*idea
*.pyc
5 changes: 3 additions & 2 deletions bot_funcs/alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from helpers.namer import get_chat_name
from scrapers.gulfnews import GulfNews


text = "This bot can also send you breaking COVID-19 news for the UAE such as new cases, " \
"deaths, etc. when they come in (usually once a day between 2PM - 8PM UAE time).\n\n" \
"Do you wish to opt in to receive such news?\n\n" \
Expand Down Expand Up @@ -46,11 +45,12 @@ def new_cases_alert(context: CallbackContext) -> None:
result = connection(query, fetchall=True)
today = datetime.today()
alert_today = context.bot_data['sent_alert_today']
print(f"Alert hours: {(today - alert_today).seconds}")

for chat_id, chat_name, msg_id in result:

try:
if today.month > alert_today.month or today.day > alert_today.day: # Check if new day has passed
if (today - alert_today).seconds >= 12*60: # Check if new day has passed
msg = context.bot.send_message(chat_id=chat_id, text=f"UPDATE: {today.strftime('%d/%m/%Y')}\n\n"
f"{breaking_url}")
logging.info(f"\nThe breaking news was just sent to: {chat_name}.\n\n")
Expand All @@ -71,6 +71,7 @@ def new_cases_alert(context: CallbackContext) -> None:

context.bot_data['latest_breaking_url'] = breaking_url # Save the latest breaking news url
context.bot_data['sent_alert_today'] = today
logging.info(f"\nSuccessfully updated breaking_url and sent_alert\n\n")
context.dispatcher.persistence.flush() # Gotta do this to force save sigh


Expand Down
57 changes: 32 additions & 25 deletions bot_funcs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from graphing.ui.utility import remove_user_data


def helper(update: Update, context: CallbackContext) -> None:
def helper(update: Update, _: CallbackContext) -> None:
"""Sends a help message to the user explaining available bot commands."""
msg = "This bot gives you up to date information about the coronavirus\. Here are the commands" \
" supported:\n\n" \
Expand All @@ -27,8 +27,7 @@ def helper(update: Update, context: CallbackContext) -> None:
"You can find the source code of this project [here](https://github.com/tmslads/Coronatracker)\.\n\n" \
"This bot is actively maintained by: @Hoppingturtles"

context.bot.send_message(chat_id=update.effective_chat.id, text=msg, parse_mode="MarkdownV2",
disable_web_page_preview=True)
update.message.reply_markdown_v2(text=msg, disable_web_page_preview=True)
logging.info(f"\n{update.effective_user.name} just used /help in {get_chat_name(update)}.\n\n")


Expand Down Expand Up @@ -68,11 +67,9 @@ def uae(update: Update, context: CallbackContext) -> None:
logging.info(f"\n{update.effective_user.name} just used /uae in {get_chat_name(update)}.\n\n")


def world(update: Update, context: CallbackContext) -> None:
def world(update: Update, _: CallbackContext) -> None:
"""Sends the user worldwide coronavirus statistics."""
chat_id = update.effective_chat.id

context.bot.send_chat_action(chat_id=chat_id, action='typing')
update.message.reply_chat_action(action='typing')
init = WorldMeter()
total, dead, recovered = init.latest_data()
msg = f"Latest coronavirus stats across the globe:\n\n" \
Expand All @@ -81,45 +78,55 @@ def world(update: Update, context: CallbackContext) -> None:
f"🩹 Recoveries: {recovered}`\n\n" \
f"_Last updated on {datetime.now(timezone.utc).strftime('%B %d, %Y at %H:%M:%S')} UTC_"

context.bot.send_message(chat_id=chat_id, text=msg, parse_mode='MarkdownV2')
update.message.reply_markdown_v2(text=msg)
logging.info(f"\n{update.effective_user.name} just used /world in {get_chat_name(update)}.\n\n")


def ask_feedback(update: Update, context: CallbackContext) -> int:
def ask_feedback(update: Update, _: CallbackContext) -> int:
"""Sends a message to the user asking for feedback. Called when user clicks /feedback."""
logging.info(msg=f"\n{update.effective_user.name} just used /feedback in {get_chat_name(update)}\n\n")

context.bot.send_message(chat_id=update.effective_chat.id,
text="What would you like suggest? You can submit a bug report, feature request, "
"anything!\nMake sure to read /help before submitting.\n\nType /cancel to cancel.",
reply_markup=ForceReply(selective=True))
update.message.reply_text(text="What would you like suggest? You can submit a bug report, feature request, "
"anything!\nMake sure to read /help before submitting.\n\nType /cancel to cancel.",
reply_markup=ForceReply(selective=True))

return 1


def receive_feedback(update: Update, context: CallbackContext) -> int:
"""Get feedback from user, display in console and save to file."""
with open("files/feedback.txt", 'a') as f:
feedback = f"{update.effective_user.name} suggested: {update.message.text}\n\n"
f.write(feedback)

"""Get feedback from user, display in console and send to bot developer."""
feedback = f"Feedback received from {update.effective_user.name}:\n\n{update.message.text}"
logging.info(msg=f'\n{feedback}')

context.bot.send_message(chat_id=update.effective_chat.id, text="Thank you for your feedback!")
update.message.reply_text(text="Thank you for your feedback!")
context.bot.send_message(chat_id=476269395, text=feedback)

return -1


def vaccine(update: Update, _: CallbackContext) -> None:
"""Sends vaccine information for the users in UAE."""
vaccine_msg = "The UAE is now offering *free* vaccinations to people\. \n\n" \
"• Anyone from age 12 onwards can walk in and get vaccinated with a vaccine of their choice\.\n\n" \
"*Where are the vaccination centres?* \n\n" \
"Call DHA \(800342\) _or_ download their app " \
"\([Android](https://play.google.com/store/apps/details?id=ae.gov.dha.flagship&hl=en&gl=US)\)" \
"\([iOS](https://apps.apple.com/ae/app/dha-%D9%87%D9%8A%D8%A6%D8%A9-%D8%A7%D9%84%D8%B5%D8%AD%D8%A9" \
"-%D8%A8%D8%AF%D8%A8%D9%8A/id1437186269)\) & book a COVID\-19 vaccination appointment\.\n\n" \

update.message.reply_markdown_v2(text=vaccine_msg, disable_web_page_preview=True)
logging.info(msg=f'\n{update.effective_user.name} just used /vaccine in {get_chat_name(update)}.\n\n')


def cancel(update: Update, context: CallbackContext) -> int:
"""Cancels the current operation."""
logging.info(msg=f"\nThe user cancelled the request.\n\n")
try:
remove_user_data(update, context)
del_msg(update, context, msg_no=-1)
except Exception as e:
print(e)

context.bot.send_message(chat_id=update.effective_chat.id, text="The command was cancelled.",
reply_markup=ReplyKeyboardRemove(selective=True))
logging.info(msg=f"\nThe user cancelled the request.\n\n")
logging.exception(e)

remove_user_data(update, context)
update.message.reply_text(text="The command was cancelled.", reply_markup=ReplyKeyboardRemove(selective=True))

return -1
Binary file modified files/bot_settings.db
Binary file not shown.
Empty file removed files/feedback.txt
Empty file.
Binary file modified files/user_data
Binary file not shown.
Binary file modified graphing/covid_data.db
Binary file not shown.
6 changes: 1 addition & 5 deletions graphing/load_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,6 @@ def converter_n_splitter(data: list, split: bool = False) -> Union[List, Tuple[d
def download_file(context: CallbackContext):
"""
Download the full covid-19 dataset from ourworldindata every 6 hours. Also shows the download progress bar.
Args:
context (CallbackContext): Required context object by python-telegram-bot.
"""
if 'last_data_dl_date' not in context.bot_data:
context.bot_data['last_data_dl_date'] = datetime.today()
Expand All @@ -134,13 +131,12 @@ def download_file(context: CallbackContext):

if (today - dl_today).seconds < 21600 and (today - dl_today).days < 1: # Update if more than 6 hours have passed.
logging.info("Not time for updates yet.")
del today, dl_today
return

logging.info("Beginning to download...")

r = requests.get("https://covid.ourworldindata.org/data/owid-covid-data.csv", allow_redirects=True, stream=True,
proxies=context.job.context['owid'], timeout=20)
timeout=20)
block_size = 1024

total_size_in_bytes = (int(r.headers.get('content-length', 0)) / (32 * block_size))
Expand Down
6 changes: 3 additions & 3 deletions graphing/ui/country_maker.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def make_country_list(update: Update, context: CallbackContext) -> COUNTRY_SELEC
country_page.insert(0, [InlineKeyboardButton(text="<< Main menu", callback_data="back_main")])

update.callback_query.answer()
update.callback_query.edit_message_text(text=country_msg.replace('()', str(page)), parse_mode="MarkdownV2",
reply_markup=InlineKeyboardMarkup(country_page))

msg = update.callback_query.edit_message_text(text=country_msg.replace('()', str(page)), parse_mode="MarkdownV2",
reply_markup=InlineKeyboardMarkup(country_page))
context.user_data['graph_id'] = msg.message_id
return COUNTRY_SELECTOR
2 changes: 0 additions & 2 deletions graphing/ui/datas.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,4 @@
'URY': 'Uruguay 🇺🇾', 'UZB': 'Uzbekistan 🇺🇿', 'VEN': 'Venezuela 🇻🇪', 'VNM': 'Vietnam 🇻🇳',
'ESH': 'Western Sahara 🇪🇭', 'YEM': 'Yemen 🇾🇪', 'ZMB': 'Zambia 🇿🇲', 'ZWE': 'Zimbabwe 🇿🇼'}

# country_to_iso = {v: k for k, v in iso_codes.items()}

MAIN_SELECTOR, COUNTRY_SELECTOR, TREND_SELECTOR, GRAPH_OPTIONS = range(0, 4)
13 changes: 8 additions & 5 deletions graphing/ui/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@

def call_graph_command(update: Update, context: CallbackContext) -> MAIN_SELECTOR:
"""Displays the main selection screen when user first uses /graphs."""
context.bot.send_message(chat_id=update.effective_chat.id, text=entry_msg,
reply_markup=InlineKeyboardMarkup(entry_buttons))
msg = update.message.reply_text(text=entry_msg, reply_markup=InlineKeyboardMarkup(entry_buttons))
context.user_data['graph_id'] = msg.message_id

logging.info(msg=f"\n{update.effective_user.name} is using /graphs in {get_chat_name(update)}")

return MAIN_SELECTOR


def show_trend_buttons(update: Update, _: CallbackContext) -> None:
def show_trend_buttons(update: Update, context: CallbackContext) -> None:
"""Displays the trend buttons and changes the callback data of the back button so back button works as expected."""
button_clicked = None

Expand All @@ -36,6 +37,8 @@ def show_trend_buttons(update: Update, _: CallbackContext) -> None:
logging.info(f"{update.callback_query.from_user.name} has selected {button_clicked}.")

update.callback_query.answer()
update.callback_query.edit_message_text(text=updated_selection, parse_mode="MarkdownV2",
reply_markup=InlineKeyboardMarkup(graph_buttons))
msg = update.callback_query.edit_message_text(text=updated_selection, parse_mode="MarkdownV2",
reply_markup=InlineKeyboardMarkup(graph_buttons))
context.user_data['graph_id'] = msg.message_id

return TREND_SELECTOR
14 changes: 9 additions & 5 deletions graphing/ui/navigation.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Navigation for countries and for going back to 'main' screen
# Navigation for country pages, covid trend selector, and main page.

import logging

Expand All @@ -11,10 +11,13 @@
user_selection, iso_codes, COUNTRY_SELECTOR, trend_buttons)


def go_back_to_main(update: Update, _: CallbackContext) -> MAIN_SELECTOR:
def go_back_to_main(update: Update, context: CallbackContext) -> MAIN_SELECTOR:
"""Navigates the user back to the main selector."""
update.callback_query.answer()
update.callback_query.edit_message_text(text=entry_msg, reply_markup=InlineKeyboardMarkup(entry_buttons))
msg = update.callback_query.edit_message_text(text=entry_msg, reply_markup=InlineKeyboardMarkup(entry_buttons))

context.user_data['graph_id'] = msg.message_id

logging.info(msg=f"{update.callback_query.from_user.name} went back to the main menu.")

return MAIN_SELECTOR
Expand All @@ -36,8 +39,9 @@ def go_back_to_trend_buttons(update: Update, context: CallbackContext) -> None:

update.callback_query.answer()
del_msg(update, context)
context.bot.send_message(chat_id=update.effective_chat.id, text=msg,
reply_markup=InlineKeyboardMarkup(graph_buttons), parse_mode="MarkdownV2")
msg = context.bot.send_message(chat_id=update.effective_chat.id, text=msg,
reply_markup=InlineKeyboardMarkup(graph_buttons), parse_mode="MarkdownV2")
context.user_data['graph_id'] = msg.message_id

context.user_data['log'] = False # Reset log to False if user left from log=True state.
trend_buttons[0][-1].text = "Log scale ❌"
Expand Down
7 changes: 4 additions & 3 deletions graphing/ui/trends_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,10 @@ def send_graph(update: Update, context: CallbackContext, x: list, y: list, count
f"{(context.bot_data['last_data_dl_date'] - timedelta(hours=4)).strftime('%B %d, %Y at %H:%M:%S')}" \
f" UTC_" # Add date and time of last update

context.bot.send_photo(chat_id=chat_id,
photo=open(f"graphing/{pic}.png", "rb"), reply_markup=InlineKeyboardMarkup(trend_buttons),
caption=img_caption, parse_mode="MarkdownV2")
msg = update.message.reply_photo(photo=open(f"graphing/{pic}.png", "rb"), parse_mode="MarkdownV2",
reply_markup=InlineKeyboardMarkup(trend_buttons),
caption=img_caption)
context.user_data['graph_id'] = msg.message_id

logging.info(f"\nThe trend picture was just sent to: {update.callback_query.from_user.name}.\n")

Expand Down
19 changes: 10 additions & 9 deletions graphing/ui/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
from telegram import Update, InlineKeyboardButton
from telegram.ext import CallbackContext

from graphing.ui.datas import iso_codes
from helpers.msg_deletor import del_msg
from graphing.ui.datas import iso_codes, trend_buttons


def trend_to_human_readable(trend: str) -> str:
Expand All @@ -29,20 +28,22 @@ def remove_user_data(update: Update, context: CallbackContext) -> None:
context (CallbackContext): Required context object by python-telegram-bot.
"""
# Commented out in case we need to delete specific items from user_data only-
# for data in {'covid_country', 'covid_trend_pic', 'log', 'trend_data', 'country_list', 'country_page'}:
# for data in {'covid_country', 'covid_trend_pic', 'log', 'trend_data', 'country_list', 'country_page', 'graph_id'}:
# del context.user_data[data]
# logging.info(f"Deleted {data} for {update.effective_user.name}!\n")
del_pic(context)
del_pic_local(context)

context.bot.edit_message_reply_markup(chat_id=update.effective_chat.id, message_id=context.user_data['graph_id'],
reply_markup=None)
logging.info(f"The /graphs markup for {update.effective_user.name} has been removed!\n\n")

context.user_data.clear()
trend_buttons[0][-1].text = "Log scale ❌" # Reset to show False if user timed out in log scale True

context.dispatcher.persistence.flush() # Force save

logging.info(f"All data for {update.effective_user.name} is deleted!\n\n")

if del_msg(update, context, msg_no=1):
logging.info(f"The /graphs msg for {update.effective_user.name} is deleted!\n\n")


def remove_all_user_data(context: CallbackContext) -> None:
"""
Expand All @@ -52,7 +53,7 @@ def remove_all_user_data(context: CallbackContext) -> None:
context (CallbackContext): Required context object by python-telegram-bot.
"""
# print(context.dispatcher.user_data.values())
del_pic(context)
del_pic_local(context)

for user in context.dispatcher.user_data.values():
user.clear()
Expand All @@ -61,7 +62,7 @@ def remove_all_user_data(context: CallbackContext) -> None:
logging.info(f"All data for all users is deleted!\n\n")


def del_pic(context: CallbackContext) -> None:
def del_pic_local(context: CallbackContext) -> None:
"""
Delete the picture which matplotlib stored.
Expand Down
4 changes: 1 addition & 3 deletions helpers/msg_deletor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,4 @@ def del_msg(update: Update, context: CallbackContext, msg_no: int = 0) -> bool:
except Exception as e:
logging.info(msg=f"\nMessage couldn't be deleted due to: {e}.")
return False

else:
return True
return True
Loading

0 comments on commit 9464247

Please sign in to comment.