4264acb8 by Barry

Refactored the way messages are processed. Added new raffle.

1 parent 771720d3
import operator
import sqlite3
import datetime
conn = sqlite3.connect('db.sqlite3')
def log(message):
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
try:
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
except:
pass
##################
## Database Calls
......
No preview for this file type
......@@ -4,8 +4,8 @@ import requests
import discord
import random
import datetime
import time
import re
import operator
import pickle
import logging
......@@ -39,12 +39,48 @@ client = discord.Client()
wolf = {}
logging.basicConfig(filename='hellsbot.log',level=logging.WARNING)
registered_commands = {'!help': 'do_help', '!commands': 'do_help',
'!shutup': 'do_shutup',
'!roll': 'do_roll',
'!lastseen': 'do_lastseen',
'!youtube': 'do_youtube',
'!image': 'do_image',
'!gif': 'do_gif',
'!gameslist': 'do_gameslist', '!gamelist': 'do_gameslist',
'!aliases': 'do_alias', '!alias': 'do_alias',
'!addalias': 'do_addalias',
'!games': 'do_games',
'!reloadbot': 'do_reload', '!restartbot': 'do_reload', '!rebootbot': 'do_reload',
'!whoplayed': 'do_whoplayed',
'!gimmecredits': 'do_gimmecredits', '!gimmecredit': 'do_gimmecredits',
'!grantcredits': 'do_grantcredits',
'!ticketrank': 'do_ticketrank',
'!startraffle': 'do_startraffle',
'!raffle': 'do_raffle',
'!buyticket': 'do_buyticket',
'!balance': 'do_balance',
'!slotsrules': 'do_slotsrules',
'!slots': 'do_slots',
'!hit': 'do_bj_hit', '!draw': 'do_bj_hit',
'!stay': 'do_bj_stay', '!stand': 'do_bj_stay',
'!bet': 'do_bj_bet',
'!msg': 'do_msg',
'!addfortune': 'do_addfortune',
'!fortune': 'do_fortune',
'!question': 'do_question',
'!addjoke': 'do_addjoke',
'!joke': 'do_joke',
}
#####################
## Utility Functions
#####################
def log(message):
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
try:
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
except:
pass
def format_exception(e):
exception_list = traceback.format_stack()
......@@ -145,30 +181,60 @@ def check_msg_queue():
log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
return
@client.event
def on_message(message):
#print message.content
#print message.author
#print client.user
global muted_until
# we do not want the bot to reply to itself
if message.author == client.user:
def do_roll(client, message_parts, message):
request = message_parts[0]
count = 1
dice = 100
if request.strip() != '':
if 'd' in request:
dice_parts = request.split('d')
if len(dice_parts) == 2:
if dice_parts[0].isdigit() and dice_parts[1].isdigit():
count = int(dice_parts[0])
dice = int(dice_parts[1])
if count > 100000000000000000:
client.send_message(message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
return
if message.content.lower().startswith(client.user.name.lower()):
log('Someone is talking to %s' % (client.user.name.lower(),))
if ' or ' in message.content:
questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))
if count > 100:
client.send_message(message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention()))
return
roll_results = []
for i in range(count):
roll_results.append(random.randint(1,dice))
out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results))
client.send_message(message.channel, out_string)
return
def do_lastseen(client, message_parts, message):
username = ' '.join(message_parts).replace('@', '').lower()
member = data.db_get_member(username=username)
#log(member)
if member:
out_string = ''
if member['is_afk'] == 1:
out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
elif member['status'] == 'offline':
out_string = 'Currently Offline\n'
else:
out_string = 'Currently Online\n'
out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'],
member['status_change_at'],
human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
member['prev_status'])
client.send_message(message.channel, 'Last Information on {}:\n{}'.format(byteify(username), out_string))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))
return
if message.content.startswith('!help') or message.content.startswith('!commands'):
def do_help(client, message_parts, message):
client.send_message(message.channel,
"""{} Available Commands:
You can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot?
User Info:
!aliases - Returns a list of all aliases a user has set for themselves.
!aliases <username> - Returns a list of all aliases a user has set for themselves.
!addalias <alias> - Adds an alias to your list of aliases.
!lastseen <username> - Returns info on when the user was last seen and their status.
Messages:
......@@ -203,251 +269,215 @@ Stuff:
!joke - Returns a random joke.
!roll <1d20> - Roll X number of dice of size X. 1d20 returns 1 roll 1-20. 3d6 returns 3 rolls of 1-6 etc...
!secret
!shutup - disables all image / gif / youtube span for 5 minutes
!shutup - disables all image / gif / youtube spam for 5 minutes
!bemyirlwaifu""".format(message.author.mention()))
return
if message.content.startswith('!lastseen'):
username = message.content[10:].replace('@', '').lower()
member = data.db_get_member(username=username)
#log(member)
if member:
out_string = ''
if member['is_afk'] == 1:
out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
elif member['status'] == 'offline':
out_string = 'Currently Offline\n'
else:
out_string = 'Currently Online\n'
out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'],
member['status_change_at'],
human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
member['prev_status'])
def do_shutup(client, message_parts, message):
muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5)
client.send_message(message.channel, 'All image / gif / youtube spam disabled for 5 minutes')
return
client.send_message(message.channel, 'Last Information on {}:\n{}'.format(username, out_string))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))
def do_youtube(client, message_parts, message):
if datetime.datetime.now() < muted_until:
return
client.send_message(message.channel, search_youtube(' '.join(message_parts)))
return
if message.content.startswith('!shutup'):
muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5)
client.send_message(message.channel, search_youtube(query))
def do_image(client, message_parts, message):
if datetime.datetime.now() < muted_until:
return
client.send_message(message.channel, search_google_images(' '.join(message_parts)))
return
if message.content.startswith('!youtube'):
if datetime.datetime.now() < muted_until:
return
query = message.content[9:]
client.send_message(message.channel, search_youtube(query))
def do_gif(client, message_parts, message):
if datetime.datetime.now() < muted_until:
return
client.send_message(message.channel, search_google_images(' '.join(message_parts), True))
return
if message.content.startswith('!image'):
if datetime.datetime.now() < muted_until:
return
query = message.content[7:]
client.send_message(message.channel, search_google_images(query))
return
def do_gameslist(client, message_parts, message):
limit = 20
if len(message_parts) > 0 and message_parts[0].isdigit():
limit = int(message_parts[0])
games_list = data.db_get_games_list(limit)
out_string = ''
for game in games_list:
out_string += ' {} - {}\n'.format(game[1], byteify(game[0]))
client.send_message(message.channel, 'The games I have seen people playing are: ')
while len(out_string) > 0:
client.send_message(message.channel, out_string[:1900])
out_string = out_string[1900:]
return
if message.content.startswith('!gif'):
if datetime.datetime.now() < muted_until:
return
query = message.content[7:]
client.send_message(message.channel, search_google_images(query, True))
return
def do_alias(client, message_parts, message):
if len(message_parts) > 0:
username = ' '.join(message_parts).replace('@', '').lower()
member = data.db_get_member(username=username)
else:
username = message.author.name
member = data.db_get_member(message.author.id)
if member:
aliases = data.db_get_aliases(member['member_id'])
if aliases:
client.send_message(message.channel, '{} has the following aliases: {}'.format(byteify(username), byteify(', '.join(aliases))))
else:
client.send_message(message.channel, 'No known alises for {} yet {}'.format(byteify(username), message.author.mention()))
else:
client.send_message(message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
return
if message.content.startswith('!roll'):
request = message.content[6:]
count = 1
dice = 100
if request.strip() != '':
if 'd' in request:
dice_parts = request.split('d')
if len(dice_parts) == 2:
if dice_parts[0].isdigit() and dice_parts[1].isdigit():
count = int(dice_parts[0])
dice = int(dice_parts[1])
if count > 100000000000000000:
client.send_message(message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
return
def do_addalias(client, message_parts, message):
alias = ' '.join(message_parts)
username = message.author.name.lower()
member = data.db_get_member(username=username)
if member:
data.db_add_aliases(member['member_id'], alias)
client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
else:
client.send_message(message.channel, 'Something horrible happened and it is all your fault, try logging out / on again or play a game. (or fuck off i dunno i\'m just an error message. Who am I to tell you how to run your life...)')
return
if count > 100:
client.send_message(message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention()))
return
roll_results = []
for i in range(count):
roll_results.append(random.randint(1,dice))
out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results))
client.send_message(message.channel, out_string)
return
def do_games(client, message_parts, message):
if len(message_parts) > 0:
username = ' '.join(message_parts).replace('@', '').lower()
else:
username = message.author.name
games_list = data.db_get_games(username)
if games_list:
games = ', '.join(games_list)
games = games.replace("FINAL FANTASY XIV", "**FINAL FANTASY XIV**")
log(byteify(games))
client.send_message(message.channel, 'I have seen {} playing: {}'.format(byteify(username), byteify(games)))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))
if message.content.startswith('!gameslist') or message.content.startswith('!gamelist') :
parts = message.content.split(' ')
limit = 20
if len(parts) > 1 and parts[1].isdigit():
limit = int(parts[1])
games_list = data.db_get_games_list(limit)
def do_reload(client, message_parts, message):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You shouldn't be calling this. You are clearly looking to piss Hellsbreath off.")
return
call(["service", "hellsbot", "restart"])
def do_whoplayed(client, message_parts, message):
game_name = ' '.join(message_parts)
member_list = data.db_get_whoplayed(game_name)
if not member_list:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
else:
out_string = ''
for game in games_list:
out_string += ' {} - {}\n'.format(game[1], byteify(game[0]))
client.send_message(message.channel, 'The games I have seen people playing are: ')
for member in member_list:
out_string += ' {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
client.send_message(message.channel, 'Below is a list of people who have played {} and the number of times they have launched the game:'.format(byteify(game_name),))
while len(out_string) > 0:
client.send_message(message.channel, out_string[:1900])
out_string = out_string[1900:]
return
return
if message.content.startswith('!aliases'):
username = message.content[9:].replace('@', '').lower()
member = data.db_get_member(username=username)
if member:
aliases = data.db_get_aliases(member['member_id'])
if aliases:
client.send_message(message.channel, '{} has the following aliases: {}'.format(username, byteify(', '.join(aliases))))
else:
client.send_message(message.channel, 'No known alises for {} yet {}'.format(username, message.author.mention()))
else:
client.send_message(message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
return
if message.content.startswith('!addalias'):
alias = message.content[10:]
username = message.author.name.lower()
member = data.db_get_member(username=username)
if member:
data.db_add_aliases(member['member_id'], alias)
client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
else:
client.send_message(message.channel, 'Something horrible happened and it is all your fault, try logging out / on again or play a game. (or fuck off i dunno i\'m just an error message. Who am I to tell you how to run your life...)')
return
if message.content.startswith('!games'):
username = message.content[7:].replace('@', '').lower()
games_list = data.db_get_games(username)
if games_list:
games = ', '.join(games_list)
client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games))
def do_gimmecredits(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
credits = data.db_get_credit(member['member_id'])
if credits < 5:
amount = random.randint(5, 50)
data.db_update_credit(member['member_id'], amount)
client.send_message(message.author, "You have been given {} credits.".format(amount,))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))
client.send_message(message.author, "You already have credits. Stop begging.")
return
if message.content.startswith('!whoplayed'):
game_name = message.content[11:]
member_list = data.db_get_whoplayed(game_name)
if not member_list:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
else:
out_string = ''
for member in member_list:
out_string += ' {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
client.send_message(message.channel, 'Below is a list of people who have played {} and the number of times they have launched the game:'.format(byteify(game_name),))
while len(out_string) > 0:
client.send_message(message.channel, out_string[:1900])
out_string = out_string[1900:]
def do_grantcredits(clients, message_parts, message):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
return
if message.content.startswith('!gimmecredits'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
for member in members:
credits = data.db_get_credit(member['member_id'])
if credits < 5:
amount = random.randint(5, 50)
data.db_update_credit(member['member_id'], amount)
client.send_message(message.author, "You have been given {} credits.".format(amount,))
else:
client.send_message(message.author, "You already have credits. Stop begging.")
return
if credits < 100:
data.db_update_credit(member['member_id'], 100)
client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
return
if message.content.startswith('!grantcredits'):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
def do_ticketrank(clients, message_parts, message):
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
ticket_count = 0
for member in members:
if member['discord_id'] != '78767557628133376':
#log(member)
ticket_count += member['tickets']
if ticket_count == 0:
client.send_message(message.channel, "No Tickets have been sold for this raffle.")
return
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
for member in members:
credits = data.db_get_credit(member['member_id'])
if credits < 100:
data.db_update_credit(member['member_id'], 100)
client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
return
if message.content.startswith('!ticketrank'):
# if message.author.id != '78767557628133376':
# client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
# return
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
ticket_count = 0
for member in members:
if member['discord_id'] != '78767557628133376':
#log(member)
ticket_count += member['tickets']
if ticket_count == 0:
client.send_message(message.channel, "No Tickets have been sold for this raffle.")
return
#log("Ticket Count: {}".format(ticket_count))
out_string = ""
for member in members:
if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
percent = (float(member['tickets']) / float(ticket_count)) * 100.0
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
#log("Ticket Count: {}".format(ticket_count))
out_string = ""
for member in members:
if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
percent = (float(member['tickets']) / float(ticket_count)) * 100.0
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
client.send_message(message.channel, out_string)
return
client.send_message(message.channel, out_string)
def do_startraffle(client, message_parts, message):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
return
if message.content.startswith('!startraffle'):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
ticket_count = 0
for member in members:
if member['discord_id'] != '78767557628133376':
#log(member)
ticket_count += member['tickets']
if ticket_count == 0:
client.send_message(message.channel, "No Tickets have been sold for this raffle.")
return
members = data.db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
ticket_count = 0
for member in members:
if member['discord_id'] != '78767557628133376':
#log(member)
ticket_count += member['tickets']
if ticket_count == 0:
client.send_message(message.channel, "No Tickets have been sold for this raffle.")
return
#log("Ticket Count: {}".format(ticket_count))
out_string = "The final standings are as follows: \n\n"
ticket_reel = []
for member in members:
if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
ticket_reel += [member['discord_mention']] * member['tickets']
percent = (float(member['tickets']) / float(ticket_count)) * 100.0
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
#log("Ticket Count: {}".format(ticket_count))
out_string = "The final standings are as follows: \n\n"
ticket_reel = []
for member in members:
if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
ticket_reel += [member['discord_mention']] * member['tickets']
percent = (float(member['tickets']) / float(ticket_count)) * 100.0
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
if len(ticket_reel) > 0:
winner = random.choice(ticket_reel)
while winner in ticket_reel:
ticket_reel.remove(winner)
client.send_message(message.channel, "\n\n\n**The winner is....\n\n{}!**".format(byteify(winner)))
if len(ticket_reel) > 0:
second = random.choice(ticket_reel)
while second in ticket_reel:
ticket_reel.remove(second)
time.sleep(0.5)
client.send_message(message.channel, "\n\n*2nd Place:* {}".format(byteify(winner)))
if len(ticket_reel) > 0:
third = random.choice(ticket_reel)
time.sleep(0.5)
client.send_message(message.channel, "\n*3rd Place:* {}".format(byteify(winner)))
return
out_string += "\n\n\n**The winner is....\n\n{}!**\n\n*2nd Place:* {}\n*3rd Place:* {}".format(byteify(winner), byteify(second), byteify(third))
client.send_message(message.channel, byteify(out_string))
return
if message.content.startswith('!raffle'):
client.send_message(message.channel, """Current Raffle Item:
def do_raffle(client, message_parts, message):
client.send_message(message.channel, """Current Raffle Item:
**1st Place**
Game: **Fairy Fencer F**
Game: **Lightning Returns**
Description:
*Long ago, the Vile God and the Goddess waged war with each other. Equally matched, they were sealed away in another world… Now a lazy young man named Fang somehow finds himself a key part of this war he’d really rather not deal with, but fate beckons in this uncommon RPG!*
*Lightning Returns is the concluding chapter of the Final Fantasy XIII saga and series heroine Lightning's final battle. The grand finale of the trilogy brings a world reborn as well as free character customization and stunning action based battles.*
http://store.steampowered.com/app/347830/
http://store.steampowered.com/app/345350/
**2nd Place**
......@@ -457,38 +487,39 @@ http://store.steampowered.com/app/347830/
1 Random Steam Key
Raffle Date: **2/2/2016 00:00:00 (ish)**
Raffle Date: **2/9/2016 00:00:00 (ish)**
You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits.
You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack.
**Disclaimer:** *If anything should go wrong you get no refund and there is no guarantee or warrantee on anything. 1 prize per person no matter how many tickets you have.*
""")
return
if message.content.startswith('!buyticket'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
result, response = data.db_buy_ticket(member['member_id'], 1)
if not result:
client.send_message(message.author, response)
return
return
credits = data.db_get_credit(member['member_id'])
client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
return
def do_buyticket(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
result, response = data.db_buy_ticket(member['member_id'], 1)
if not result:
client.send_message(message.author, response)
return
if message.content.startswith('!balance'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
client.send_message(message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
return
credits = data.db_get_credit(member['member_id'])
client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
return
def do_balance(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
client.send_message(message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
return
if message.content.startswith('!slotsrules'):
client.send_message(message.channel, """Paying Combinations:
def do_slotsrules(client, message_parts, message):
client.send_message(message.channel, """Paying Combinations:
:moneybag:\t:moneybag:\t:moneybag:\t\t\t pays\t250
:bell:\t:bell:\t:bell:/:moneybag:\tpays\t20
......@@ -505,126 +536,94 @@ All payouts are in credits. Each pull costs 1 credit.
Max Bet: 10 credits
To Play: !slots <bet>""")
return
def do_slots(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
return
if message.content.startswith('!slots'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
return
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
return
bet_amount = message.content[7:]
log("Member: {} Slots Bet: {}".format(member['member_name'], bet_amount))
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
return
bet_amount = message.content[7:]
log("Member: {} Slots Bet: {}".format(member['member_name'], bet_amount))
if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0:
client.send_message(message.author, "Please provide a bet amount up to 10 credits.")
return
result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0:
client.send_message(message.author, "Please provide a bet amount up to 10 credits.")
return
result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
if not result:
client.send_message(message.author, error_message)
return
reel1 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel2 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel3 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
#:moneybag: :bell: :diamonds: :spades: :hearts:
val1 = random.choice(reel1)
val2 = random.choice(reel2)
val3 = random.choice(reel3)
winnings = 0
reels = [val1, val2, val3]
cherries = reels.count(":cherries:")
spades = reels.count(":spades:")
diamonds = reels.count(":diamonds:")
bells = reels.count(":bell:")
moneybags = reels.count(":moneybag:")
if moneybags == 3:
out_string += "JACKPOT!!"
winnings = 250
elif bells == 3 or (bells == 2 and moneybags == 1):
winnings = 20
elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
winnings = 14
elif spades == 3 or (spades == 2 and moneybags == 1):
winnings = 10
elif cherries == 3:
winnings = 7
elif cherries == 2:
winnings = 5
elif cherries == 1:
winnings = 2
out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
winnings = int(winnings * int(bet_amount))
if winnings > 0:
out_string += "You Won! Total Winnings: {}".format(winnings,)
log("Member: {} Wins: {}".format(member['member_name'], winnings))
else:
out_string += "You lose. Total Winnings: {}".format(winnings,)
if winnings > 0:
result, error_message = data.db_update_credit(member['member_id'], winnings)
if not result:
client.send_message(message.author, error_message)
return
reel1 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel2 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel3 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
#:moneybag: :bell: :diamonds: :spades: :hearts:
val1 = random.choice(reel1)
val2 = random.choice(reel2)
val3 = random.choice(reel3)
winnings = 0
reels = [val1, val2, val3]
cherries = reels.count(":cherries:")
spades = reels.count(":spades:")
diamonds = reels.count(":diamonds:")
bells = reels.count(":bell:")
moneybags = reels.count(":moneybag:")
if moneybags == 3:
out_string += "JACKPOT!!"
winnings = 250
elif bells == 3 or (bells == 2 and moneybags == 1):
winnings = 20
elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
winnings = 14
elif spades == 3 or (spades == 2 and moneybags == 1):
winnings = 10
elif cherries == 3:
winnings = 7
elif cherries == 2:
winnings = 5
elif cherries == 1:
winnings = 2
out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
winnings = int(winnings * int(bet_amount))
if winnings > 0:
out_string += "You Won! Total Winnings: {}".format(winnings,)
log("Member: {} Wins: {}".format(member['member_name'], winnings))
else:
out_string += "You lose. Total Winnings: {}".format(winnings,)
if winnings > 0:
result, error_message = data.db_update_credit(member['member_id'], winnings)
if not result:
client.send_message(message.author, error_message)
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
#log(out_string)
client.send_message(message.author, out_string)
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
if message.content.startswith('!hit') or message.content.startswith('!draw'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
bj.draw()
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
data.db_delete_minigame_state(member['member_id'], 'blackjack')
log("{} - {}".format(member['member_name'], response.format(win,)))
result, error_message = data.db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
client.send_message(message.author, out_string)
return
def do_bj_hit(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
bj.draw()
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
return
if message.content.startswith('!stay') or message.content.startswith('!stand'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
......@@ -634,65 +633,60 @@ To Play: !slots <bet>""")
if not result:
client.send_message(message.author, error_message)
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
return
if message.content.startswith('!bet'):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
client.send_message(message.author, "You are already playing a game!")
out_string = ""
bj = pickle.loads(str(state))
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
data.db_delete_minigame_state(member['member_id'], 'blackjack')
log("{} - {}".format(member['member_name'], response.format(win,)))
result, error_message = data.db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
client.send_message(message.author, out_string)
return
else:
client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
return
def do_bj_stay(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bet_amount = message.content[5:]
log("Member: {} Bet: {}".format(member['member_name'], bet_amount))
if not bet_amount.isdigit():
client.send_message(message.author, "Please provide a bet amount. !bet 10")
return
result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
bj = pickle.loads(str(state))
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
data.db_delete_minigame_state(member['member_id'], 'blackjack')
log("{} - {}".format(member['member_name'], response.format(win,)))
result, error_message = data.db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
bj = Blackjack(bet_amount)
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
return
def do_bj_bet(client, message_parts, message):
member = data.db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
client.send_message(message.author, "You are already playing a game!")
out_string = ""
bj = pickle.loads(str(state))
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
......@@ -708,180 +702,247 @@ To Play: !slots <bet>""")
client.send_message(message.author, out_string)
return
return
# !msg joe in 5 minutes YOU ARE A DICK
if message.content.startswith('!msg'):
channel = message.channel
author = message.author
#author = message.author.name
username = ''
try:
message_bits = message.content.split(" ")
msg_datetime = datetime.datetime.now()
msg_idx = 2
if message_bits[2] == 'in' and message_bits[3].isdigit():
time = int(message_bits[3])
msg_idx = 4
if message_bits[4].startswith('sec'):
msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
msg_idx = 5
elif message_bits[4].startswith('hour'):
msg_datetime = msg_datetime + datetime.timedelta(hours=time)
msg_idx = 5
else: # minutes by default
msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
msg_idx = 5
elif message_bits[2] == 'on':
try:
tmp_date = parse(message_bits[3])
msg_datetime = tmp_date
msg_idx = 4
except ValueError:
client.send_message(channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
return
username = message_bits[1]
user_mention = ''
# TODO: have it look in the database. Do this AFTER on startup we add all users.
for member in client.get_all_members():
log("MEMBER: %s" % member)
if username.lower() == member.name.lower():
user_mention = member.mention()
user_id = member.id
if user_mention == '':
client.send_message(channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
return
msg_text = byteify(' '.join(message_bits[msg_idx:]))
message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
log("Message: %s" % message)
data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
# print("Data: %s" % data)
#test_ch = Object(channel.id)
#client.send_message(test_ch, 'Test Message {}.'.format(author))
except Exception as e:
client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, e))
return
if msg_datetime < datetime.datetime.now():
client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
else:
client.send_message(channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))
check_msg_queue()
return
out_string = ""
bet_amount = message.content[5:]
log("Member: {} Bet: {}".format(member['member_name'], bet_amount))
if message.content.startswith('!addfortune'):
try:
fortune = message.content[9:]
if 'aa737a5846' in fortune:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
if not bet_amount.isdigit():
client.send_message(message.author, "Please provide a bet amount. !bet 10")
return
result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
if not result:
client.send_message(message.author, error_message)
return
out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
bj = Blackjack(bet_amount)
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
data.db_delete_minigame_state(member['member_id'], 'blackjack')
log("{} - {}".format(member['member_name'], response.format(win,)))
result, error_message = data.db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
log("Added fortune")
except Exception as e:
log(e.message)
client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
return
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
if message.content.startswith('!fortune'):
fortune = None
try:
c = conn.cursor()
fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
log(fortune)
except Exception as e:
log(e)
pass
if not fortune:
client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
client.send_message(message.author, out_string)
return
def do_msg(client, message_parts, message):
channel = message.channel
author = message.author
#author = message.author.name
username = ''
try:
# TODO: Switch message_bits with message_parts
message_bits = message.content.split(" ")
msg_datetime = datetime.datetime.now()
msg_idx = 2
if message_bits[2] == 'in' and message_bits[3].isdigit():
time = int(message_bits[3])
msg_idx = 4
if message_bits[4].startswith('sec'):
msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
msg_idx = 5
elif message_bits[4].startswith('hour'):
msg_datetime = msg_datetime + datetime.timedelta(hours=time)
msg_idx = 5
else: # minutes by default
msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
msg_idx = 5
elif message_bits[2] == 'on':
try:
tmp_date = parse(message_bits[3])
msg_datetime = tmp_date
msg_idx = 4
except ValueError:
client.send_message(channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
return
username = message_bits[1]
user_mention = ''
# TODO: have it look in the database. Do this AFTER on startup we add all users.
for member in client.get_all_members():
#log("MEMBER: {}".format(byteify(member)))
if username.lower() == member.name.lower():
user_mention = member.mention()
user_id = member.id
if user_mention == '':
client.send_message(channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
return
msg_text = byteify(' '.join(message_bits[msg_idx:]))
message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
log("Message: %s" % byteify(message))
data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
# print("Data: %s" % data)
#test_ch = Object(channel.id)
#client.send_message(test_ch, 'Test Message {}.'.format(author))
except Exception as e:
client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, format_exception(e)))
return
if msg_datetime < datetime.datetime.now():
client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
else:
client.send_message(channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))
check_msg_queue()
return
def do_addfortune(client, message_parts, message):
try:
fortune = message.content[9:]
if 'aa737a5846' in fortune:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
log("Added fortune")
except Exception as e:
log(e.message)
client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
return
def do_fortune(client, message_parts, message):
fortune = None
try:
c = conn.cursor()
# TODO: Move this shit to data
fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
log(fortune)
except Exception as e:
log(e)
pass
if not fortune:
client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
else:
client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune)))
return
def do_question(client, message_parts, message):
question = message.content[10:]
if "is it gay" in question:
client.send_message(message.channel, 'Yes {}, it is gay.'.format(message.author.mention()))
return
res = wolf.query(question)
try:
if len(res.pods):
pod_text = []
for pod in res.pods:
if pod.text:
pod_text.append(pod.text)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
else:
client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune)))
tagged_sent = pos_tag(question.replace('?', '').split())
proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
wiki_search = " ".join(proper_nouns)
if wiki_search.strip() != "":
log("Looking up {}".format(wiki_search))
wiki_out = wikipedia.summary(wiki_search, sentences=3)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
else:
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
except Exception as e:
log(format_exception(e))
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
if message.content.startswith('!question'):
question = message.content[10:]
if "is it gay" in question:
client.send_message(message.channel, 'Yes {}, it is gay.'.format(message.author.mention()))
return
res = wolf.query(question)
try:
if len(res.pods):
pod_text = []
for pod in res.pods:
if pod.text:
pod_text.append(pod.text)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
else:
tagged_sent = pos_tag(question.replace('?', '').split())
proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
wiki_search = " ".join(proper_nouns)
if wiki_search.strip() != "":
log("Looking up {}".format(wiki_search))
wiki_out = wikipedia.summary(wiki_search, sentences=3)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
else:
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
except Exception as e:
log(format_exception(e))
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
def do_addjoke(client, message_parts, message):
try:
joke = message.content[9:]
if 'aa737a5846' in joke:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
log("Added joke")
except Exception as e:
log(e.message)
client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
return
def do_joke(client, message_parts, message):
joke = None
try:
c = conn.cursor()
joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
log(joke)
except Exception as e:
log(e)
pass
if not joke:
client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
else:
client.send_message(message.channel, '{} {}'.format(message.author.mention(), byteify(joke)))
return
if message.content.startswith('!addjoke'):
try:
joke = message.content[9:]
if 'aa737a5846' in joke:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
log("Added joke")
except Exception as e:
log(e.message)
client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
@client.event
def on_message(message):
#print message.content
#print message.author
#print client.user
global muted_until
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('!joke'):
joke = None
try:
c = conn.cursor()
joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
log(joke)
except Exception as e:
log(e)
pass
if not joke:
client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
else:
client.send_message(message.channel, '{} {}'.format(message.author.mention(), byteify(joke)))
return
message_parts = message.content.split(" ")
for command, method in registered_commands.iteritems():
if message_parts[0] == command:
try:
globals()[method](client, message_parts[1:], message)
except Exception as e:
log("{} - {}".format(format_exception(e), e.message))
return
if message.content.lower().startswith(client.user.name.lower()):
log('Someone is talking to %s' % (client.user.name.lower(),))
if ' or ' in message.content:
questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))
if message.content.startswith('!secret'):
client.send_message(message.channel, 'git gud {}! My source is here: http://git.savsoul.com/barry/discordbot\nVersion: {}'.format(message.author.mention(), VERSION))
return
if message.content.startswith('!bemyirlwaifu'):
client.send_message(message.channel, 'http://orig13.deviantart.net/b25e/f/2014/175/3/d/no_waifu_no_laifu_by_imtheonenexttome-d7nsx3b.gif {}!'.format(message.author.mention()))
return
if message.content.startswith('HILLARY 2016'):
client.send_message(message.channel, ':bomb: Ohhhhhh, now you done it...:bomb:'.format(message.author.mention()))
return
if message.content.startswith('!squid'):
client.send_message(message.channel, 'くコ:彡 くコ:彡 くコ:彡 くコ:彡')
return
if message.content.startswith('!stars'):
client.send_message(message.channel, '✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈ ✰═━┈┈ ✰═━┈┈')
return
if message.content.startswith('!hello'):
client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))
if message.content.startswith('!reloadbot'):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You shouldn't be calling this. You are clearly looking to piss Hellsbreath off.")
return
call(["service", "hellsbot", "restart"])
return
@client.event
......
import random
import time
import pickle
FIND_PERCENTAGE = 80
FIND_PERCENTAGE = 100
SKILL_PERCENT = 80
class HuntResponse:
ERROR = -1
......@@ -14,6 +15,7 @@ class HuntResponse:
self.message = message
self.monster = monster
exp_to_level = [500, 1250, 2250, 3500, 5000, 6750, 8750, 10950, 13350, 15950, 18750, 21750, 24950, 28350, 31950, 35750, 39750, 43950, 48350, 52950, 57750, 62750, 67850, 73050, 78350, 83750, 89250, 94850, 100550, 106350, 112250, 118250, 124350, 130550, 136850, 143250, 149750, 156350, 163050, 169850, 176750, 183750, 190850, 198050, 205350, 212750, 220250, 227850, 235550]
class Jobs:
WAR = 1
......@@ -39,6 +41,20 @@ class Jobs:
GEO = 21
RUN = 22
TemperamentPosture = {
4: {"name": "Very Agressive", "message": "Show no mercy!", "value": 4},
3: {"name": "Somewhat Agressive", "message": "Give em' a little more bite!", "value": 3},
2: {"name": "Somewhat Defensive", "message": "Back off a bit!", "value": 2},
1: {"name": "Very Defensive", "message": "Guard! Block! Parry! Hold!", "value": 1}
}
TemperamentAttitude = {
4: {"name": "Very Wild", "message": "Don't think, kill!", "value": 4},
3: {"name": "Somewhat Wild", "message": "Less thinking, more striking!", "value": 3},
2: {"name": "Somewhat Tame", "message": "Watch your opponent, then attack!", "value": 2},
1: {"name": "Very Tame", "message": "Think, and think again!", "value": 1}
}
PhysicalDamageTypes = {
'blunt': ['Hand-to-Hand', 'Club', 'Staff', 'Harlequin Frame', 'Stormwaker Frame', 'Sharpshot Frame'],
'slashing': ['Axe', 'Great Axe', 'Great Sword', 'Sword', 'Scythe', 'Katana', 'Great Katana', 'Valoredge Frame'],
......@@ -46,7 +62,7 @@ PhysicalDamageTypes = {
}
FeralSkills = {
'Airy Shield': {'type': 'Enhancing', 'sub_type': 'arrow shield', 'shadows': 'ignore', 'range': None, 'aoe': False, 'spell': 'arrow shield'},
'Airy Shield': {'fp_cost': 0, 'type': 'Enhancing', 'sub_type': 'arrow shield', 'shadows': 'ignore', 'range': None, 'aoe': False, 'spell': 'arrow shield'},
'Binding Wave': {'type': 'Enfeebling', 'shadows': 'ignore', 'range': 15, 'aoe': True, 'spell': 'bind'},
'Dire Straight': {'type': 'Physical', 'shadows': 'wipe', 'range': None, 'aoe': False},
'Dismemberment': {'type': 'Piercing', 'shadows': 'absorb', 'range': None, 'aoe': False}, # causes the monster to lose a body part
......@@ -60,37 +76,75 @@ Families = {
'acrolith': {
'base_fp': 50,
'fp_per_level': 0.1,
'max_fp': 55,
'main_job': Jobs.WAR,
'support_job': None,
'max_fp': 55,
'available_main_job': [Jobs.WAR, Jobs.DRG, Jobs.DRK, Jobs.PLD],
'available_support_job': [Jobs.WAR, Jobs.DRG, Jobs.DRK, Jobs.PLD],
'innate_feral_skills': ['Sinker Drill', 'Dire Straight', 'Dismemberment', 'Earthshatter'],
'type': 'Arcana',
'strong_vs': ['Dark'],
'charmable': False,
'aspir': False,
'drain': False
'drain': False,
'temperament_attitude': {
'initial_value': 4,
'actions': {
4: {'use_tp_chance': 100, 'ws': ['Sinker Drill'], 'side_attack_chance': 0, 'range_chance': 0},
3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
1: {'use_tp_chance': 70, 'ws': ['Binding Wave', 'Hypnosis', 'Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 70}
}
},
'temperament_posture': {
'initial_value': 4,
'actions': {
4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
1: {'use_tp_chance': 70, 'ws': ['Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 100}
}
}
},
'ahriman': {
'base_fp': 65,
'fp_per_level': 0.3,
'max_fp': 80,
'main_job': Jobs.WAR,
'support_job': Jobs.BLM,
'available_main_job': [Jobs.BLM, Jobs.RDM, Jobs.WAR],
'available_support_job': [Jobs.BLM, Jobs.RDM, Jobs.WAR],
'innate_feral_skills': ['Binding Wave', 'Magic Barrier', 'Hypnosis', 'Eyes On Me', 'Airy Shield'],
'type': 'Demon',
'traits': ['magic defence bonus +25%'],
'charmable': False,
'aspir': True,
'drain': True
'drain': True,
'temperament_attitude': {
'initial_value': 4,
'actions': {
4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
1: {'use_tp_chance': 70, 'ws': ['Binding Wave', 'Hypnosis', 'Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 70}
}
},
'temperament_posture': {
'initial_value': 4,
'actions': {
4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
1: {'use_tp_chance': 70, 'ws': ['Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 100}
}
}
}
}
Monsters = {
'Mechanical Menace': {
'initial_level': 9,
'family': 'acrolith',
'zone': 'Abyssea - Uleguerand'
},
'Floating Eye': {
'initial_level': 3,
'family': 'ahriman',
'zone': 'Ranguemont Pass'
}
......@@ -120,8 +174,27 @@ class Pankration:
def hunt_monster(self, zone):
if random.randint(1, 100) < FIND_PERCENTAGE:
monster_data = Monsters[random.choice(self.get_monsters(zone))]
print(monster_data)
family_name = monster_data['family']
level = monster_data['initial_level']
family = Families[family_name]
main_job = random.choice(family['available_main_job'])
support_job = random.choice(family['available_support_job'])
feral_skills = []
skills = random.sample(family['innate_feral_skills'], 3)
if random.randint(1, 100) < SKILL_PERCENT:
feral_skills.append(skills[0])
if random.randint(1, 100) < SKILL_PERCENT:
feral_skills.append(skills[1])
if random.randint(1, 100) < SKILL_PERCENT:
feral_skills.append(skills[2])
dicipline_level = 1
monster = Monster(family, level, main_job, support_job, feral_skills,
[], dicipline_level)
return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!",
random.choice(self.get_monsters(zone)))
monster)
else:
return HuntResponse(HuntResponse.FAILURE, "You were unable to capture a monster's soul.",
None)
......@@ -130,26 +203,77 @@ class Pankration:
return ""
class Monster:
def __init__(self, family, level, main_job, support_job, fp_capacity, innate_feral_skills,
eqipped_feral_skills, dicipline_level, temperament):
def __init__(self, family, level, main_job, support_job, innate_feral_skills,
equipped_feral_skills, dicipline_level):
self.family = family
self.level = level
self.main_job = main_job
self.support_job = support_job
self.fp_capacity = fp_capacity
self.innate_feral_skills = innate_feral_skills
self.equipped_feral_skills = eqipped_feral_skills
self.equipped_feral_skills = equipped_feral_skills
self.discipline_level = dicipline_level
self.temperament = temperament
def calculate_fp_gain(self):
self.temperament_posture = family['temperament_posture']['initial_value']
self.temperament_attitude = family['temperament_attitude']['initial_value']
self.pre_fight_command = {"temperament_posture": None, "temperament_attitude": None}
self.exp = exp_to_level[level] + 1
def __str__(self):
return "Family: {}\nLevel: {}\nMain Job: {}\nSupport Job: {}\nInnate Feral Skills: {}\nEquipped Feral Skills: {}\nDicipline Level: {}\nTemperament...".format(self.family, self.level, self.main_job, self.support_job, self.innate_feral_skills, self.equipped_feral_skills, self.discipline_level)
def get_fp(self):
return int(self.level / self.family['fp_per_level'])
def add_xp(self, exp_to_add):
self.exp += exp_to_add
for i in range(self.level, 50):
if self.exp > exp_to_level[i]:
if i > self.level:
# We leveled up!
print("Start level: {} New Level: {}".format(self.level, i))
else:
print("Just another brick in the wall...")
else:
break
# calc level based on xp
# stop at 50
pass
def set_strategy(self, strategy_type):
if strategy_type not in self.monster_data['strategies']:
return False
def get_current_posture(self):
return TemperamentPosture(self.temperament_posture)
def get_current_attitude(self):
return TemperamentAttitude(self.temperament_attitude)
def get_dicipline_level(self):
if self.dicipline_level < 2:
return "Defiant"
elif self.dicipline_level < 5:
return "Disrespectful"
elif self.dicipline_level < 7:
return "Disobedient"
else:
return "Obedient"
# This should ONLY be executed at the start of battle.
def set_strategy(self, temperament_posture, temperament_attitude):
distance_from_nature = abs(self.temperament_posture - temperament_posture)
distance_from_nature += abs(self.temperament_attitude - temperament_attitude)
if distance_from_nature == 0:
chance_of_listening = self.discipline_level
else:
chance_of_listening = float(float(self.discipline_level) / (float(distance_from_nature)/10))
chance_of_listening = abs(float((float(chance_of_listening)-1)/(20-1)))
if random.randint(1, 100) > chance_of_listening * 100:
print("DO ACTION:")
# adjust dicipline_level
# move temperament
else:
self.strategy = strategy_type
#continue action
#if severe request then reduce dicipline_level
pass
class Battle:
pass
......@@ -169,8 +293,12 @@ print(str(hunt_response.result))
time.sleep(0.5)
if hunt_response.result == HuntResponse.SUCCESS:
print(hunt_response.message)
monster = Monsters[hunt_response.monster]
print("The Soul Plate Shows: \n\n{}\n{}{}".format(hunt_response.monster))
monster = hunt_response.monster
print("The Soul Plate Shows: \n\n{}".format(monster))
print(monster.set_strategy(4, 3))
print(monster.set_strategy(1, 1))
print(monster.set_strategy(1, 2))
monster.add_xp(2900)
else:
print(hunt_response.message)
......