def enterGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] sameNameExists = False players = [parsePlayer(i) for i in db.fetchall('SELECT name, handJSON FROM players WHERE gameId = %d; ' % gameId)] for player in players: if player['name'] == name: sameNameExists = True send({ 'error': { 'event': 'enterGame', 'reason': 'same name exists' } }, json=True) break if not sameNameExists: db.execute("INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)] gameMsg.message['elements']['messages'] = messages send({ 'event': 'enterGame', 'message' : gameMsg.message, 'game': game }, json=True)
def resumeGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] players = db.fetchall("SELECT name FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) if len(players) != 0: game = getGame(db, gameId) gameMsg.buildResumeGame() send({ 'event': 'resumeGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)] gameMsg.message['elements']['messages'] = messages send({ 'event': 'resumeGame', 'message' : gameMsg.message, 'game': game }, json=True) else: send({ 'error': { 'event': 'resumeGame', 'reason': 'no player with name exists' } }, json=True)
def enterGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] sameNameExists = False players = [ parsePlayer(i) for i in db.fetchall( 'SELECT name, handJSON FROM players WHERE gameId = %d; ' % gameId) ] for player in players: if player['name'] == name: sameNameExists = True send( { 'error': { 'event': 'enterGame', 'reason': 'same name exists' } }, json=True) break if not sameNameExists: db.execute( "INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [ parseMessage(i) for i in db.fetchall( "SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId) ] gameMsg.message['elements']['messages'] = messages send({ 'event': 'enterGame', 'message': gameMsg.message, 'game': game }, json=True)
def resumeGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] players = db.fetchall( "SELECT name FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) if len(players) != 0: game = getGame(db, gameId) gameMsg.buildResumeGame() send({ 'event': 'resumeGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [ parseMessage(i) for i in db.fetchall( "SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId) ] gameMsg.message['elements']['messages'] = messages send({ 'event': 'resumeGame', 'message': gameMsg.message, 'game': game }, json=True) else: send( { 'error': { 'event': 'resumeGame', 'reason': 'no player with name exists' } }, json=True)
async def logUser(m, state): # Attempt to generate user object userid = ul.parse_mention(m) if userid == None: if state == LogTypes.NOTE: await m.channel.send("I wasn't able to understand that message: `$note USER`") else: await m.channel.send("I wasn't able to understand that message: `$log USER`") return # Calculate value for 'num' category in database # For warns, it's the newest number of warns, otherwise it's a special value if state == LogTypes.WARN: count = db.get_warn_count(userid) else: count = state.value currentTime = datetime.datetime.utcnow() # Attempt to fetch the username for the user username = ul.fetch_username(m.guild, userid) if username == None: username = "******" + str(userid) await m.channel.send("I wasn't able to find a username for that user, but whatever, I'll do it anyway.") # Generate log message, adding URLs of any attachments content = utils.combineMessage(m) mes = utils.parseMessage(content, username) # If they didn't give a message, abort if mes == "": await m.channel.send("Please give a reason for why you want to log them.") return # Update records for graphing import visualize if state == LogTypes.BAN: visualize.updateCache(m.author.name, (1, 0), utils.formatTime(currentTime)) elif state == LogTypes.WARN: visualize.updateCache(m.author.name, (0, 1), utils.formatTime(currentTime)) elif state == LogTypes.UNBAN: await m.channel.send("Removing all old logs for unbanning") db.clear_user_logs(userid) # Generate message for log channel globalcount = db.get_dbid() new_log = db.UserLogEntry(globalcount + 1, userid, username, count, currentTime, mes, m.author.name, None) logMessage = str(new_log) await m.channel.send(logMessage) # Send ban recommendation, if needed if (state == LogTypes.WARN and count >= config.WARN_THRESHOLD): await m.channel.send("This user has received {} warnings or more. It is recommended that they be banned.".format(config.WARN_THRESHOLD)) logMesID = 0 # If we aren't noting, need to also write to log channel if state != LogTypes.NOTE: # Post to channel, keep track of message ID try: chan = discord.utils.get(m.guild.channels, id=config.LOG_CHAN) logMes = await chan.send(logMessage) logMesID = logMes.id except discord.errors.InvalidArgument: await m.channel.send("The logging channel has not been set up in `config.json`. In order to have a visual record, please specify a channel ID.") try: # Send a DM to the user u = ul.fetch_user(m.guild, userid) if u != None: DMchan = u.dm_channel # If first time DMing, need to create channel if DMchan == None: DMchan = await u.create_dm() # Only send DM when specified in configs if state == LogTypes.BAN and config.DM_BAN: await DMchan.send("Hi there! You've been banned from the Stardew Valley Discord for violating the rules: `{}`. If you have any questions, you can send a message to the moderators via the sidebar at <https://www.reddit.com/r/StardewValley>, and they'll forward it to us.".format(mes)) elif state == LogTypes.WARN and config.DM_WARN: await DMchan.send("Hi there! You received warning #{} in the Stardew Valley Discord for violating the rules: `{}`. Please review <#445729591533764620> and <#445729663885639680> for more info. If you have any questions, you can reply directly to this message to contact the staff.".format(count, mes)) elif state == LogTypes.KICK and config.DM_BAN: await DMchan.send("Hi there! You've been kicked from the Stardew Valley Discord for violating the following reason: `{}`. If you have any questions, you can send a message to the moderators via the sidebar at <https://www.reddit.com/r/StardewValley>, and they'll forward it to us.".format(mes)) # Exception handling except discord.errors.HTTPException as e: await m.channel.send("ERROR: While attempting to DM, there was an unexpected error. Tell aquova this: {}".format(e)) except Exception as e: await m.channel.send( "ERROR: An unexpected error has occurred. Tell aquova this: {}".format(e)) # Update database new_log.message_url = logMesID db.add_log(new_log)
async def removeError(m, edit): userid = ul.parse_mention(m) if userid == None: if edit: await m.channel.send("I wasn't able to understand that message: `$remove USER [num] new_message`") else: await m.channel.send("I wasn't able to understand that message: `$remove USER [num]`") return username = ul.fetch_username(m.guild, userid) if username == None: username = str(userid) # If editing, and no message specified, abort. mes = utils.parseMessage(m.content, username) if mes == "": if edit: await m.channel.send("You need to specify an edit message") return else: mes = "0" try: index = int(mes.split()[0]) - 1 mes = utils.strip(mes) except (IndexError, ValueError): index = -1 # Find most recent entry in database for specified user search_results = db.search(userid) # If no results in database found, can't modify if search_results == []: await m.channel.send("I couldn't find that user in the database") # If invalid index given, yell elif (index > len(search_results) - 1) or index < -1: await m.channel.send("I can't modify item number {}, there aren't that many for this user".format(index + 1)) else: item = search_results[index] import visualize if edit: if item.log_type == LogTypes.NOTE.value: currentTime = datetime.datetime.utcnow() item.timestamp = currentTime item.log_message = mes item.staff = m.author.name db.add_log(item) out = "The log now reads as follows:\n{}\n".format(str(item)) await m.channel.send(out) return else: await m.channel.send("You can only edit notes for now") return # Everything after here is deletion db.remove_log(item.dbid) out = "The following log was deleted:\n" out += str(item) if item.log_type == LogTypes.BAN: visualize.updateCache(item.staff, (-1, 0), utils.formatTime(item.timestamp)) elif item.log_type == LogTypes.WARN: visualize.updateCache(item.staff, (0, -1), utils.formatTime(item.timestamp)) await m.channel.send(out) # Search logging channel for matching post, and remove it try: if item.message_url != 0: chan = discord.utils.get(m.guild.channels, id=config.LOG_CHAN) m = await chan.fetch_message(item.message_url) await m.delete() # Print message if unable to find message to delete, but don't stop except discord.errors.HTTPException as e: print("Unable to find message to delete: {}", str(e))