Skip to content
This repository has been archived by the owner on Oct 23, 2022. It is now read-only.

Commit

Permalink
Merge pull request #24 from ExtraRandom/master
Browse files Browse the repository at this point in the history
1.0.1.2 started
  • Loading branch information
David Jetelina authored and David Jetelina committed Jun 6, 2016
2 parents fa6eb57 + efd29ca commit 0bde7d9
Show file tree
Hide file tree
Showing 7 changed files with 251 additions and 206 deletions.
102 changes: 102 additions & 0 deletions cogs/games.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import asyncio
import random
import time
import logging

import helpers.simplify as s
from helpers import descriptions as desc, settings

import calendar
from datetime import datetime

import aiohttp
from discord.ext import commands

import helpers.time_calculations as tc

# List with running game instances
games_list = []
loop = asyncio.get_event_loop()
log = logging.getLogger(__name__)


class Games:
def __init__(self, bot):

self.bot = bot

# Dates have to be in relation to UTC (so if release is 5am BST, it would be 4am UTC)
# Preferably use the latest release time for a game with different release times for different regions
self.dates = {
"No Man''s Sky": datetime(2016, 8, 12, 0, 0, 0),
"Deus Ex: Mankind Divided": datetime(2016, 8, 23, 0, 0, 0),
"Battlefield 1": datetime(2016, 10, 21, 0, 0, 0),
"Civilization 6": datetime(2016, 10, 21, 0, 0, 0),
"Dishonored 2": datetime(2016, 11, 11, 0, 0, 0),
"Mirror''s Edge: Catalyst": datetime(2016, 6, 9, 0, 0, 0),
"Mafia III": datetime(2016, 10, 7, 0, 0, 0),
"Pokemon Sun and Moon": datetime(2016, 11, 23, 0, 0, 0),
"World of Warcraft: Legion": datetime(2016, 8, 30, 0, 0, 0),
"Mighty No. 9": datetime(2016, 6, 21, 0, 0, 0),
}

@commands.command(description=desc.steam_status, brief=desc.steam_status)
async def steam(self):
steam_api = 'http://is.steam.rip/api/v1/?request=SteamStatus'
with aiohttp.ClientSession() as session:
async with session.get(steam_api)as resp:
data = await resp.json()
if str(data["result"]["success"]) == "True":
login = (data["result"]["SteamStatus"]["services"]["SessionsLogon"]).capitalize()
community = (data["result"]["SteamStatus"]["services"]["SteamCommunity"]).capitalize()
economy = (data["result"]["SteamStatus"]["services"]["IEconItems"]).capitalize()
# leaderboards = (data["result"]["SteamStatus"]["services"]["LeaderBoards"]).capitalize()

reply = """**Steam Server Status**
```xl
Login {}
Community {}
Economy {}```""".format(login, community, economy)

else:
reply = "Failed connecting to API - Error: {}".format(data["result"]["error"])

await self.bot.say(reply)

@commands.command(pass_context=True, description=desc.release_dates, brief=desc.release_datesb)
async def release(self, ctx):
# We are using manual argument detection instead of @commands.group,
# because we want sub-commands to be dynamic based on our self.dates dictionary
for game in self.dates:
maxlen = len(game)
else:
maxlen = 0
arg = " ".join(ctx.message.content.split()[1:])

if len(arg) > 0:
found = False
msg = "Found games starting with `{}`:\n\n```Ruby\n".format(arg.capitalize())
for game in self.dates:
if game.lower().startswith(arg.lower()) or game.lower() is arg.lower():
days, hrs, mins = tc.calc_until(self.dates[game])
msg += "{}\n".format(tc.create_msg(game, days, hrs, mins, maxlen))
found = True

if not found:
msg += ("No game in our release list found, that starts with {}".format(arg))

msg += "```"

else:
msg = "**Release Dates List**\n\n```Ruby\n"
for game, time in sorted(self.dates.items(), key=lambda x: x[1]):
days, hrs, mins = tc.calc_until(self.dates[game])
msg += "{}\n".format(tc.create_msg(game, days, hrs, mins, maxlen))
msg += "```"

await self.bot.say(msg)


def setup(bot):
bot.add_cog(Games(bot))
180 changes: 0 additions & 180 deletions cogs/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,6 @@ def __init__(self, bot):
"""
self.bot = bot

# Dates have to be in relation to UTC (so if release is 5am BST, it would be 4am UTC)
self.dates = {
"No Man''s Sky": datetime(2016, 8, 12, 0, 0, 0),
"Deus Ex: Mankind Divided": datetime(2016, 8, 23, 0, 0, 0),
"Battlefield 1": datetime(2016, 10, 21, 0, 0, 0),
"Civilization 6": datetime(2016, 10, 21, 0, 0, 0),
"Dishonored 2": datetime(2016, 11, 11, 0, 0, 0),
"Mirror''s Edge: Catalyst": datetime(2016, 6, 9, 0, 0, 0),
"Mafia III": datetime(2016, 10, 7, 0, 0, 0),
"Pokemon Sun and Moon": datetime(2016, 11, 23, 0, 0, 0),
"World of Warcraft: Legion": datetime(2016, 8, 30, 0, 0, 0),
"Mighty No. 9": datetime(2016, 6, 21, 0, 0, 0),
}

@commands.command(description=desc.reddit, brief=desc.reddit)
async def reddit(self): # returns link to sub-reddit
await self.bot.say("https://www.reddit.com/r/idiotechgaming/")
Expand Down Expand Up @@ -163,172 +149,6 @@ async def _perth(self):
time = get_time()
await self.bot.say("**Perth**: {} (UTC+8)".format(time["perth"]))

@commands.command(description=desc.steam_status, brief=desc.steam_status)
async def steam(self):
steam_api = 'http://is.steam.rip/api/v1/?request=SteamStatus'
with aiohttp.ClientSession() as session:
async with session.get(steam_api)as resp:
data = await resp.json()
if str(data["result"]["success"]) == "True":
login = (data["result"]["SteamStatus"]["services"]["SessionsLogon"]).capitalize()
community = (data["result"]["SteamStatus"]["services"]["SteamCommunity"]).capitalize()
economy = (data["result"]["SteamStatus"]["services"]["IEconItems"]).capitalize()
# leaderboards = (data["result"]["SteamStatus"]["services"]["LeaderBoards"]).capitalize()

reply = """**Steam Server Status**
```Login {}
Community {}
Economy {}```""".format(login, community, economy)

else:
reply = "Failed connecting to API - Error: {}".format(data["result"]["error"])

await self.bot.say(reply)

@commands.command(pass_context=True, description=desc.release_dates, brief=desc.release_datesb)
async def release(self, ctx):
# We are using manual argument detection instead of @commands.group,
# because we want sub-commands to be dynamic based on our self.dates dictionary
for game in self.dates:
maxlen = len(game)
else:
maxlen = 0
arg = " ".join(ctx.message.content.split()[1:])

if len(arg) > 0:
found = False
msg = "Found games starting with `{}`:\n\n```Ruby\n".format(arg.capitalize())
for game in self.dates:
if game.lower().startswith(arg.lower()) or game.lower() is arg.lower():
days, hrs, mins = calc_until(self.dates[game])
msg += "{}\n".format(create_msg(game, days, hrs, mins, maxlen))
found = True

if not found:
msg += ("No game in our release list found, that starts with {}".format(arg))

msg += "```"

else:
msg = "**Release Dates List**\n\n```Ruby\n"
for game, time in sorted(self.dates.items(), key=lambda x: x[1]):
days, hrs, mins = calc_until(self.dates[game])
msg += "{}\n".format(create_msg(game, days, hrs, mins, maxlen))
msg += "```"

await self.bot.say(msg)


def create_msg(game, days, hrs, mins, maxlen):
spaces = maxlen - len(game) + 30
for _ in range(spaces):
game = game + " "
if int_day(days) < 0: # if hours is a minus (i.e. game is released)
msg = "{} is out now!".format(game)
elif int_day(days) == 0 and int(hrs) == 0 and int(mins) == 0:
msg = "{} releases within the next 60 seconds, HYPE!!!".format(game)
else:
msg = "{} {}, {} hours {} minutes".format(game, days, hrs, mins)

return msg


def int_day(day):
"""
Takes day as string ('3 days') and returns just the number as an integer
:param day:
:return:
"""
day, word = day.split(" ")
return int(day)


def get_date_suf(day):
# Get the suffix to add to date ('st' for 1, 'nd' for 2 and so on) code from http://stackoverflow.com/a/5891598
if 4 <= int(day) <= 20 or 24 <= int(day) <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][int(day) % 10 - 1]
return suffix


def date_split(date):
"""
Returns the given datetime as three strings: year, month and day
:param date: The datetime to split into year, month and day
:return: year, month, day
"""

to_split = str(date).split('T')[0]
year, month, day = to_split.split('-')

return year, month, day


def date_now():
"""
Returns the date now as three strings: year, month and day
:return: year, month, day
"""

now = datetime.utcnow()
date, time = str(now).split(' ')
year, month, day = date.split('-')

return year, month, day


def calc_until(rd):
"""
Calculates the amount of time between now and 'rd'
:param rd: release date as datetime()
:return: three strings with time left
"""

t_delta = rd - datetime.utcnow()
t_str = str(t_delta)

test_var = t_str.split(".")[0]
if len(test_var) == 7 or len(test_var) == 8:
days = "0 days"
hrs, minutes, secs = test_var.split(":")
elif len(test_var) == 5 or len(test_var) == 4:
days = "0 days"
hrs = "0"
minutes, secs = test_var.split(":")
elif len(test_var) == 1 or len(test_var) == 2:
days = "0 days"
hrs = "0"
minutes = "0"
else:
days, time = t_str.split(",")
hrs, minutes, secs = time.split(":")

hrs = hrs.strip() # removes spaces in string

return days, hrs, minutes


def calc_duration(start):
"""
Calculates the amount of time between 'start' and now
:param start: Datetime
:return: three strings with time passed
"""

tdelta = datetime.utcnow() - start
tstr = str(tdelta)

hrs, mins, secs = tstr.split(":")
secs = secs.split(".")[0]

return hrs, mins, secs


def get_time() -> dict:
"""
Expand Down
22 changes: 4 additions & 18 deletions cogs/giveaway.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@

import helpers.simplify as s
from helpers import descriptions as desc, settings
import helpers.time_calculations as tc

# List with running giveaway instances
giveawayslist = []
loop = asyncio.get_event_loop()
log = logging.getLogger(__name__)


class Giveaway:
"""
Giveaway object
Expand Down Expand Up @@ -120,7 +122,7 @@ async def giveaway(self, ctx):
reply = "Currently opened giveaways:\n=========="
for ga in giveawayslist:
reply += "\n**{}** by {} ({}, {} people enrolled)".format(
ga.game, ga.owner.mention, parsesecs(ga.time), len(ga.enrolled))
ga.game, ga.owner.mention, tc.parsesecs(ga.time), len(ga.enrolled))
reply += "\n==========\nEnter giveaway with !enroll **GameName**"

else:
Expand Down Expand Up @@ -256,25 +258,9 @@ async def changetopic(self):
await self.bot.edit_channel(self.bot.get_channel(settings.channels['giveaways']), topic = new_topic)
log.info("Topic updated in giveaways")
except Exception as e:
log.exception("Couldn't change topic in giveaways")

log.exception("Couldn't change topic in giveaways - Error: {}".format(e))

def parsesecs(sec: int) -> str:
"""
Parses seconds into time left format
This is to be used only for giveaway which have limit of 30 minutes

:param sec: number of seconds
:return: string with time left
"""
if sec >= 120:
tleft = time.strftime("%M minutes left", time.gmtime(sec)).lstrip('0')
elif sec >= 60:
tleft = time.strftime("%M minute left", time.gmtime(sec)).lstrip('0')
else:
tleft = time.strftime("%S seconds left", time.gmtime(sec)).lstrip('0')

return tleft


def setup(bot):
Expand Down
17 changes: 11 additions & 6 deletions cogs/versioning/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@ Changelog
1.0
===

1.0.1
-----
* Added Versioning system
* Everything up to this point is only found in commits
* [!version][] says bot's version out loud
* [!changelog][] whispers caller last changes
1.0.1.2
-------
* Moved about some code
* Hello

1.0.1.1
-------
* Overwatch Command now also displays a players win rate as a percentage
* [!release][] Removed Hearts of Iron 4 from list
* [!release][] Added Mighty No. 9 and WoW: Legion to list

1.0.1
-----
* Added Versioning system
* Everything up to this point is only found in commits
* [!version][] says bot's version out loud
* [!changelog][] whispers caller last changes
** **
2 changes: 2 additions & 0 deletions helpers/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
'cogs.swear',
'cogs.overwatch',
'cogs.versioning',
'cogs.games',
]

# Status message for bot
Expand All @@ -35,5 +36,6 @@
"tabletop": "188081332834926592",
"technology": "188085243478147074",
"programming": "188083195470807040",
# "giveaways": "181233418099490826", # for the testing server
"giveaways": "188087131070005248",
}

0 comments on commit 0bde7d9

Please sign in to comment.