Moved most configuration settings out from being hardcoded to a JSON formatted config file and included a template.

This commit is contained in:
Alex Huddleston 2020-03-28 19:47:46 -05:00
parent 06f0741d0b
commit b58143fdf3
9 changed files with 52 additions and 22 deletions

3
.gitignore vendored
View file

@ -3,5 +3,4 @@
**/__pycache__/** **/__pycache__/**
**.pyc **.pyc
Pipfile.lock Pipfile.lock
.keys/ config.json
**/.credentials

View file

@ -29,5 +29,6 @@ RUN pip install pipenv
RUN pipenv install Pipfile RUN pipenv install Pipfile
COPY covid_bot.py covid_bot.py COPY covid_bot.py covid_bot.py
COPY config.json config.json
ENTRYPOINT [ "pipenv", "run", "python", "covid_bot.py" ] ENTRYPOINT [ "pipenv", "run", "python", "covid_bot.py" ]

View file

@ -29,5 +29,6 @@ RUN pip install pipenv
RUN pipenv install Pipfile RUN pipenv install Pipfile
COPY covid_report.py covid_report.py COPY covid_report.py covid_report.py
COPY config.json config.json
ENTRYPOINT [ "pipenv", "run", "python", "covid_report.py" ] ENTRYPOINT [ "pipenv", "run", "python", "covid_report.py" ]

View file

@ -1,11 +1,11 @@
#!/bin/python #!/bin/python
from discord.ext import commands from discord.ext import commands
from lib.covidBot import add_commands from lib.covidBot import add_commands
from lib.parse_data import import_config
if(__name__ == '__main__'): if(__name__ == '__main__'):
bot = commands.Bot(command_prefix='!') bot = commands.Bot(command_prefix='!')
with open('.keys/bot_api.key') as key: config_dict = import_config()
discord_api_key = key.readline().strip()
add_commands(bot) add_commands(bot)
bot.run(discord_api_key) bot.run(config_dict['api_key'])

View file

@ -2,11 +2,12 @@
from discord import Client from discord import Client
from lib.covid_report_lib import background_task from lib.covid_report_lib import background_task
from lib.parse_data import import_config
if(__name__ == '__main__'): if(__name__ == '__main__'):
with open('.keys/bot_api.key') as key: config_dict = import_config()
discord_api_key = key.readline().strip() discord_api_key = config_dict['api_key']
client = Client() client = Client()
client.loop.create_task(background_task(client)) client.loop.create_task(background_task(client, config_dict))
client.run(discord_api_key) client.run(discord_api_key)

View file

@ -1,6 +1,6 @@
from discord.ext import commands from discord.ext import commands
from re import match from re import match
from lib.parse_data import update_data, get_covid_data, covid_db, get_top_data from lib.parse_data import *
@commands.command() @commands.command()

View file

@ -3,19 +3,20 @@ from lib.parse_data import update_data, get_covid_data, get_top_data
from datetime import datetime from datetime import datetime
from pytz import timezone from pytz import timezone
from asyncio import sleep from asyncio import sleep
from math import floor
async def background_task(client): async def background_task(client, config_dict):
await client.wait_until_ready() await client.wait_until_ready()
with open('.keys/report_channel_id') as cid: channel = client.get_channel(config_dict['report_channel_id'])
channel = client.get_channel(int(cid.readline().strip()))
while not client.is_closed(): while not client.is_closed():
current_hour_and_minute = [int(t) for t in str( current_hour_and_minute = [int(t) for t in str(
datetime.now(timezone('US/Central')).time()).split(':')[:-1]] datetime.now(timezone(config_dict['report_timezones'])).time()).split(':')[:-1]]
if(current_hour_and_minute[0] == 12 and (current_hour_and_minute[1] == 0)): for rt in config_dict['report_times']:
update_data() if(current_hour_and_minute[0] == floor(rt/100) and (current_hour_and_minute[1] == rt % 100)):
await channel.send('Daily report from: https://www.worldometers.info/coronavirus/') update_data()
await channel.send(get_covid_data('USA')) await channel.send('Daily report from: https://www.worldometers.info/coronavirus/')
await channel.send(get_covid_data('TOTAL')) for selection in config_dict['report_selections']:
await channel.send(get_top_data(5)) await channel.send(get_covid_data(selection))
await channel.send(get_top_data(config_dict['report_top_number']))
await sleep(60) await sleep(60)

View file

@ -3,6 +3,8 @@
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from lib.covidData import covidData from lib.covidData import covidData
import json
from os.path import exists
# temporary database # temporary database
covid_db = {} covid_db = {}
@ -11,6 +13,20 @@ covid_db = {}
sa_data_url = 'https://www.sanantonio.gov/health/news/alerts/coronavirus' sa_data_url = 'https://www.sanantonio.gov/health/news/alerts/coronavirus'
def import_config(path='config.json'):
if(exists(path)):
try:
with open(path) as config_file:
config_dict = json.load(config_file)
except Exception as e:
print(f'There was some issue opening and loading the config.\n{e}')
exit(1)
else:
print('Didn\'t find the config file.')
exit(1)
return config_dict
def update_data(): def update_data():
data_html = requests.get('https://www.worldometers.info/coronavirus/') data_html = requests.get('https://www.worldometers.info/coronavirus/')
if(data_html.status_code == '200' or data_html.status_code == 200): if(data_html.status_code == '200' or data_html.status_code == 200):
@ -39,12 +55,15 @@ def get_top_data(number):
for data in covid_db.keys(): for data in covid_db.keys():
try: try:
if(covid_db[data].data['Selection'] and covid_db[data].data['Total Cases'] and not covid_db[data].data['Selection'] == 'Total'): if(covid_db[data].data['Selection'] and covid_db[data].data['Total Cases'] and not covid_db[data].data['Selection'] == 'Total'):
covid_db_dict[covid_db[data].data['Selection'].upper()] = int(covid_db[data].data['Total Cases'].replace(',', '')) covid_db_dict[covid_db[data].data['Selection'].upper()] = int(
covid_db[data].data['Total Cases'].replace(',', ''))
except Exception as e: except Exception as e:
print(e) print(e)
return f'{e} tests' return f'{e} tests'
covid_db_dict_sorted = {key: value for key, value in sorted(covid_db_dict.items(), key=lambda item: item[1], reverse=True)} covid_db_dict_sorted = {key: value for key, value in sorted(
top_covid_data = [(covid_db[selection].data['Selection'], covid_db[selection].data['Total Cases']) for selection in list(covid_db_dict_sorted.keys())[:number]] covid_db_dict.items(), key=lambda item: item[1], reverse=True)}
top_covid_data = [(covid_db[selection].data['Selection'], covid_db[selection].data['Total Cases'])
for selection in list(covid_db_dict_sorted.keys())[:number]]
output = '' output = ''
counter = number + 1 counter = number + 1
for data in top_covid_data: for data in top_covid_data:

8
template_config.json Normal file
View file

@ -0,0 +1,8 @@
{
"api_key": "https://discordapp.com/developers/docs/intro",
"report_channel_id": 0,
"report_timezones":"US/Central",
"report_times": [1200, 1600, 0],
"report_selections": ["USA", "TOTAL"],
"report_top_number": 5
}