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

Commit

Permalink
formatting and readability check
Browse files Browse the repository at this point in the history
  • Loading branch information
djetelina committed May 19, 2016
1 parent f7bc859 commit 143568a
Show file tree
Hide file tree
Showing 9 changed files with 170 additions and 64 deletions.
16 changes: 8 additions & 8 deletions channels.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
channels = {
"admin" : "176304607172100097",
"news" : "179963038781276160",
"prison" : "180887016207024129",
"private" : "179945195280924673",
"public" : "176293292865093632",
"rules" : "179965419728273408",
"code" : "181397661956571136"
}
"admin": "176304607172100097",
"news": "179963038781276160",
"prison": "180887016207024129",
"private": "179945195280924673",
"public": "176293292865093632",
"rules": "179965419728273408",
"code": "181397661956571136"
}
5 changes: 3 additions & 2 deletions checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def predicate(ctx):
DANNY'S PERMS
"""


def is_owner_check(message):
return message.author.id == '132577770046750720'

Expand All @@ -58,7 +59,7 @@ def role_or_permissions(ctx, check, **perms):
ch = ctx.message.channel
author = ctx.message.author
if ch.is_private:
return False # can't have roles in PMs
return False # can't have roles in PMs

role = discord.utils.find(check, author.roles)
return role is not None
Expand All @@ -75,4 +76,4 @@ def admin_or_permissions(**perms):
def predicate(ctx):
return role_or_permissions(ctx, lambda r: r.name == 'Bot Admin', **perms)

return commands.check(predicate)
return commands.check(predicate)
86 changes: 59 additions & 27 deletions cogs/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,20 @@

class General:
def __init__(self, bot):
"""
Edit self.dates with releases we want to track
"""
self.bot = bot
self.dates = {
"Overwatch": datetime(2016, 5, 24, 0, 0, 0),
"Total War: Warhammer": datetime(2016, 5, 24, 0, 0, 0),
"Hearts of Iron 4": datetime(2016, 6, 6, 0, 0, 0),
"No Man's Sky": datetime(2016, 6, 21, 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),
}

@commands.command(description=desc.reddit, brief=desc.reddit)
async def reddit(self):
Expand Down Expand Up @@ -96,7 +109,7 @@ async def _sf(self):
await s.destructmsg("**San Francisco**: {} (UTC-7)".format(time["sf"]), 30, self.bot)

@commands.command(description=desc.steam_status, brief=desc.steam_status)
async def steamstatus(self):
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:
Expand All @@ -114,33 +127,43 @@ async def steamstatus(self):
**Economy servers:** {}""".format(login, community, economy)

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

await s.destructmsg(reply, 30, self.bot)

@commands.command(description=desc.releasae_dates, brief=desc.releasae_dates)
async def rd(self):
dates = {
"Overwatch": datetime(2016, 5, 24, 0, 0, 0),
"Total War: Warhammer": datetime(2016, 5, 24, 0, 0, 0),
"Hearts of Iron 4": datetime(2016, 6, 6, 0, 0, 0),
"No Man's Sky": datetime(2016, 6, 21, 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),
}

msg = "Release Dates List - Times, Dates and Games are subject to change\n"

for game, time in sorted(dates.items(), key=lambda x: x[1]):
days, hrs, mins = rd_calc(dates[game])
msg += "\n{} releases in {},{} hours and {} minutes.".format(game, days, hrs, mins)

await s.destructmsg("```"+msg+"```", 30, self.bot)
@commands.command(pass_context=True, description=desc.releasae_dates, brief=desc.releasae_dates)
async def release(self, ctx):
"""
We are using manual argument detection instead of @commands.group,
because we want subcommands to be dynamic based on our self.dates dictionary
"""
arg = " ".join(ctx.message.content.split()[1:])
if len(arg) > 0:
for game in self.dates:
if game.lower().startswith(arg):
days, hrs, mins = rd_calc(self.dates[game])
msg = "{} releases in {},{} hours and {} minutes.".format(game, days, hrs, mins)
await s.destructmsg(msg, 30, self.bot)
break
else:
await s.destructmsg("No game in our release list found, that starts with {}".format(arg), 30, self.bot)
else:
msg = "Release Dates List - Times, Dates and Games are subject to change\n"

for game, time in sorted(self.dates.items(), key=lambda x: x[1]):
days, hrs, mins = rd_calc(self.dates[game])
msg += "\n{} releases in {},{} hours and {} minutes.".format(game, days, hrs, mins)

await s.destructmsg("```{}```".format(msg), 30, self.bot)


def rd_calc(rd):
"""
Calculator for release dates
:param rd: datetime()
:return: three strings with time left
"""

tdelta = rd - datetime.utcnow()
tstr = str(tdelta)
Expand All @@ -152,12 +175,18 @@ def rd_calc(rd):


def dur_calc(rd):
"""
Calculator for duration of time streaming
:param rd: Timestamp of stream start from twitch API
:return: three strings with time passed
"""

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

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

return hrs, mins, secs

Expand All @@ -170,9 +199,7 @@ def get_time() -> dict:
"""
fmt = '%H:%M'

# http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/

now_utc = datetime.now(timezone('UTC')) # print(now_utc.strftime(fmt))
now_utc = datetime.now(timezone('UTC'))

now_pacific = now_utc.astimezone(timezone('US/Pacific'))
sf = now_pacific.strftime(fmt)
Expand All @@ -186,7 +213,12 @@ def get_time() -> dict:
now_ny = now_utc.astimezone(timezone('US/Eastern'))
ny = now_ny.strftime(fmt)

return {"sydney": sydney, "london": london, "ny": ny, "sf": sf}
return {
"sydney": sydney,
"london": london,
"ny": ny,
"sf": sf
}


def setup(bot):
Expand Down
51 changes: 43 additions & 8 deletions cogs/giveaway.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
import asyncio
import time

# List with running giveaway instances
giveawayslist = []
loop = asyncio.get_event_loop()
# Channels where we are allowed to host giveaways
whitechannels = ['private', 'code']
loop = asyncio.get_event_loop()


class Giveaway:
"""
Object for giveaway, after creating call loop.create_event(self.countdown)
Giveaway object
To start counting down the giveaway timer we call loop.create_event(self.countdown())
"""

def __init__(self, game, countdown, channel, owner, bot):
Expand All @@ -40,38 +44,53 @@ def __init__(self, game, countdown, channel, owner, bot):
giveawayslist.append(self)

async def countdown(self):
"""
Start counting down the giveaway
"""
while True:
if self.time > 0:
self.time -= 1
await asyncio.sleep(1)
else:
break
# After the countdown is complete, check if the givaway hasn't been cancelled
if self.status:
try:
stats = self.bot.get_cog('Stats')
if stats is not None:
await stats.on_giveaway(self.game)

winner = random.choice(self.enrolled)
await self.bot.send_message(self.channel, "{}'s giveaway winner of {} is: {}".format(
self.owner.mention, self.game, winner.mention))
self.owner.mention, self.game, winner.mention))
await s.whisper(self.owner, "Winner of your giveaway for {}: {}".format(
self.game, winner.mention), self.bot)
self.game, winner.mention), self.bot)
await s.whisper(winner, "You won a giveaway for **{}** by {}".format(
self.game, self.owner.mention), self.bot)
self.game, self.owner.mention), self.bot)

if self.code:
await s.whisper(winner, "Your game code: {}".format(self.code), self.bot)
await s.whisper(self.owner, "I have sent them the code you provided.", self.bot)

except IndexError:
await self.bot.send_message(self.channel,
"Nobody enrolled for {} and the giveaway has concluded".format(self.game))
await self.bot.send_message(
self.channel, "Nobody enrolled for {} and the giveaway has concluded".format(self.game))
await s.whisper(self.owner, "Nobody enrolled for your giveaway of {}".format(self.game), self.bot)

giveawayslist.remove(self)

def enroll(self, user):
self.enrolled.append(user)

def remove(self, user):
"""
Right now not used
Possible ways to implement:
!enroll cancel
Remove somebody from giveaway and permit them from entering
Would need to add blacklist function
This is okay with #public not being whitelisted
"""
self.enrolled.remove(user)

async def cancel(self):
Expand All @@ -85,6 +104,7 @@ class Giveaways:
"""
Giveaway category of commands
"""

def __init__(self, bot):
self.bot = bot

Expand All @@ -95,8 +115,9 @@ async def giveaway(self, ctx):
reply = "\nCurrently opened giveaways:\n=========="
for ga in giveawayslist:
reply += "\n**{}** in {} by {} ({}, {} people enrolled)".format(
ga.game, ga.channel.mention, ga.owner.mention, parsesecs(ga.time), len(ga.enrolled))
ga.game, ga.channel.mention, ga.owner.mention, parsesecs(ga.time), len(ga.enrolled))
reply += "\n==========\nEnter giveaway with !enroll **GameName**"

else:
reply = "No giveaway open"

Expand All @@ -108,6 +129,7 @@ async def _open(self, ctx, channel: str, countdown: int, *, game: str):
for giveaway in giveawayslist:
if ctx.message.author == giveaway.owner:
has_opened = True

if not has_opened:
try:
destination = self.bot.get_channel(chan.channels[channel])
Expand All @@ -130,11 +152,14 @@ async def _open(self, ctx, channel: str, countdown: int, *, game: str):
I will open the enrollments to your giveaway after you send me `!giveaway confirm`
""", self.bot)

else:
await s.whisper(
ctx.message.author, "I'm sorry, but you can't open a giveaway in this channel.", self.bot)

except KeyError:
await s.whisper(ctx.message.author, "I don't know channel *{}*".format(channel), self.bot)

else:
await s.whisper(ctx.message.author, "You already have one giveaway open", self.bot)

Expand Down Expand Up @@ -168,8 +193,10 @@ async def _confirm(self, ctx):
await self.bot.send_message(
giveaway.channel, "@here {0} just opened a giveaway for {1}. Type '!enroll {1}' to enroll".format(
giveaway.owner.mention, giveaway.game))

if giveaway.desc:
await self.bot.send_message(giveaway.channel, "Description: {}".format(giveaway.description))

if giveaway.url:
await self.bot.send_message(giveaway.channel, giveaway.url)

Expand All @@ -184,24 +211,30 @@ async def _cancel(self, ctx):
async def enroll(self, ctx, *, game: str):
user = ctx.message.author
found = 0

if len(giveawayslist) == 0:
await s.whisper(user, "There are no giveaway opened", self.bot)
return

for opened in giveawayslist:
if opened.game.lower() == game.lower():
if ctx.message.channel == opened.channel and user not in opened.enrolled:
opened.enroll(user)
found = 1
await s.whisper(user, "You enrolled for {}".format(game), self.bot)

elif user in opened.enrolled:
found = 1
await s.whisper(user, "You are already enrolled for this game", self.bot)

else:
found = 1
await s.whisper(user, "You tried to enter a giveaway from wrong channel, sorry can't do that",
self.bot)

if not found:
await s.whisper(user, "Giveaway for the game you mentioned not found", self.bot)

await self.bot.delete_message(ctx.message)


Expand All @@ -215,8 +248,10 @@ def parsesecs(sec: int) -> str:
"""
if sec >= 60:
tleft = time.strftime("%M minutes left", time.gmtime(sec)).lstrip('0')

else:
tleft = time.strftime("%S seconds left", time.gmtime(sec)).lstrip('0')

return tleft


Expand Down

0 comments on commit 143568a

Please sign in to comment.