Separated settings into own file; added reporting task

This makes it easier to not have to mess with files on each git update.
Reporting code already existed in production, but the auth token is no
longer hardcoded into the function.
This commit is contained in:
Noikoio 2018-08-01 17:40:41 -07:00
parent 502a8d6b9e
commit 87dda003b7
4 changed files with 45 additions and 13 deletions

3
.gitignore vendored
View file

@ -1,2 +1,3 @@
users.db
__pycache__
__pycache__
settings.py

4
settings.py Normal file
View file

@ -0,0 +1,4 @@
# WorldTime configuration settings
# Bot token. Required to run.
BotToken = ''

View file

@ -9,20 +9,16 @@
# And yes, this code sucks. I don't know Python all too well.
# --------------------------------
# Required:
bot_token = ''
# --------------------------------
from discord import Game
from client import WorldTime
from wtclient import WorldTime
import settings
if __name__ == '__main__':
try:
if bot_token == '': raise NameError() # <- dumb
except NameError:
print("Bot token not set. Backing out.")
if settings.BotToken == '': raise AttributeError() # Cover both scenarios: variable doesn't exist, or variable is empty
except AttributeError:
print("Bot token not set. Will not continue.")
exit()
client = WorldTime(activity=Game('tz.help'))
client.run(bot_token)
client.run(settings.BotToken)

View file

@ -2,11 +2,12 @@
import discord
import asyncio
import aiohttp
from datetime import datetime
import pytz
import aiohttp
import settings
from userdb import UserDatabase
# For case-insensitive time zone lookup, map lowercase tzdata entries with
@ -35,6 +36,7 @@ class WorldTime(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.udb = UserDatabase('users.db')
self.bg_task = self.loop.create_task(self.periodic_report())
async def on_ready(self):
tsPrint('Status', 'Connected as {0} ({1})'.format(self.user.name, self.user.id))
@ -86,6 +88,7 @@ This bot uses zone names from the tz database. Most common zones are supported.
async def cmd_list_userparam(self, message, param):
# wishlist: search based on username/nickname
param = str(param)
if param.startswith('<@!') and param.endswith('>'):
param = param[3:][:-1]
if param.startswith('<@') and param.endswith('>'):
@ -166,4 +169,32 @@ This bot uses zone names from the tz database. Most common zones are supported.
# to do: small cache to not flood users who can't take a hint
return
self.udb.update_activity(message.guild.id, message.author.id)
await self.command_dispatch(message)
await self.command_dispatch(message)
# ----------------
async def periodic_report(self):
'''
Provides a periodic update in console of how many guilds we're on.
Reports guild count to Discord Bots. Please don't make use of this unless you're the original author.
'''
try:
authtoken = settings.DBotsApiKey
except AttributeError:
authtoken = ''
await self.wait_until_ready()
while not self.is_closed():
guildcount = len(self.guilds)
tsPrint("Report", "Currently in {0} guild(s).".format(guildcount))
async with aiohttp.ClientSession() as session:
if authtoken != '':
rurl = "https://bots.discord.pw/api/bots/{}/stats".format(self.user.id)
rdata = { "server_count": guildcount }
rhead = { "Content-Type": "application/json", "Authorization": authtoken }
try:
await session.post(rurl, json=rdata, headers=rhead)
tsPrint("Report", "Reported count to Discord Bots.")
except aiohttp.ClientError as e:
tsPrint("Report", "Discord Bots API report failed: {}".format(e))
await asyncio.sleep(21600) # Repeat once every six hours