771720d3 by Barry

Moved the data access layer to it's own file. Added a way to restart the bot fro…

…m chat. Updates to pankration.
1 parent 775d749e
import sqlite3
conn = sqlite3.connect('db.sqlite3')
def log(message):
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
##################
## Database Calls
##################
# Converts a row into a dictionary
def dict_factory(cursor, row):
if row == None:
return None
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def db_get_credit(member_id):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if credits:
return credits[0]
def db_buy_ticket(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits, tickets FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) - int(100*amount) < 0:
return False, "You do not have enough credits to purchase a ticket. Credits: {} Tickets: {}".format(credits[0], credits[1])
c = conn.cursor()
cost = int(100 * amount)
c.execute("""UPDATE members SET credits = credits - ?, tickets = tickets + ?
WHERE member_id = ?;""", (cost, amount, member_id))
conn.commit()
return True, int(credits[1]) + int(amount)
def db_update_credit(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) + int(amount) < 0:
return False, "You do not have enough credits to cover amount requested. Credit: {} Amount Requested: {}".format(credits[0], amount)
if int(credits[0]) < 0:
c.execute("""UPDATE members SET credits = 0
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
c.execute("""UPDATE members SET credits = credits + ?
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
return True, ""
def db_add_minigame(member_id, minigame_name, state):
c = conn.cursor()
db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if not db_state:
c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
VALUES(?, ?, ?);""", (member_id, minigame_name, state))
conn.commit()
else:
c.execute("""UPDATE minigames SET state = ?
WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
conn.commit()
def db_get_minigame_state(member_id, minigame_name):
c = conn.cursor()
state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if state:
return state[0]
def db_delete_minigame_state(member_id, minigame_name):
c = conn.cursor()
c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
conn.commit()
def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
c = conn.cursor()
c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
VALUES(?, ?, ?, ?, ?, ?);""", (message, delivery_time, channel, message_from, message_to, user_id))
conn.commit()
def db_delete_sent_message(message_id):
c = conn.cursor()
c.execute("DELETE FROM messages WHERE message_id = ?;", (message_id,))
conn.commit()
def db_get_aliases(member_id):
c = conn.cursor()
aliases = c.execute("SELECT alias_name FROM aliases WHERE member_id = ?;", (member_id,)).fetchall()
if aliases:
alias_list = []
for alias in aliases:
alias_list.append(alias[0])
return alias_list
else:
return None
def db_add_aliases(member_id, alias_name):
c = conn.cursor()
c.execute("INSERT INTO aliases(alias_name, member_id) VALUES (?, ?);", (alias_name, member_id,))
conn.commit()
def db_get_messages():
msg_conn = sqlite3.connect('db.sqlite3')
c = msg_conn.cursor()
messages = c.execute("SELECT * FROM messages WHERE datetime('now') >= datetime( replace(delivery_time, '/', '-'));").fetchall()
if messages:
db_messages = []
for message in messages:
db_messages.append(dict_factory(c, message))
else:
db_messages = None
msg_conn.close()
return db_messages
def db_get_whoplayed(game_name):
c = conn.cursor()
members = c.execute("""SELECT m.member_name, xmg.launch_count
FROM members m
INNER JOIN xmember_games xmg ON
m.member_id = xmg.member_id
INNER JOIN games g ON
g.game_id = xmg.game_id
WHERE g.game_name COLLATE nocase = ?
Order By xmg.launch_count, m.member_name DESC;""", (game_name,)).fetchall()
member_list = {}
for member in members:
member_list[member[0]] = member[1]
#log(member_list)
return sorted(member_list.items(), reverse=True, key=operator.itemgetter(1))
#return sorted(member_list, reverse=True, key=lambda tup: tup[1])
def db_get_games(username):
c = conn.cursor()
games = c.execute("""SELECT g.game_name, xmg.launch_count FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
INNER JOIN members m ON
m.member_id = xmg.member_id
WHERE m.member_name COLLATE nocase = ?;""", (username,)).fetchall()
games_list = {}
for game in games:
games_list[game[0]] = game[1]
return games_list
def db_get_games_list(limit):
c = conn.cursor()
games_list = c.execute("""SELECT g.game_name, count(DISTINCT xmg.member_id)
FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
Group By xmg.game_id
Order By COUNT(DISTINCT xmg.member_id) DESC
LIMIT ?""", (limit,)).fetchall()
return games_list
def db_add_game(member_id, game_name):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
games = c.execute("SELECT game_id FROM games WHERE game_name = ?;", (game_name,)).fetchone()
db_game_id = 0
if not games:
log("Adding Game: {}".format(game_name,))
c.execute("INSERT INTO games(game_name) VALUES(?);", (game_name,))
conn.commit()
db_game_id = c.execute("select last_insert_rowid();").fetchone()[0]
else:
db_game_id = games[0]
#log("DB Game ID: {}".format(db_game_id,))
member_games = c.execute("SELECT launch_count FROM xmember_games WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id)).fetchone()
if not member_games:
#log("Inserting Member Games: {}, {}".format(db_game_id, member_id))
c.execute("INSERT INTO xmember_games(game_id, member_id, launch_count) VALUES(?, ?, 1);", (db_game_id, member_id))
conn.commit()
else:
#log("Updating Member Games: {}, {}".format(db_game_id, member_id))
c.execute("UPDATE xmember_games SET launch_count = launch_count + 1 WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id))
conn.commit()
def db_get_all_members():
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
results = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members;").fetchall()
member_conn.close()
members_list = []
for member in results:
members_list.append(dict_factory(c, member))
return members_list
def db_get_member(discord_id=None, username=None):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
result = None
if discord_id:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE discord_id = ?;", (discord_id,)).fetchone()
if username:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE member_name = ?;", (username,)).fetchone()
member_conn.close()
return dict_factory(c, result)
def db_create_member(member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
c.execute("""INSERT INTO members (member_name, discord_id, discord_mention,
is_afk, afk_at, status, prev_status,
status_change_at, current_game)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);""", (member.name.lower(),
member.id, member.mention(),
0, datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
'online', 'offline',
datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
member.game_id))
conn.commit()
if member.game_id != None:
db_add_game(db_get_member(member.id)['member_id'], member.game_id)
def db_update_member(member, db_member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
db_member_id = db_member['member_id']
db_membername = db_member['member_name']
status = db_member['status']
prev_status = db_member['prev_status']
c = conn.cursor()
if member.name.lower() != db_membername:
log("Member Name changed! {} to {}".format(byteify(db_membername), byteify(member.name.lower())))
c.execute("UPDATE members SET member_name = ? WHERE discord_id = ?;", (member.name.lower(), member.id,))
conn.commit()
aliases = c.execute("SELECT * FROM aliases WHERE alias_name = ? AND member_id = ?;", (db_membername, db_member_id)).fetchone()
log("Alias list for user: {}".format(aliases))
if aliases == None:
log("creating new alias: {}, {}".format(byteify(db_membername), db_member_id))
c.execute("INSERT INTO aliases (alias_name, member_id) VALUES (?, ?);", (db_membername, db_member_id))
conn.commit()
if member.status == 'idle':
afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
is_afk = True
else:
is_afk = False
status_change_at = None
if status != member.status:
prev_status = status
status = member.status
status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
if is_afk:
#log("is afk")
c.execute("""UPDATE members
SET is_afk = ?, afk_at = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (1, afk_at, status, prev_status, status_change_at, member.id))
conn.commit()
else:
#log("is not afk")
c.execute("""UPDATE members
SET is_afk = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (0, status, prev_status, status_change_at, member.id))
conn.commit()
c.execute("UPDATE members SET current_game = ? WHERE discord_id = ?;", (member.game_id, member.id))
conn.commit()
#log("Member: {} \nMember GameID: {} db Game id: {}".format(member, member.game_id, db_member['current_game']))
if member.game_id != None and member.game_id != db_member['current_game']:
db_add_game(db_member['member_id'], member.game_id)
\ No newline at end of file
No preview for this file type
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import discord
......@@ -11,6 +12,7 @@ import logging
import traceback
import sys
import wikipedia
from subprocess import call
from dateutil.parser import parse
......@@ -23,16 +25,12 @@ from nltk.tag import pos_tag
import wolframalpha
import sqlite3
from blackjack import Blackjack
import data
VERSION = 1.6
VERSION = 2.0
conn = sqlite3.connect('db.sqlite3')
member_status = 'members.json'
deliveries_file = 'deliveries.json'
# fortune_file = 'fortunes.json'
# joke_file = 'jokes.json'
games_file = 'games.json'
credentials = 'creds.json'
muted_until = datetime.datetime.now()
......@@ -81,7 +79,7 @@ def search_youtube(query):
query_string = {"search_query" : query}
r = requests.get("http://www.youtube.com/results", params=query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', r.content)
print("http://www.youtube.com/watch?v=" + search_results[0])
log("http://www.youtube.com/watch?v=" + search_results[0])
return "http://www.youtube.com/watch?v=" + search_results[0]
def search_google_images(query, animated=False):
......@@ -99,281 +97,10 @@ def search_google_images(query, animated=False):
search_result = search_result[:search_result.find('/revision/')]
if '%' in search_result:
search_result = search_result[:search_result.find('%')]
print(search_result)
log(search_result)
return search_result
return "boo you fail.."
##################
## Database Calls
##################
# Converts a row into a dictionary
def dict_factory(cursor, row):
if row == None:
return None
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def db_get_credit(member_id):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if credits:
return credits[0]
def db_buy_ticket(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits, tickets FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) - int(100*amount) < 0:
return False, "You do not have enough credits to purchase a ticket. Credits: {} Tickets: {}".format(credits[0], credits[1])
c = conn.cursor()
cost = int(100 * amount)
c.execute("""UPDATE members SET credits = credits - ?, tickets = tickets + ?
WHERE member_id = ?;""", (cost, amount, member_id))
conn.commit()
return True, int(credits[1]) + int(amount)
def db_update_credit(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) + int(amount) < 0:
return False, "You do not have enough credits to cover amount requested. Credit: {} Amount Requested: {}".format(credits[0], amount)
if int(credits[0]) < 0:
c.execute("""UPDATE members SET credits = 0
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
c.execute("""UPDATE members SET credits = credits + ?
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
return True, ""
def db_add_minigame(member_id, minigame_name, state):
c = conn.cursor()
db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if not db_state:
c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
VALUES(?, ?, ?);""", (member_id, minigame_name, state))
conn.commit()
else:
c.execute("""UPDATE minigames SET state = ?
WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
conn.commit()
def db_get_minigame_state(member_id, minigame_name):
c = conn.cursor()
state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if state:
return state[0]
def db_delete_minigame_state(member_id, minigame_name):
c = conn.cursor()
c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
conn.commit()
def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
c = conn.cursor()
c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
VALUES(?, ?, ?, ?, ?, ?);""", (message, delivery_time, channel, message_from, message_to, user_id))
conn.commit()
def db_delete_sent_message(message_id):
c = conn.cursor()
c.execute("DELETE FROM messages WHERE message_id = ?;", (message_id,))
conn.commit()
def db_get_aliases(member_id):
c = conn.cursor()
aliases = c.execute("SELECT alias_name FROM aliases WHERE member_id = ?;", (member_id,)).fetchall()
if aliases:
alias_list = []
for alias in aliases:
alias_list.append(alias[0])
return alias_list
else:
return None
def db_add_aliases(member_id, alias_name):
c = conn.cursor()
c.execute("INSERT INTO aliases(alias_name, member_id) VALUES (?, ?);", (alias_name, member_id,))
conn.commit()
def db_get_messages():
msg_conn = sqlite3.connect('db.sqlite3')
c = msg_conn.cursor()
messages = c.execute("SELECT * FROM messages WHERE datetime('now') >= datetime( replace(delivery_time, '/', '-'));").fetchall()
if messages:
db_messages = []
for message in messages:
db_messages.append(dict_factory(c, message))
else:
db_messages = None
msg_conn.close()
return db_messages
def db_get_whoplayed(game_name):
c = conn.cursor()
members = c.execute("""SELECT m.member_name, xmg.launch_count
FROM members m
INNER JOIN xmember_games xmg ON
m.member_id = xmg.member_id
INNER JOIN games g ON
g.game_id = xmg.game_id
WHERE g.game_name COLLATE nocase = ?
Order By xmg.launch_count, m.member_name DESC;""", (game_name,)).fetchall()
member_list = {}
for member in members:
member_list[member[0]] = member[1]
#log(member_list)
return sorted(member_list.items(), reverse=True, key=operator.itemgetter(1))
#return sorted(member_list, reverse=True, key=lambda tup: tup[1])
def db_get_games(username):
c = conn.cursor()
games = c.execute("""SELECT g.game_name, xmg.launch_count FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
INNER JOIN members m ON
m.member_id = xmg.member_id
WHERE m.member_name COLLATE nocase = ?;""", (username,)).fetchall()
games_list = {}
for game in games:
games_list[game[0]] = game[1]
return games_list
def db_get_games_list(limit):
c = conn.cursor()
games_list = c.execute("""SELECT g.game_name, count(DISTINCT xmg.member_id)
FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
Group By xmg.game_id
Order By COUNT(DISTINCT xmg.member_id) DESC
LIMIT ?""", (limit,)).fetchall()
return games_list
def db_add_game(member_id, game_name):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
games = c.execute("SELECT game_id FROM games WHERE game_name = ?;", (game_name,)).fetchone()
db_game_id = 0
if not games:
log("Adding Game: {}".format(game_name,))
c.execute("INSERT INTO games(game_name) VALUES(?);", (game_name,))
conn.commit()
db_game_id = c.execute("select last_insert_rowid();").fetchone()[0]
else:
db_game_id = games[0]
#log("DB Game ID: {}".format(db_game_id,))
member_games = c.execute("SELECT launch_count FROM xmember_games WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id)).fetchone()
if not member_games:
#log("Inserting Member Games: {}, {}".format(db_game_id, member_id))
c.execute("INSERT INTO xmember_games(game_id, member_id, launch_count) VALUES(?, ?, 1);", (db_game_id, member_id))
conn.commit()
else:
#log("Updating Member Games: {}, {}".format(db_game_id, member_id))
c.execute("UPDATE xmember_games SET launch_count = launch_count + 1 WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id))
conn.commit()
def db_get_all_members():
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
results = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members;").fetchall()
member_conn.close()
members_list = []
for member in results:
members_list.append(dict_factory(c, member))
return members_list
def db_get_member(discord_id=None, username=None):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
result = None
if discord_id:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE discord_id = ?;", (discord_id,)).fetchone()
if username:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE member_name = ?;", (username,)).fetchone()
member_conn.close()
return dict_factory(c, result)
def db_create_member(member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
c.execute("""INSERT INTO members (member_name, discord_id, discord_mention,
is_afk, afk_at, status, prev_status,
status_change_at, current_game)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);""", (member.name.lower(),
member.id, member.mention(),
0, datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
'online', 'offline',
datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
member.game_id))
conn.commit()
if member.game_id != None:
db_add_game(db_get_member(member.id)['member_id'], member.game_id)
def db_update_member(member, db_member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
db_member_id = db_member['member_id']
db_membername = db_member['member_name']
status = db_member['status']
prev_status = db_member['prev_status']
c = conn.cursor()
if member.name.lower() != db_membername:
log("Member Name changed! {} to {}".format(byteify(db_membername), byteify(member.name.lower())))
c.execute("UPDATE members SET member_name = ? WHERE discord_id = ?;", (member.name.lower(), member.id,))
conn.commit()
aliases = c.execute("SELECT * FROM aliases WHERE alias_name = ? AND member_id = ?;", (db_membername, db_member_id)).fetchone()
log("Alias list for user: {}".format(aliases))
if aliases == None:
log("creating new alias: {}, {}".format(byteify(db_membername), db_member_id))
c.execute("INSERT INTO aliases (alias_name, member_id) VALUES (?, ?);", (db_membername, db_member_id))
conn.commit()
if member.status == 'idle':
afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
is_afk = True
else:
is_afk = False
status_change_at = None
if status != member.status:
prev_status = status
status = member.status
status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
if is_afk:
#log("is afk")
c.execute("""UPDATE members
SET is_afk = ?, afk_at = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (1, afk_at, status, prev_status, status_change_at, member.id))
conn.commit()
else:
#log("is not afk")
c.execute("""UPDATE members
SET is_afk = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (0, status, prev_status, status_change_at, member.id))
conn.commit()
c.execute("UPDATE members SET current_game = ? WHERE discord_id = ?;", (member.game_id, member.id))
conn.commit()
#log("Member: {} \nMember GameID: {} db Game id: {}".format(member, member.game_id, db_member['current_game']))
if member.game_id != None and member.game_id != db_member['current_game']:
db_add_game(db_member['member_id'], member.game_id)
#################
## Client Events
......@@ -387,62 +114,33 @@ def on_socket_raw_send(payload, binary=False):
def on_status(member):
for member in client.get_all_members():
try:
db_member = db_get_member(member.id)
db_member = data.db_get_member(member.id)
#log(db_member)
if not db_member:
log("Creating new member: {}".format(member) )
db_create_member(member)
data.db_create_member(member)
else:
#log("Updating member: {}".format(member) )
db_update_member(member, db_member)
data.db_update_member(member, db_member)
check_msg_queue()
except Exception as e:
log("Exception: {}".format(format_exception(e)))
pass
def get_game_names(game_id_list):
json_data=open(games_file).read()
data = json.loads(json_data)
result = []
for game_id in game_id_list:
if isinstance(game_id, str) and not game_id.isdigit():
result.append(game_id)
continue
name_set = False
for game in data:
if game['id'] == game_id:
result.append(game['name'])
name_set = True
return result
def get_mention_status(mention):
try:
json_data=open(member_status).read()
data = json.loads(json_data)
except ValueError:
data = {}
if not data:
data = {}
for user in data:
if 'mention' in data[user]:
if data[user]['mention'] == mention:
return data[user]
return None
def check_msg_queue():
#print("checking messages")
messages = db_get_messages()
#log("checking messages")
messages = data.db_get_messages()
if messages:
for message in messages:
try:
member = db_get_member(filter(unicode.isalnum, message['message_to']))
member = data.db_get_member(filter(unicode.isalnum, message['message_to']))
if member:
if message['message_to'] == member['discord_mention']:
print("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel']))
log("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel']))
if member['status'] == 'online':
client.send_message(Object(message['channel']), '{}, {} asked me to tell you "{}"'.format(message['message_to'], message['message_from'], message['message']))
db_delete_sent_message(message['message_id'])
data.db_delete_sent_message(message['message_id'])
except Exception as e:
log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
return
......@@ -458,7 +156,7 @@ def on_message(message):
return
if message.content.lower().startswith(client.user.name.lower()):
print('Someone is talking to %s' % (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')))
......@@ -511,8 +209,8 @@ Stuff:
if message.content.startswith('!lastseen'):
username = message.content[10:].replace('@', '').lower()
member = db_get_member(username=username)
log(member)
member = data.db_get_member(username=username)
#log(member)
if member:
out_string = ''
if member['is_afk'] == 1:
......@@ -587,7 +285,7 @@ Stuff:
limit = 20
if len(parts) > 1 and parts[1].isdigit():
limit = int(parts[1])
games_list = db_get_games_list(limit)
games_list = data.db_get_games_list(limit)
out_string = ''
for game in games_list:
......@@ -601,9 +299,9 @@ Stuff:
if message.content.startswith('!aliases'):
username = message.content[9:].replace('@', '').lower()
member = db_get_member(username=username)
member = data.db_get_member(username=username)
if member:
aliases = db_get_aliases(member['member_id'])
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:
......@@ -615,9 +313,9 @@ Stuff:
if message.content.startswith('!addalias'):
alias = message.content[10:]
username = message.author.name.lower()
member = db_get_member(username=username)
member = data.db_get_member(username=username)
if member:
db_add_aliases(member['member_id'], alias)
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...)')
......@@ -625,7 +323,7 @@ Stuff:
if message.content.startswith('!games'):
username = message.content[7:].replace('@', '').lower()
games_list = db_get_games(username)
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))
......@@ -634,7 +332,7 @@ Stuff:
if message.content.startswith('!whoplayed'):
game_name = message.content[11:]
member_list = db_get_whoplayed(game_name)
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:
......@@ -648,14 +346,14 @@ Stuff:
return
if message.content.startswith('!gimmecredits'):
member = db_get_member(message.author.id)
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 = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
if credits < 5:
amount = random.randint(5, 50)
db_update_credit(member['member_id'], amount)
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.")
......@@ -665,14 +363,14 @@ Stuff:
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 = db_get_all_members()
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 = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
if credits < 100:
db_update_credit(member['member_id'], 100)
data.db_update_credit(member['member_id'], 100)
client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
return
......@@ -680,21 +378,26 @@ Stuff:
# 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 = db_get_all_members()
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)
#log(member)
ticket_count += member['tickets']
log("Ticket Count: {}".format(ticket_count))
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(member['member_name'], int(percent))
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
client.send_message(message.channel, out_string)
return
......@@ -702,27 +405,37 @@ Stuff:
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
return
members = db_get_all_members()
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)
#log(member)
ticket_count += member['tickets']
log("Ticket Count: {}".format(ticket_count))
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['member_name']] * member['tickets']
ticket_reel += [member['discord_mention']] * member['tickets']
percent = (float(member['tickets']) / float(ticket_count)) * 100.0
out_string += "{} - {}%\n".format(member['member_name'], int(percent))
out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
winner = random.choice(ticket_reel)
out_string += "\n\n\nThe winner is....\n\n{}!".format(winner,)
client.send_message(message.channel, out_string)
while winner in ticket_reel:
ticket_reel.remove(winner)
second = random.choice(ticket_reel)
while second in ticket_reel:
ticket_reel.remove(second)
third = random.choice(ticket_reel)
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'):
......@@ -730,9 +443,11 @@ Stuff:
**1st Place**
Game: **The Witness**
Game: **Fairy Fencer F**
Description:
*Inspired by Myst, The Witness has the player explore an open world island filled with a number of natural and man-made structures. The player progresses by solving puzzles which are based on interactions with mazes presented on panels around the island.*
*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!*
http://store.steampowered.com/app/347830/
**2nd Place**
......@@ -742,28 +457,30 @@ Description:
1 Random Steam Key
Raffle Date: **1/29/2016**
Raffle Date: **2/2/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 = db_get_member(message.author.id)
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 = db_buy_ticket(member['member_id'], 1)
result, response = data.db_buy_ticket(member['member_id'], 1)
if not result:
client.send_message(message.author, response)
return
credits = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
return
if message.content.startswith('!balance'):
member = db_get_member(message.author.id)
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:
......@@ -790,7 +507,7 @@ Max Bet: 10 credits
To Play: !slots <bet>""")
return
if message.content.startswith('!slots'):
member = db_get_member(message.author.id)
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
......@@ -803,7 +520,10 @@ To Play: !slots <bet>""")
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 = db_update_credit(member['member_id'], -int(bet_amount))
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:']
......@@ -838,30 +558,32 @@ To Play: !slots <bet>""")
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 = db_update_credit(member['member_id'], winnings)
result, error_message = data.db_update_credit(member['member_id'], winnings)
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
log(out_string)
#log(out_string)
client.send_message(message.author, out_string)
return
if message.content.startswith('!hit') or message.content.startswith('!draw'):
member = db_get_member(message.author.id)
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 = db_get_minigame_state(member['member_id'], 'blackjack')
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
......@@ -870,18 +592,19 @@ To Play: !slots <bet>""")
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
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,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(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 = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
......@@ -891,13 +614,13 @@ To Play: !slots <bet>""")
return
if message.content.startswith('!stay') or message.content.startswith('!stand'):
member = db_get_member(message.author.id)
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 = db_get_minigame_state(member['member_id'], 'blackjack')
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
......@@ -905,24 +628,25 @@ To Play: !slots <bet>""")
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(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 = db_get_credit(member['member_id'])
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 = db_get_member(message.author.id)
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 = db_get_minigame_state(member['member_id'], 'blackjack')
state = data.db_get_minigame_state(member['member_id'], 'blackjack')
if state:
client.send_message(message.author, "You are already playing a game!")
......@@ -932,17 +656,18 @@ To Play: !slots <bet>""")
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
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,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(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 = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
......@@ -957,7 +682,7 @@ To Play: !slots <bet>""")
client.send_message(message.author, "Please provide a bet amount. !bet 10")
return
result, error_message = db_update_credit(member['member_id'], -int(bet_amount))
result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
if not result:
client.send_message(message.author, error_message)
return
......@@ -967,17 +692,18 @@ To Play: !slots <bet>""")
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
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,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(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 = db_get_credit(member['member_id'])
credits = data.db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
......@@ -986,13 +712,6 @@ To Play: !slots <bet>""")
# !msg joe in 5 minutes YOU ARE A DICK
if message.content.startswith('!msg'):
try:
json_data=open(deliveries_file).read()
data = json.loads(json_data)
except ValueError:
data = {}
if not data:
data = {}
channel = message.channel
author = message.author
#author = message.author.name
......@@ -1026,7 +745,7 @@ To Play: !slots <bet>""")
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():
print("MEMBER: %s" % member)
log("MEMBER: %s" % member)
if username.lower() == member.name.lower():
user_mention = member.mention()
user_id = member.id
......@@ -1036,18 +755,14 @@ To Play: !slots <bet>""")
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}
print("Message: %s" % message)
db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
# data[user_mention] = {}
# data[user_mention][author.mention()] = message
# jdata = json.dumps(data, ensure_ascii=False)
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
# open(deliveries_file, 'wb+').write(jdata.encode('utf8'))
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:
......@@ -1065,9 +780,9 @@ To Play: !slots <bet>""")
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
print("Added fortune")
log("Added fortune")
except Exception as e:
print e.message
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()))
......@@ -1078,9 +793,9 @@ To Play: !slots <bet>""")
try:
c = conn.cursor()
fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
print(fortune)
log(fortune)
except Exception as e:
print(e)
log(e)
pass
if not fortune:
client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
......@@ -1106,14 +821,14 @@ To Play: !slots <bet>""")
proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
wiki_search = " ".join(proper_nouns)
if wiki_search.strip() != "":
print "Looking up {}".format(wiki_search)
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:
print(format_exception(e))
log(format_exception(e))
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
......@@ -1127,9 +842,9 @@ To Play: !slots <bet>""")
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
print("Added joke")
log("Added joke")
except Exception as e:
print e.message
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()))
......@@ -1140,9 +855,9 @@ To Play: !slots <bet>""")
try:
c = conn.cursor()
joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
print(joke)
log(joke)
except Exception as e:
print(e)
log(e)
pass
if not joke:
client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
......@@ -1162,16 +877,22 @@ To Play: !slots <bet>""")
if message.content.startswith('!hello'):
client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))
if message.content.startswith('!deal'):
client.send_message(message.channel, 'You get {}!'.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"])
@client.event
def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
log('Logged in as')
log(client.user.name)
log(client.user.id)
log('------')
for member in client.get_all_members():
if member.id == '78767557628133376':
client.send_message(member, "Bot Started")
check_msg_queue()
retries = 0
......@@ -1185,6 +906,7 @@ while retries < 1000:
except KeyboardInterrupt:
conn.close
quit()
except:
except Exception as e:
retries += 1
print("Shit I crashed: Retry %s" % (retries,))
log("Shit I crashed: {}\nRetry {}".format(e, retries))
#time.sleep(1)
......
......@@ -119,7 +119,7 @@ class Pankration:
return monster_list
def hunt_monster(self, zone):
if random.randint(1, 100) > FIND_PERCENTAGE:
if random.randint(1, 100) < FIND_PERCENTAGE:
return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!",
random.choice(self.get_monsters(zone)))
else:
......