Skip to content

Instantly share code, notes, and snippets.

@spudfkc
Created January 31, 2021 19:31
Show Gist options
  • Save spudfkc/51b2ed7f00ef978041957e16244b264c to your computer and use it in GitHub Desktop.
Save spudfkc/51b2ed7f00ef978041957e16244b264c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# requirements:
# discord.py
# python-dotenv
# requests
# python-dateutil
#
# reference: https://realpython.com/how-to-make-a-discord-bot-python/
import os
import random
import requests
import json
import traceback
import os
from discord.ext import commands
from dotenv import load_dotenv
from datetime import timedelta
from dateutil.parser import parse
from dateutil import tz
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
JSON_FEED_URL = os.getenv('JSON_FEED_URL', 'https://shift.orcicorn.com/index.json')
DATA_DIR = '/data'
def get_codes(url, since_date):
should_update_codes = False
last_modified = os.path.getmtime(f'{DATA_DIR}/codes.json')
# TODO date timestamp checking
with open(f'{DATA_DIR}/codes.json', 'r') as f:
json_body = json.loads(f.read())
since_date = parse(since_date)
since_date = since_date.replace(tzinfo=tz.gettz("America/New York"))
d = timedelta(days=365)
since_date = since_date - d
print(f'since date: {since_date}')
if should_update_codes:
response = requests.get(url)
response.raise_for_status()
json_body = response.json()
with open(f'{DATA_DIR}/codes.json', 'w') as f:
f.write(json.dumps(json_body))
codes = json_body[0]['codes']
for c in codes:
print(parse(c['archived']))
shift_codes = [code for code in codes if code['type'] == 'shift']
shift_codes_since = [code for code in codes if parse(code['archived']) > since_date]
b = parse(shift_codes[0]['archived'])
t = b > since_date
print(f'{b} > {since_date} = {t}')
return shift_codes_since
bot = commands.Bot(command_prefix='!')
@bot.command(name='shifty')
async def shift_codes(ctx, since_date=None):
try:
if not since_date:
await ctx.send('provide a date')
else:
codes = get_codes(JSON_FEED_URL, since_date)
if len(codes) == 0:
await ctx.send('no SHiFT codes found')
for code in codes:
print('sending...')
await ctx.send("SHiFT Code for {game}: {code}".format(game=code['game'], code=code['code']))
except Exception as e:
traceback.print_exc()
print(f'e: {e}')
await ctx.send('uh oh')
bot.run(TOKEN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment