Skip to content

[WIP] Refactor and proper configurations #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 58 additions & 40 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@


# env variable bot_id
BOT_ID = os.environ.get("SLACK_BOT_ID")
BOT_ID = os.environ.get('SLACK_BOT_ID')

# constants
AT_BOT = "<@" + BOT_ID + ">"
AT_BOT = '<@{}>'.format(BOT_ID)

# instantiate Slack client
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
Expand All @@ -23,72 +23,72 @@
user_manager = HackcoinUserManager()

def handle_command(command, channel, user_id):
"""
Receives commands directed at the bot and determines if they
are valid commands. If so, then acts on the commands. If not,
returns back what it needs for clarification.
"""
'''
Receives commands directed at the bot and determines if they
are valid commands. If so, then acts on the commands. If not,
returns back what it needs for clarification.
'''
user_manager.load_user(user_id, channel=channel)

# Set defaults.
response = "Type *@hackcoinbot help* for a guide!"
response = 'Type *@hackcoinbot help* for a guide!'
attachment = []

command_tokens = [w.lower() for w in command.strip().split(" ")]
command_tokens = [w.lower() for w in command.strip().split(' ')]
command_type = get_command_type(command_tokens)

if command_type == "price":
if command_type == 'price':
response, attachment = get_price(command_tokens)

if command_type == "buy":
if command_type == 'buy':
response = buy(user_manager, command_tokens, user_id, channel=channel)

if command_type == "sell":
if command_type == 'sell':
response = sell(user_manager, command_tokens, user_id, channel=channel)

if command_type == "balance":
if command_type == 'balance':
response = user_manager.check_balance(user_id, channel=channel)

if command_type == "portfolio":
if command_type == 'portfolio':
response, attachment = portfolio(user_manager, user_id, channel=channel)

if command_type == "leaderboard":
if command_type == 'leaderboard':
response = user_manager.check_leaderboard(user_id, channel=channel)

if command_type == "help":
if command_type == 'help':
response = print_help()

if command_type == "meme":
if command_type == 'meme':
response = random.choice([
" litecoin is a shit investment ",
" :seansmile: buy ethereum now !!",
" is tonight the night we go to MARU ?? ",
" :blondesassyparrot: cash me ousside :blondesassyparrot: how bout dah :blondesassyparrot: ",
" you have been blessed by a r a r e p u p :doge: ",
" g o o d b o i ",
" :sakibwouldlikethat: sakib would like that "
' litecoin is a shit investment ',
' :seansmile: buy ethereum now !!',
' is tonight the night we go to MARU ?? ',
' :blondesassyparrot: cash me ousside :blondesassyparrot: how bout dah :blondesassyparrot: ',
' you have been blessed by a r a r e p u p :doge: ',
' g o o d b o i ',
' :sakibwouldlikethat: sakib would like that '
])

if command_type == "greet":
if command_type == 'greet':
response = random.choice([
" :wave: ",
" :seansmile: ",
" :fastparrot: "
' :wave: ',
' :seansmile: ',
' :fastparrot: '
])

print datetime.now(), user_manager.users[user_id]['first_name'], command_type, command
print(datetime.now(), user_manager.users[user_id]['first_name'], command_type, command)

if response is not None:
slack_client.api_call("chat.postMessage", channel=channel,
slack_client.api_call('chat.postMessage', channel=channel,
text=response,
attachments=attachment,
as_user=True)

def parse_slack_output(slack_rtm_output):
"""
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
"""
output_list = slack_rtm_output

Expand Down Expand Up @@ -116,29 +116,47 @@ def parse_slack_output(slack_rtm_output):

return None, None, None

def normalize_events(events):
okay_events = []

for event in events:
is_bot = (event.get('bot_id') is not None) and (event.get('user') != BOT_ID)
has_text = event.get('text') is not None

if is_bot or not has_text:
continue

is_direct_message = event['channel'][0] == 'D'
okay_events.append(event)

def listen():
# 0.25 second delay between reading from firehose
READ_WEBSOCKET_DELAY = 0.25
CHECK_MARKET_REMINDER = True

if slack_client.rtm_connect():
print("hackcoinbot says hello!")
print('hackcoinbot says hello!')

while True:
data_read = slack_client.rtm_read()

if CHECK_MARKET_REMINDER and is_one_hour_left():
slack_client.api_call("chat.postMessage",
channel="#tradingfloor",
text="<!channel> The stock market closes in *1 hour* :hourglass:",
slack_client.api_call('chat.postMessage',
channel='#tradingfloor',
text='<!channel> The stock market closes in *1 hour* :hourglass:',
as_user=True)
CHECK_MARKET_REMINDER = False

command, channel, user_id = parse_slack_output(slack_client.rtm_read())
print('\n\n')
print(data_read)
print('\n\n')
command, channel, user_id = parse_slack_output(data_read)
if command and channel and user_id:
handle_command(command, channel, user_id)
time.sleep(READ_WEBSOCKET_DELAY)
else:
print("Connection failed. Invalid Slack token or bot ID?")
print('Connection failed. Invalid Slack token or bot ID?')


if __name__ == "__main__":
if __name__ == '__main__':
listen()
78 changes: 39 additions & 39 deletions handlers/get_price.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ def get_price(command_tokens):
except:
return "I couldn't find the price you wanted :cry:", None

title = "{} ({})".format(
title = '{} ({})'.format(
quote['NAME'],
quote['TICKER']
)

bar_color = "good"
bar_color = 'good'
try:
if float(quote['CHANGE_AMT']) < 0:
bar_color = "danger"
bar_color = 'danger'
except:
pass

chart_url = "http://finviz.com/chart.ashx?t={}&ty=c&ta=1&p=d&s=l".format(
chart_url = 'http://finviz.com/chart.ashx?t={}&ty=c&ta=1&p=d&s=l'.format(
quote['TICKER']
)

change_text = "{} ({}%)".format(
change_text = '{} ({}%)'.format(
quote['CHANGE_AMT'],
quote['CHANGE']
)
Expand All @@ -40,28 +40,28 @@ def get_price(command_tokens):

attachment = [
{
"fallback": "Check Price",
"color": bar_color,
"title": title,
"fields": [
'fallback': 'Check Price',
'color': bar_color,
'title': title,
'fields': [
{
"title": "Price",
"value": quote['PRICE'],
"short": True
'title': 'Price',
'value': quote['PRICE'],
'short': True
},
{
"title": "Change",
"value": change_text,
"short": True
'title': 'Change',
'value': change_text,
'short': True
}
],
"image_url": chart_url,
"footer": "Google Finance | Finviz",
"ts": now
'image_url': chart_url,
'footer': 'Google Finance | Finviz',
'ts': now
}
]

return "", attachment
return '', attachment

def get_crpyto_price(command_tokens):
try:
Expand All @@ -72,49 +72,49 @@ def get_crpyto_price(command_tokens):
except:
return "We don't support that coin yet :cry:", None

title = "{} ({})".format(
title = '{} ({})'.format(
quote['NAME'],
quote['TICKER']
)

bar_color = "good"
bar_color = 'good'
try:
if quote['CHANGE_AMT'] < 0:
bar_color = "danger"
bar_color = 'danger'
except:
pass

change_pct = quote['CHANGE_AMT'] * 100.0 / (quote['PRICE'] - quote['CHANGE_AMT'])
change_text = "{:04.3f} ({:04.3f}%)".format(
change_text = '{:04.3f} ({:04.3f}%)'.format(
quote['CHANGE_AMT'],
change_pct
)

attachment = [
{
"fallback": "Check Price",
"color": bar_color,
"title": title,
"fields": [
'fallback': 'Check Price',
'color': bar_color,
'title': title,
'fields': [
{
"title": "Price",
"value": "{:05.3f}".format(quote['PRICE']),
"short": True
'title': 'Price',
'value': '{:05.3f}'.format(quote['PRICE']),
'short': True
},
{
"title": "Change (1hr)",
"value": change_text,
"short": True
'title': 'Change (1hr)',
'value': change_text,
'short': True
},
{
"title": "Volume (24hr)",
"value": "{:05.3f}".format(quote['VOLUME']),
"short": True
'title': 'Volume (24hr)',
'value': '{:05.3f}'.format(quote['VOLUME']),
'short': True
},
],
"footer": "Google Finance | Finviz",
"ts": quote['TIMESTAMP']
'footer': 'Google Finance | Finviz',
'ts': quote['TIMESTAMP']
}
]

return "", attachment
return '', attachment
40 changes: 20 additions & 20 deletions handlers/main.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
def get_command_type(command_tokens):
if len(command_tokens) == 0:
if not command_tokens:
return None

if "$" in command_tokens[0]:
return "price"
if '$' in command_tokens[0]:
return 'price'

if command_tokens[0] in set(["buy", "b"]):
return "buy"
if command_tokens[0] in ('buy', 'b'):
return 'buy'

if command_tokens[0] in set(["sell", "s"]):
return "sell"
if command_tokens[0] in ('sell', 's'):
return 'sell'

if command_tokens[0] == "balance":
return "balance"
if command_tokens[0] == 'balance':
return 'balance'

if command_tokens[0] in set(["portfolio", "p"]):
return "portfolio"
if command_tokens[0] in ('portfolio', 'p'):
return 'portfolio'

if command_tokens[0] in set(["leader", "leaderboard", "l", "top"]):
return "leaderboard"
if command_tokens[0] in ('leader', 'leaderboard', 'l', 'top'):
return 'leaderboard'

if command_tokens[0] == "help":
return "help"
if command_tokens[0] == 'help':
return 'help'

if command_tokens[0] in set(["hello", "hey", "greet", "hi"]):
return "greet"
if command_tokens[0] in ('hello', 'hey', 'greet', 'hi'):
return 'greet'

if command_tokens[0] in set(["meme", "shit", "shitpost"]):
return "meme"
if command_tokens[0] in ('meme', 'shit', 'shitpost'):
return 'meme'

def is_private_message(slack_client, channel_id):
im_ids = [
x['id']
for x in
slack_client.api_call("im.list")['ims']
slack_client.api_call('im.list')['ims']
]

return channel_id in set(im_ids)
16 changes: 8 additions & 8 deletions handlers/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ def portfolio(user_manager, user_id, channel=None):

attachment = [
{
"fallback": "Check Portfolio",
"color": "good",
"author_name": user_manager.users[user_id]['first_name'],
"author_icon": user_manager.get_user_thumbnail_url(user_id),
"title": "Portfolio",
"text": response,
"ts": now
'fallback': 'Check Portfolio',
'color': 'good',
'author_name': user_manager.users[user_id]['first_name'],
'author_icon': user_manager.get_user_thumbnail_url(user_id),
'title': 'Portfolio',
'text': response,
'ts': now
}
]
return "", attachment
return '', attachment
Loading